# BerryIMU Python Code Update – Kalman Filter and More

We have updated to the python code in our git repo.

It now includes;

• The elusive Kalman filter.
• Math needed when the IMU is upside down
• Automatically calculate loop period.

What is a Kalman filter?  In a nutshell;
A Kalman filter is, it is an algorithm which uses a series of measurements observed over time, in this context an accelerometer and a gyroscope. These measurements will contain noise that will contribute to the error of the measurement. The Kalman filter will then try to estimate the state of the system, based on the current and previous states, that tend to be more precise that than the measurements alone.

A Kalman filter is more precise than a Complementary filter. This can be seen in the image below, which is the output of a complementary filter (CFangleX) and a Kalman filter (kalmanX) from the X axis plotted in a graph.

The red line (KalmanX) is better at filtering out noisep;

The code can be found here in our Git repository here
And  can be pulled down to your Raspberry Pi with;

pi@raspberrypi ~ \$ git clone https://github.com/mwilliams03/BerryIMU.git

A summary of the code;

```
def kalmanFilterY ( accAngle, gyroRate, DT):
y=0.0
S=0.0

global KFangleY
global Q_angle
global Q_gyro
global y_bias
global XP_00
global XP_01
global XP_10
global XP_11
global YP_00
global YP_01
global YP_10
global YP_11

KFangleY = KFangleY + DT * (gyroRate - y_bias)

YP_00 = YP_00 + ( - DT * (YP_10 + YP_01) + Q_angle * DT )
YP_01 = YP_01 + ( - DT * YP_11 )
YP_10 = YP_10 + ( - DT * YP_11 )
YP_11 = YP_11 + ( + Q_gyro * DT )

y = accAngle - KFangleY
S = YP_00 + R_angle
K_0 = YP_00 / S
K_1 = YP_10 / S

KFangleY = KFangleY + ( K_0 * y )
y_bias = y_bias + ( K_1 * y )

YP_00 = YP_00 - ( K_0 * YP_00 )
YP_01 = YP_01 - ( K_0 * YP_01 )
YP_10 = YP_10 - ( K_1 * YP_00 )
YP_11 = YP_11 - ( K_1 * YP_01 )

return KFangleY

```