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 by 33Charlie on 18 May 2017 - 07:36

Quote

I must say it was hard to find your page in google.

You write interesting posts but you should rank your page higher in search engines.

If you don’t know how to do it search on youtube:

how to rank a website Marcel’s way

#2 by

mohammadon 15 April 2017 - 17:39Quote

hi

need angle in 3 axis .

in two axis i can get it with mix giro data and accelerometer data but in yaw axis i need help

i need to Integral 3 axis to get angle

its my email please help me

ty

#3 by

Alekskon 19 December 2016 - 01:00Quote

kalman filter code for MPU6050 IMU sensor

http://www.jarzebski.pl/arduino/rozwiazania-i-algorytmy/odczyty-pitch-roll-oraz-filtr-kalmana.html

#4 by

Gökhanon 13 December 2016 - 12:31Quote

Hi. i need a kalman filter code for MPU6050 IMU sensor.Please help me.I can’t writing code a kalman filter.

#5 by

Ahmedon 3 December 2016 - 11:56Quote

i need complementary filter code for GY-85 9DOF IMU sensor

Regards,

#6 by

Richard Payneon 12 May 2016 - 20:46Quote

I would like this code to try out, much appericated.

#7 by

nagaon 25 February 2016 - 14:05Quote

i need filter codes for gy85

‘

#8 by

Jim Remingtonon 31 January 2016 - 05:45Quote

Although this post is rather old, continued interest in it compels me to point out a problem. The Kalman filter used here for comparison seems to work, but it is simply wrong. An explanation for several of its problems and an alternative that works well is presented at http://home.earthlink.net/~schultdw/bbot/bbot.html

For anyone interested to learn the theory, I recommend an excellent text book entitled “Optimal State Estimation” by Dan Simon. Note: I have no connection with any of the authors.

#9 by

dddon 14 December 2015 - 15:10Quote

Thanks for information. I want to apply this filters to one dimensional data like temperature or pressure. How can i apply this.

#10 by

Yangon 2 October 2015 - 23:06Quote

I think there may be a big problem with deriving angle/heading by accelerometer data (which is used as the z- measurements in this Kalman example).

it accumulates current angle by integrating angle changes, which angle change is derived from v_x , v_y changes. but if you just spin around the exact point of the accelerometer, you get dv_x = 0 and dv_y = 0, but apparently the angle change is not zero

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

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

#11 by Boston magician on 6 September 2014 - 11:22

Quote

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

#12 by

Elijahon 30 June 2014 - 11:52Quote

Hello,

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

Thanks.

Regards.

#13 by

Animeshon 16 June 2014 - 19:50Quote

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??

#14 by

robottinion 16 June 2014 - 20:48Quote

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

#15 by

harion 14 May 2014 - 13:56Quote

Hi Bro:)

Good job,

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

please,send your code…

thanks in advance

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

#16 by

TARIKU w/TSADIKon 23 March 2014 - 15:44Quote

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

#17 by

Ali Hamzaon 2 February 2014 - 17:21Quote

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.

#18 by

Ericon 23 December 2013 - 10:02Quote

我想回覆#20 by Pablopaolus

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

Here is the equation:

http://ppt.cc/oY1M

http://ppt.cc/7sc~

thx~ 😀

#19 by

kevanon 12 November 2013 - 17:24Quote

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?

#20 by

robottinion 12 November 2013 - 10:31Quote

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.

#21 by

kevanon 12 November 2013 - 09:13Quote

no sir, i’m using serial 1200.

it’s make value of the sensor just 0?

#22 by

kevanon 7 November 2013 - 14:55Quote

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

#23 by

robottinion 7 November 2013 - 15:03Quote

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

#24 by siddharth on 28 October 2013 - 12:44

Quote

Dear Sir,

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

#25 by

robottinion 28 October 2013 - 12:48Quote

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

#26 by siddharth on 28 October 2013 - 12:43

Quote

Dear Sir,

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

I will be very thankfulto you.

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

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

#27 by

irinaon 13 June 2013 - 21:37Quote

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

#28 by

Tjaarton 10 June 2013 - 21:17Quote

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!

#29 by

Pablopaoluson 27 May 2013 - 16:29Quote

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.

#30 by

robottinion 3 May 2013 - 07:48Quote

Thanks Morten, now the link works.

#31 by

Mortenon 2 May 2013 - 18:25Quote

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?

#32 by

Someoneon 30 January 2013 - 09:13Quote

Okay, I can see that. Thanks

#33 by

Someoneon 30 January 2013 - 05:47Quote

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

#34 by

robottinion 30 January 2013 - 08:39Quote

At the bottom of the post the complete source code

#35 by

robottinion 19 January 2013 - 10:16Quote

At the bottom of the post the complete source code

#36 by

kamalon 19 January 2013 - 09:57Quote

Dear , can u send me to code

#37 by

jjon 1 January 2013 - 11:34Quote

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

#38 by

robottinion 1 January 2013 - 13:03Quote

Yes, i put the code in the post.

#39 by

phuongnuton 12 December 2012 - 16:21Quote

I want to try it.

Send to me complete source code pls!

#40 by

robottinion 12 December 2012 - 17:50Quote

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

#41 by

Izberton 11 December 2012 - 03:56Quote

Can i also get a copy of this source code?

#42 by

tantunon 7 December 2012 - 15:14Quote

can you send to me complete source code?

#43 by

ducation 7 December 2012 - 00:54Quote

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!

#44 by

xwon 6 December 2012 - 22:35Quote

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

#45 by

robottinion 3 December 2012 - 21:27Quote

I sent you an email with the code

#46 by

Iwanon 3 December 2012 - 19:55Quote

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

#47 by

Iwanon 21 November 2012 - 05:40Quote

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

#48 by

robottinion 21 November 2012 - 06:02Quote

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