Open Source

How a Kalman Filter Works

I found this tutorial online. Here’s the original: http://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/

I originally translated this English tutorial into Chinese because it explains the subject more clearly than I could.

I. What is a Kalman filter?

In any dynamic system with uncertain information, you can use a Kalman filter to make an informed prediction about what the system will do next. The filter can still estimate what is happening when the measurements are noisy or other disturbances are present.

For systems that change continuously, a Kalman filter is a good fit. It uses little memory because it only carries forward the previous estimate and its uncertainty, and it runs quickly enough for real-time and embedded applications.

Most of the equations you find on Google for implementing a Kalman filter look pretty intimidating, which is a shame. Look at it the right way and the filter is actually quite simple to understand.

II. What can we use a Kalman filter for?

Take a toy example: you’ve built a little robot that can roam around in the woods. To navigate, it needs to know exactly where it is.

We can give the robot a state xk that represents its position and velocity:xk=(p,v)

The state is just a set of numbers that describe the system’s basic properties. It can describe anything. Here it’s position and velocity, but it could just as well be the amount of liquid in a container, the temperature of a car engine, the coordinates of a finger on a touchpad, or any other signal you need to track.

The robot has GPS, which is accurate to about 10 meters. That’s reasonably good, but it needs to locate itself to within less than 10 meters. The woods are full of gullies and cliffs, and one wrong move could send the robot over a cliff. GPS alone won’t cut it.
 

We might know a few things about how the robot moves. For example, it knows what commands it sent to its motors. If it’s moving in one direction and nobody intervenes, it’ll probably still be moving that way in the next time step. Of course, the robot can’t directly tell how it actually moved. The wind might push it, its wheels might be pointed slightly off course, or it might hit uneven ground and tip over. So the distance the wheels roll doesn’t exactly match how far the robot actually travels, and our prediction is imperfect.

The GPS sensor tells us something about the state, and our prediction tells us how the robot is likely to move. Both are indirect, uncertain, and imprecise. But can we combine all the information we have to get a better estimate than either gives us on its own? The answer is YES. That’s what the Kalman filter is for.

III. How a Kalman filter sees the problem

Let’s stick with the simple example where the state contains just position and velocity.

We don’t know the actual position or velocity. Many combinations are possible, but some are more likely than others:

The Kalman filter assumes that both variables (position and velocity in this example) are random and follow Gaussian distributions. Each has a mean μ at the center of its distribution (the most likely value) and a variance σ2 that represents its uncertainty.

In the figure above, position and velocity are uncorrelated, so knowing one tells us nothing about the likely value of the other. The next example is more interesting. Position and velocity are correlated, so the likelihood of observing a particular position depends on the current velocity:

That can happen, for example, when we estimate a new position from an earlier one. If we were moving quickly, we may have gone a long way. If we were moving slowly, we probably didn’t get far. Keeping track of this relationship gives us more information: a measurement of one variable tells us something about the likely values of the others. That’s the point of the Kalman filter: to extract as much information as possible from uncertain measurements!

We represent this correlation with a covariance matrix. In short, each entry ∑ij describes how the ith and jth state variables vary together. (You may have guessed that the covariance matrix is a symmetric matrix, so you can swap i and j.) The covariance matrix is usually denoted by Σ, and its entries are written as ∑ij

IV. Describing the problem with matrices

We model our state variables with a Gaussian distribution, so at time k we need two things: the best estimate xk (the mean, often written as μ elsewhere) and the covariance matrix Pk

(1)

(we’re only using position and velocity here, but the state can contain any number of variables representing whatever you want to track). Next, we use the current state (at time k-1) to predict the next state (at time k). Remember, we don’t know which of our possible predictions is the “true” next state. The prediction function applies to every possibility and gives us a new Gaussian distribution.

We can use the matrix Fk to represent this prediction:

It moves every point in our original estimate to a new predicted position. If the original estimate is correct, this predicted position is where the system will move next. So how do we use a matrix to predict position and velocity at the next time step? We can start with a basic kinematics equation:

We now have a prediction matrix for the state at the next time step. We still need to update the covariance matrix. For that, we introduce another equation. Suppose we multiply every point in the distribution by a matrix A and look at the resulting change in the covariance matrix ∑.

How does it change? The equation is:

Combining equations (4) and (3) gives:

V. External control inputs

Our model doesn’t capture everything. External inputs may act on the system and change it in ways that don’t depend on its current state.

Take a model of a moving train. The driver can open the throttle to speed up. Likewise, in the robot example, the navigation software might tell the wheels to turn or stop. If we know these inputs, we can represent them with a vector uk and add it to the prediction equation to correct the estimate.

Suppose the throttle setting or control command gives us an expected acceleration a. Basic kinematics gives us:

In matrix form:

Bk is called the control matrix, and uk is called the control vector (you can ignore this part for a simple system with no external control). Now what do we do if our prediction isn’t 100% accurate?

External disturbances

If the state changes according to the system’s own dynamics or known control inputs, we’re fine.

But what if there are unknown disturbances? A quadcopter we’re tracking might get pushed by the wind. A wheeled robot might skid or slow down on a small incline. We can’t directly track these effects, so leaving them out will throw off our predictions.

After each prediction, we can add some uncertainty to account for the “outside world” (the disturbances we aren’t tracking):

After the update, each state variable from the original estimate still follows a Gaussian distribution. We can say that each state variable in xk-1 moves into a new Gaussian-distributed region with covariance Qk. In other words, we model the untracked disturbances as noise with covariance Qk.

This gives us a new Gaussian distribution with a different covariance (and the same mean).

We simply add Qk to get the expanded covariance. Here are the complete equations for the prediction step:

As the equations show, the new best estimate comes from predicting forward from the previous best estimate and correcting for the known external control inputs.

Meanwhile, the new uncertainty comes from propagating the previous uncertainty and accounting for disturbances from the environment.

We now have a rough estimate of what the system might do next, expressed by xk and Pk. What happens if we also bring in sensor data?

VI. Updating the estimate with measurements

We might have several sensors measuring the system’s current state. Which sensor measures which state variable doesn’t matter here. One might measure position and another velocity. Each tells us something about the state indirectly.

The sensor readings may use different units and scales from the state we want to track. We use a matrix Hk to map the state to the sensor readings.

We can calculate the distribution of the sensor readings using the same notation as before:

One big advantage of the Kalman filter is that it can handle sensor noise. Our sensors are imperfect to some degree, so each possible state in the original estimate can correspond to a range of sensor readings.

The sensor data gives us a rough idea of the system’s current state. Because the readings are uncertain, some other states may be closer to the actual state than the readings suggest.

We represent this uncertainty (for example, sensor noise) with the covariance Rk. The mean of this distribution is the sensor reading itself, which we call zk。

We now have two Gaussian distributions. One is centered on the prediction, the other on the sensor reading.

We need to find the best estimate by combining the prediction (pink) and the sensor measurement (green).

So what is the most likely state? For any possible reading (z1,z2), we have two estimates:

(1) the sensor measurement;

(2) the prediction based on the previous state.

To combine the evidence from the measurement and the prediction, multiply their Gaussian densities.

That leaves the overlap. Its mean is the most likely value given the two estimates, so it’s our best estimate given all the available information.

Look! The overlap itself looks like another Gaussian distribution.

Multiplying two Gaussian densities with different means and variances, then normalizing the result, gives a new Gaussian with its own mean and variance. Here is how that works.

VII. Combining Gaussian distributions

It’s easier to start with a one-dimensional Gaussian. A Gaussian curve with variance σ2 and mean μ is given by:

What happens if we multiply two Gaussian functions?

Substitute equation (9) into equation (10) (remember to renormalize so the total probability is 1) to get:

Let k stand for the term that appears in both expressions in equation (11):

Now write equations (12) and (13) in matrix form. If Σ denotes the covariance of the Gaussian distribution and μ is the vector of means for each dimension, we get:

The matrix K is called the Kalman gain. We’ll use it shortly. Hang in there! We’re nearly done!

VIII. Putting the equations together

We have two Gaussian distributions. The first comes from the prediction:

The second comes from the measurement:

Plug them into equation (15) to find their overlap:

Equation (14) gives us the Kalman gain:

Left-multiply both sides of equations (16) and (17) by the inverse of the matrix (note that K contains Hk, so it cancels out). Then right-multiply both sides of the second equality in equation (16) by the inverse of HTk to get:

These are the complete equations for the update step. x‘k is our new best estimate. We can feed it and Pk‘ into the next prediction and update equations and repeat the process.

IX. Summary

The only equations you need are (7), (18), and (19). (If you forget them, you can derive them again from equations (4) and (15).)

These equations apply to linear systems of the form described here. For nonlinear systems, the extended Kalman filter (EKF) adds a step that linearizes the prediction and measurement models. An example implementation follows:

/* 

这个代码是GPT生成的,不确定有没有错误,欢迎批评

*/ 
 

#include <Wire.h> // I2C library, gyroscope 

// Accelerometer ADXL345 

#define ACC (0x53)    //ADXL345 ACC address 

#define A_TO_READ (6)        //num of bytes we are going to read each time (two bytes for each axis) 


// Gyroscope ITG3200  

#define GYRO 0x68 // gyro address, binary = 11101000 when AD0 is connected to Vcc (see schematics of your breakout board) 

#define G_SMPLRT_DIV 0x15    

#define G_DLPF_FS 0x16    

#define G_INT_CFG 0x17 

#define G_PWR_MGM 0x3E 


#define G_TO_READ 8 // 2 bytes for each axis x, y, z 

// offsets are chip specific.  

int a_offx = 0; 

int a_offy = 0; 

int a_offz = 0; 


int g_offx = 0; 

int g_offy = 0; 

int g_offz = 0; 

 

char str[512];  

 
 

void initAcc() { 

  //Turning on the ADXL345 

  writeTo(ACC, 0x2D, 0);       

  writeTo(ACC, 0x2D, 16); 

  writeTo(ACC, 0x2D, 8); 

  //by default the device is in +-2g range reading 

} 

 
 

void getAccelerometerData(int* result) { 

  int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345 

  byte buff[A_TO_READ]; 

   

  readFrom(ACC, regAddress, A_TO_READ, buff); //read the acceleration data from the ADXL345 

   

  //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!! 

  //thus we are converting both bytes in to one int 

  result[0] = (((int)buff[1]) << 8) | buff[0] + a_offx;    

  result[1] = (((int)buff[3]) << 8) | buff[2] + a_offy; 

  result[2] = (((int)buff[5]) << 8) | buff[4] + a_offz; 

} 

 
 

//initializes the gyroscope 

void initGyro() 

{ 

  /***************************************** 

  * ITG 3200 

  * power management set to: 

  * clock select = internal oscillator 

  *     no reset, no sleep mode 

  *   no standby mode 

  * sample rate to = 125Hz 

  * parameter to +/- 2000 degrees/sec 

  * low pass filter = 5Hz 

  * no interrupt 

  ******************************************/ 

  writeTo(GYRO, G_PWR_MGM, 0x00); 

  writeTo(GYRO, G_SMPLRT_DIV, 0x07); // EB, 50, 80, 7F, DE, 23, 20, FF 

  writeTo(GYRO, G_DLPF_FS, 0x1E); // +/- 2000 dgrs/sec, 1KHz, 1E, 19 

  writeTo(GYRO, G_INT_CFG, 0x00); 

} 

 
 
 

void getGyroscopeData(int * result) 

{ 

  /************************************** 

  Gyro ITG-3200 I2C 

  registers: 

  temp MSB = 1B, temp LSB = 1C 

  x axis MSB = 1D, x axis LSB = 1E 

  y axis MSB = 1F, y axis LSB = 20 

  z axis MSB = 21, z axis LSB = 22 

  *************************************/ 

 
 

  int regAddress = 0x1B; 

  int temp, x, y, z; 

  byte buff[G_TO_READ]; 

   

  readFrom(GYRO, regAddress, G_TO_READ, buff); //read the gyro data from the ITG3200 

   

  result[0] = ((buff[2] << 8) | buff[3]) + g_offx; 

  result[1] = ((buff[4] << 8) | buff[5]) + g_offy; 

  result[2] = ((buff[6] << 8) | buff[7]) + g_offz; 

  result[3] = (buff[0] << 8) | buff[1]; // temperature 

   

} 

 
 
 

float xz=0,yx=0,yz=0; 

float p_xz=1,p_yx=1,p_yz=1; 

float q_xz=0.0025,q_yx=0.0025,q_yz=0.0025; 

float k_xz=0,k_yx=0,k_yz=0; 

float r_xz=0.25,r_yx=0.25,r_yz=0.25; 

  //int acc_temp[3]; 

  //float acc[3]; 

  int acc[3]; 

  int gyro[4]; 

  float Axz; 

  float Ayx; 

  float Ayz; 

  float t=0.025; 

void setup() 

{ 

  Serial.begin(9600); 

  Wire.begin(); 

  initAcc(); 

  initGyro(); 

   

} 

 
 

//unsigned long timer = 0; 

//float o; 

void loop() 

{ 

   

  getAccelerometerData(acc); 

  getGyroscopeData(gyro); 

  //timer = millis(); 

  sprintf(str, "%d,%d,%d,%d,%d,%d", acc[0],acc[1],acc[2],gyro[0],gyro[1],gyro[2]); 

   

  //acc[0]=acc[0]; 

  //acc[2]=acc[2]; 

  //acc[1]=acc[1]; 

  //r=sqrt(acc[0]*acc[0]+acc[1]*acc[1]+acc[2]*acc[2]); 

  gyro[0]=gyro[0]/ 14.375; 

  gyro[1]=gyro[1]/ (-14.375); 

  gyro[2]=gyro[2]/ 14.375; 

   

    

  Axz=(atan2(acc[0],acc[2]))*180/PI; 

  Ayx=(atan2(acc[0],acc[1]))*180/PI; 

  /*if((acc[0]!=0)&&(acc[1]!=0)) 

    { 

      Ayx=(atan2(acc[0],acc[1]))*180/PI; 

    } 

    else 

    { 

      Ayx=t*gyro[2]; 

    }*/ 

  Ayz=(atan2(acc[1],acc[2]))*180/PI; 

   

   

 //kalman filter 

  calculate_xz(); 

  calculate_yx(); 

  calculate_yz(); 

   

  //sprintf(str, "%d,%d,%d", xz_1, xy_1, x_1); 

  //Serial.print(xz);Serial.print(","); 

  //Serial.print(yx);Serial.print(","); 

  //Serial.print(yz);Serial.print(","); 

  //sprintf(str, "%d,%d,%d,%d,%d,%d", acc[0],acc[1],acc[2],gyro[0],gyro[1],gyro[2]); 

  //sprintf(str, "%d,%d,%d",gyro[0],gyro[1],gyro[2]); 

    Serial.print(Axz);Serial.print(","); 

    //Serial.print(Ayx);Serial.print(","); 

    //Serial.print(Ayz);Serial.print(","); 

  //Serial.print(str); 

  //o=gyro[2];//w=acc[2]; 

  //Serial.print(o);Serial.print(","); 

  //Serial.print(w);Serial.print(","); 

  Serial.print("\n"); 

 
 

   

  //delay(50); 

} 

void calculate_xz() 

{ 

 
 

 xz=xz+t*gyro[1]; 

 p_xz=p_xz+q_xz; 

 k_xz=p_xz/(p_xz+r_xz); 

 xz=xz+k_xz*(Axz-xz); 

 p_xz=(1-k_xz)*p_xz; 

} 

void calculate_yx() 

{ 

   

  yx=yx+t*gyro[2]; 

  p_yx=p_yx+q_yx; 

  k_yx=p_yx/(p_yx+r_yx); 

  yx=yx+k_yx*(Ayx-yx); 

  p_yx=(1-k_yx)*p_yx; 

 
 

} 

void calculate_yz() 

{ 

  yz=yz+t*gyro[0]; 

  p_yz=p_yz+q_yz; 

  k_yz=p_yz/(p_yz+r_yz); 

  yz=yz+k_yz*(Ayz-yz); 

  p_yz=(1-k_yz)*p_yz; 

  

} 


//---------------- Functions 

//Writes val to address register on ACC 

void writeTo(int DEVICE, byte address, byte val) { 

   Wire.beginTransmission(DEVICE); //start transmission to ACC  

   Wire.write(address);        // send register address 

   Wire.write(val);        // send value to write 

   Wire.endTransmission(); //end transmission 

} 

 
 
 

//reads num bytes starting from address register on ACC in to buff array 

void readFrom(int DEVICE, byte address, int num, byte buff[]) { 

  Wire.beginTransmission(DEVICE); //start transmission to ACC  

  Wire.write(address);        //sends address to read from 

  Wire.endTransmission(); //end transmission 

   

  Wire.beginTransmission(DEVICE); //start transmission to ACC 

  Wire.requestFrom(DEVICE, num);    // request 6 bytes from ACC 

   

  int i = 0; 

  while(Wire.available())    //ACC may send less than requested (abnormal) 

  {  

    buff[i] = Wire.read(); // receive a byte 

    i++; 

  } 

  Wire.endTransmission(); //end transmission 

} 

 
Hi, I’m 005

Leave a Reply

Your email address will not be published. Required fields are marked *