The Kalman filter is a very powerful tool to remove noise in data series that can be used in various engineering fields. I’ve used Kalman filter to smooth out sensor data before I display them on LCD screen or use them to control something.

As I’ve realized the versatility of Kalman filter I wrote the function below which uses Kalman filter to remove noise from ADC (analog to digital) measurement. I was able to use this function successfully to smooth out my ADC measurement specially if I need to plot or display the measurement. Here is the function below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
unsigned int Kalman_filter_for_SEN_1(signed int ADC_Value) { static unsigned char counter = 0; static float A,H,Q,R,X,P; float XP,PP; static float value_return=0; float K; float temp_float; if(counter<1) counter++; if(counter==1) { A = 1; H = 1; //1 Q = 0.32; //earlier 0.92,0.02 R = 0.8; // X = 1023; P = 6; counter = 2; XP = A*X; PP = A*P*A + Q; K = PP*H; K /=(H*H*PP)+R; temp_float = (float)(ADC_Value-H*XP); value_return = XP + K*temp_float; temp_float = H*PP; P = PP-K*temp_float; return (unsigned int)value_return; } else { XP = A*value_return; PP = A*P*A + Q; K = PP*H; K /=(H*H*PP)+R; temp_float = (float)(ADC_Value-H*XP); value_return = XP + K*temp_float; temp_float = (float)H*PP; P = PP-K*temp_float; return (unsigned int)value_return; } } |

This function takes signed int ADC value and spit out smoothed out unsigned int value. You can play with Q and R value to get desired smoothness. However beware when the results become less effected by the noise that also means your function is less responsive to fast changes of the ADC as well.

The Kalaman filter keeps record of the previous states; hence you need to have separate function for each ADC channel in case if you need more than one ADC channel. In case if you know the initial value ADC you can initialize X with that value. In case you don’t know the initial value of the ADC you can just load ADC value with number in the range(0-1023 for 10 bit) and initialize P with a larger value. In the above function I’ve made P=6 and X=1023 as I don’t exactly know the initial value of the X. The Kalman filter will start converging once it starts get readings.

I am not a genius of mathematics so I will not be able to explain Kalman filter deeply. However there are quite good resources in the internet as to how Kalman filter works. I also recommended book “Kalman Filter for Begineers : with MATLAB examples by Phil Kim” for anybody who wants to learn how to apply Kalman filter for projects. I’ve got my copy recently.

You can call this function soon after you read the ADC. Try this function and let us know how you’ve used it in your project.

## Leave a Reply