Note: At the bottom of the post the complete source code

The use of accelerometer and gyroscope to build little robots, such as the self-balancing, requires a math filter in order to merge the signals returned by the sensors.

The gyroscope has a drift and in a few time the values returned are completely wrong. The accelerometer, from the other side, returns a true value when the acceleration is progressive but it suffers much the vibrations, returning values of the angle wrong.

Usually a math filter is used to mix and merge the two values, in order to have a correct value: the Kalman filter . This is the best filter you can use, even from a theoretical point of view, since it is one that minimizes the errors from the true signal value. However it is very difficult (see here) to understand. In fact, the filter needs to be able to calculate the coefficients of the matrices, the process-based error, measurement error, etc. that are not trivial.

In the hobbistic world, recently are emerging other filters, called **complementary filters**. In fact, they manage both high-pass and low-pass filters simultaneously. The low pass filter filters high frequency signals (such as the accelerometer in the case of vibration) and low pass filters that filter low frequency signals (such as the drift of the gyroscope). By combining these filters, you get a good signal, without the complications of the Kalman filter.

Making a study from a theoretical point of view, the discussion is complicated and is beyond the scope of this tutorial. The complementary filters can be have different ‘orders’. Here I speak about the so-called first-order filter that filter already well, and the second-order filter which filter even better. Clearly, going from first to second order, the algorithm is more complicated to use and perhaps there is no gain so obvious to justify the increase in complexity.

A great introduction to the first order complementary filters applied to the an accelerometer and a gyroscope, comes from MIT (here). It introduces the filter in a a very simple mode. On this document is based the first Arduino algorithm:

// a=tau / (tau + loop time) // newAngle = angle measured with atan2 using the accelerometer // newRate = angle measured using the gyro // looptime = loop time in millis() float tau=0.075; float a=0.0; float Complementary(float newAngle, float newRate,int looptime) { float dtC = float(looptime)/1000.0; a=tau/(tau+dtC); x_angleC= a* (x_angleC + newRate * dtC) + (1-a) * (newAngle); return x_angleC; }

It ‘enough to choose the response time of *tau*, to send the arguments, ie the angle measured with the accelerometer and the gyroscope, the time of the loop and you get in two lines, the angle calculated by the filter.

The algorithm at the base of the second order complementary filter is described here. Indeed it is not described at all, but now we’ve figured out how the filter works by the MIT’s documentation. The principle is the same, the algorithm is more complicated. The translation of this algorithm for the Arduino:

// newAngle = angle measured with atan2 using the accelerometer // newRate = angle measured using the gyro // looptime = loop time in millis() float Complementary2(float newAngle, float newRate,int looptime) { float k=10; float dtc2=float(looptime)/1000.0; x1 = (newAngle - x_angle2C)*k*k; y1 = dtc2*x1 + y1; x2 = y1 + (newAngle - x_angle2C)*2*k + newRate; x_angle2C = dtc2*x2 + x_angle2C; return x_angle2C; }

Here too we just have to set the *k* and magically we get the angle.

If we want to apply the Kalman filter, we can re-use one of the codes already present in internet. This is the code that I copied from the Arduino forum (here):

// KasBot V1 - Kalman filter module float Q_angle = 0.01; //0.001 float Q_gyro = 0.0003; //0.003 float R_angle = 0.01; //0.03 float x_bias = 0; float P_00 = 0, P_01 = 0, P_10 = 0, P_11 = 0; float y, S; float K_0, K_1; // newAngle = angle measured with atan2 using the accelerometer // newRate = angle measured using the gyro // looptime = loop time in millis() float kalmanCalculate(float newAngle, float newRate,int looptime) { float dt = float(looptime)/1000; x_angle += dt * (newRate - x_bias); P_00 += - dt * (P_10 + P_01) + Q_angle * dt; P_01 += - dt * P_11; P_10 += - dt * P_11; P_11 += + Q_gyro * dt; y = newAngle - x_angle; S = P_00 + R_angle; K_0 = P_00 / S; K_1 = P_10 / S; x_angle += K_0 * y; x_bias += K_1 * y; P_00 -= K_0 * P_00; P_01 -= K_0 * P_01; P_10 -= K_1 * P_00; P_11 -= K_1 * P_01; return x_angle; }

To get the answer, you have to set 3 parameters: *Q_angle, R_angle,R_gyro*. The activity is a bit complicated .

But what happens with these algorithms? Similar curves are obtained? Here’s a comparison:

There are 5 curves:

Color lines:

- Red – accelerometer
- Green – Gyro
- Blue – Kalman filter
- Black – complementary filter
- Yellow – the second order complementary filter

As you can see the signals filtered are very similarly. Note that in the presence of vibrations, the accelerometer (red) generally go crazy. The gyro (green) has a very strong drift increasing int the time.

Now let’s see a comparison only between a filtered signal. That kalman (green), complementary (black) and complementary second-order (yellow). You can see how the Kalman is a bit late vs complementary filters, but it is more responsive to the vibration. In this case the second order filter does not return an ideal curve, probably I have to work a bit on the coefficients.

In conclusion I think that the complementary filter, in this case the first order, can be used in place of the Kalman filter. The smoothing is good and the algorithm is much simpler than Kalman.

The hardware I used was composed of:

– Arduino 2009

– 6-axis IMU SparkFun Razor 6 DOF

#1 da

Iwanil 21 novembre 2012 - 05:40Cita

how do you display the graph the results of Kalman and complementary?

This chart comes from the hardware or the results of the simulation matlab?

Tell me please,

Regard,

Iwan

#2 da

robottiniil 21 novembre 2012 - 06:02Cita

No Matlab simulation. They are the hardware results. The code is included in the post.

#3 da

Iwanil 3 dicembre 2012 - 19:55Cita

can you give me a complete source code? I want to try it..

#4 da

robottiniil 3 dicembre 2012 - 21:27Cita

I sent you an email with the code

#5 da

xwil 6 dicembre 2012 - 22:35Cita

can you give me a complete source code? I want to try it..

#6 da

ducatiil 7 dicembre 2012 - 00:54Cita

nice post!

I, too, am interested in how you collect the data for the graph.

if possible, please send me the code.

ciao e grazie mille!

#7 da

tantunil 7 dicembre 2012 - 15:14Cita

can you send to me complete source code?

#8 da

Izbertil 11 dicembre 2012 - 03:56Cita

Can i also get a copy of this source code?

#9 da

phuongnutil 12 dicembre 2012 - 16:21Cita

I want to try it.

Send to me complete source code pls!

#10 da

robottiniil 12 dicembre 2012 - 17:50Cita

FOR ALL: I put the source code in the post. please take it if you need

#11 da

jjil 1 gennaio 2013 - 11:34Cita

Are the codes that you post are all complete source codes? If not can I have them? Thanks

#12 da

robottiniil 1 gennaio 2013 - 13:03Cita

Yes, i put the code in the post.

#13 da

kamalil 19 gennaio 2013 - 09:57Cita

Dear , can u send me to code

#14 da

robottiniil 19 gennaio 2013 - 10:16Cita

At the bottom of the post the complete source code

#15 da

Someoneil 30 gennaio 2013 - 05:47Cita

Can you send a completed code to me? I want to try it since I do not have any experience about that. Thanks

#16 da

robottiniil 30 gennaio 2013 - 08:39Cita

At the bottom of the post the complete source code

#17 da

Someoneil 30 gennaio 2013 - 09:13Cita

Okay, I can see that. Thanks

#18 da

Mortenil 2 maggio 2013 - 18:25Cita

Hi, when I click on Filters1 for downloading the source code I just get redirected to this page.

Is it possible to repost the source code?

#19 da

robottiniil 3 maggio 2013 - 07:48Cita

Thanks Morten, now the link works.

#20 da

Pablopaolusil 27 maggio 2013 - 16:29Cita

Hello,

Thank you for sharing your job

I’m using PIC18F46J50 as MCU along with Sparkfun IMU – 6DOF ITG3200/ADXL345, and I’m trying to combine accelerometer and giroscope data using the first order complementary filter. I’ve ported your code (to CCS v4.140). It seems to work well enough within an angle range. However, if I tilt for instance pitch angle to 90 or -90 deg, roll angle goes crazy. The same occurs to pitch if I tilt roll to +-90. I don’t know if I’ve explained myself clearly, so I’ve made a video:

http://www.youtube.com/watch?v=RmqbKVueVIw

Here is my code:

float tau=0.075;

float a=0.0;

float rollAcc=0, rollGyro=0;

float pitchAcc=0, pitchGyro=0;

//RwAcc[x] in g

//Gyro[x] in deg/s

void ComplementaryFilter2() {

interval = (0.250*(float)timerCount250us)/1000.0; //Units: sec

timerCount250us = 0; //Restart the counters

rollAcc=atan2(RwAcc[1], RwAcc[2]) * 180 / PI;

pitchAcc=atan2(RwAcc[0], RwAcc[2]) * 180 / PI;

a=tau/(tau+interval);

roll = a * (roll + Gyro[0] * interval) + (1-a) * (rollAcc);

pitch = a * (pitch + Gyro[1] * interval) + (1-a) * (pitchAcc);

}

I use an internal interruption so as to calculate the interval. Timer0 overflows every 250us:

#int_TIMER0

void TIMER0_isr(void)

{

timerCount250us+=1;

set_timer0(64036);

}

Sorry for the long post.

I would greatly appreciate if you could help me.

Thank you.

#21 da

Tjaartil 10 giugno 2013 - 21:17Cita

Hello, I’m currently trying to implement a Kalman filter using the code above. After I plotted the accelerometer angle vs the Kalman angle, they seemed to be about the same. After looking through the code I found that :

x_angle += K_0 * y;

x_angle += K_0 * (newAngle – x_angle);

x_angle += (P_00 / S) * (newAngle – x_angle);

x_angle += (P_00 / (P_00 + R_angle)) * (newAngle – x_angle);

In most cases my P_00>>R_angle (sometimes maxed at about +-1800) whis basically means K_0~1 and then

x_angle = x_angle + newAngle – x_angle;

x_angle = newAngle;

Am I calculating P_00 wrong? Any help would be appreciated!

#22 da

irinail 13 giugno 2013 - 21:37Cita

Hi, I’m trying to use a ADXL345 and ITG 3200 for a platform with 3 analog servos. I need to filtrate the data from gyro and accel and using your complementary filter implementations. Hoe would the filter look like for all three axis active? thanks

Pingback: How to combine data from Gyro and Accel | solenerotech EN

Pingback: Come combinare i dati del giroscopio e dell’accelerometro | solenerotech IT

#23 da siddharth il 28 ottobre 2013 - 12:43

Cita

Dear Sir,

plz send me source code of 2 wheel balancing robot using gyro-521 and kalman filter.

I will be very thankfulto you.

#24 da siddharth il 28 ottobre 2013 - 12:44

Cita

Dear Sir,

plz send me the code of two wheel balancing robot using gyro and kalman filter.

#25 da

robottiniil 28 ottobre 2013 - 12:48Cita

Sorry the code is complex, I can’t work on it. You can find many implementations on internet about it.

#26 da

kevanil 7 novembre 2013 - 14:55Cita

sir, can you help me. why result the source code can’t look in serial monitor arduino?

#27 da

robottiniil 7 novembre 2013 - 15:03Cita

Are you using the right speed in the serial monitor (the same of Serial.begin in the code)?

#28 da

kevanil 12 novembre 2013 - 09:13Cita

no sir, i’m using serial 1200.

it’s make value of the sensor just 0?

#29 da

robottiniil 12 novembre 2013 - 10:31Cita

You have to use the same speed in the serial monitor and in the Serial.begin in the code. Please use 57600 as a value in the Serial.beglin (57600) and in the Serial monitor. This is the first point. After, we can see if there are other problems.

#30 da

kevanil 12 novembre 2013 - 17:24Cita

sir, i was changed serial begin become 57600 but the result constant 0..

i’m using accelerometer (ADXL345) and Gyroscope (ITG3200), how setting and read this sensor sir?

#31 da

Ericil 23 dicembre 2013 - 10:02Cita

我想回覆#20 by Pablopaolus

因為當在計算尤拉角的時候，當pitch在+-90度時，轉換矩陣會有奇異點的發生。

Here is the equation:

http://ppt.cc/oY1M

http://ppt.cc/7sc~

thx~

#32 da

Ali Hamzail 2 febbraio 2014 - 17:21Cita

Hi, I was looking at your code and I kinda get hold of it and understand it. However, I have a question. This code gives all the 6 axis readings. like the 3 axis of gyro and 3 axis of accelerometer. Because I am trying to implement it on my quadroter. So wanted to know if I can implement it on it.

Sorry if I dnt make too much sense as I am new to all this.

#33 da

TARIKU w/TSADIKil 23 marzo 2014 - 15:44Cita

Hi, I am tried to implement Kalman filter for noisey Gyro-accelerometer data in matlab. Is there anyone who could help me ,please?

Pingback: Still working on the Autopilot | m/v C:[ESC]

#34 da

hariil 14 maggio 2014 - 13:56Cita

Hi Bro:)

Good job,

I need your guidance to build my quadcopter with kalman filter.

please,send your code…

thanks in advance

#35 da

Animeshil 16 giugno 2014 - 19:50Cita

I tried this code on a MPU 6050 GY 521 Breakboard..When I run the code I get all values as 0..

Can U suggest me the modifications that will be required or mail me the code??

#36 da

robottiniil 16 giugno 2014 - 20:48Cita

Sorry, I don’t know the MPU6050, but you can find many tutorials with google

#37 da

Elijahil 30 giugno 2014 - 11:52Cita

Hello,

Can someone help me with the code to implement the Kalmer and complementary filter?

Thanks.

Regards.

#38 da Boston magician il 6 settembre 2014 - 11:22

Cita

I savor, result iin I discovered exactly what I was taking a look

for. You have ended my fokur day long hunt! God Bless yyou man. Have a nice day.

Bye

Pingback: Gyro Drift And What To Do About It? | paulcreaser

Pingback: Gyro Drift And What To Do About It? | paulcreaser