# Integrating accelerometer and gyroscope using complementary filter

Hello, i am having difficulty trying to combine accelerometer and gyroscope in matlab. I am unsure that the graph that i got is correct because the gyroscope waveform and complementary waveform is similar. Can help me check if the codings ive done is right?
This is what ive done:
X= graceAcc(:,2);
Y= graceAcc(:,3);
Z= graceAcc(:,4);

T= graceGyro(:,1);
X1= graceGyro(:,2);
Y1= graceGyro(:,3);
Z1= graceGyro(:,4);

hpf = 0.98;
lpf = 0.02;

TX = atand((X)./sqrt(Y.^2 + Z.^2));
TY = atand((Y)./sqrt(X.^2 + Z.^2));
TZ = atand(sqrt(Y.^2 + X.^2)./(Z));

X2 = 0;
Y2 = 0;
Z2 = 0;
X3 = X2 + (X1.*T);

for a = 1:length(X1)
if a == 1
X2 = ((X1.*T).*hpf) + (TX(1:110).*lpf);
Y2 = (Y1.*T).*hpf + (TY(1:110).*lpf);
Z2 = (Z1.*T).*hpf + (TZ(1:110).*lpf);
else
X2 = (X3).*hpf + (TX(1:110).*lpf);
Y2 = (Y2 + (Y1.*T)).*hpf + (TY(1:110).*lpf);
Z2 = (Z2 + (Z1.*T)).*hpf + (TZ(1:110).*lpf);
end
end
plot(TX,'g');
hold on
plot(TY,'r');
hold on
plot(TZ,'b');

title('Change in Angle of Accelerometer and Gyroscope')
xlabel('samples')
ylabel('tilt angle')
legend('Complementary filter X','Accelerometer X','Gyroscope X')

• Hi Shiqi,

It is expected that the complimentary filter produces similar, but different results when compared to the pure gyroscope data. I cannot run and check your code, but I would not make the assumption that it is wrong simply because the two produce similar results. You may want to play with the different constant settings if what you're getting is not what you're looking for.

Thanks,
Yu
• Hi Yu,
What do you mean by pure gyroscope data? Can i ask if the equation that i use for complimentary filter is correct or can provide me with the equation to combine for data together? Thanks.

• Hi Shiqi,

Pure gyroscope data means results taken from the gyroscope without adding the accelerometer data.

The equation for the complimentary filter is described in one of the blog posts I made a while back:

You should be able to find what you need there.

Thanks,
Yu
This discussion has been closed.