Working with STM32 and digital Filters :Kalman filter.

In the previous guides, we took a look at FIR and IIR filters and in this guide, we shall take a small introduction to Kalman filter and how to use it filter ADC signal from out STM32F7 board.

In this guide, we shall cover the following:

  • Kalman filter.
  • Code.
  • Demo.

1. Kalman Filter:

Kalman filtering is an algorithm that provides estimates of some unknown variables given measurements observed over time. Kalman filters have been demonstrating its usefulness in various applications. Kalman filters have relatively simple form and require small computational power. However, it is still not easy for people who are not familiar with estimation theory to understand and implement the Kalman filters.

For more information please refer to this article on ResearchGate : here.

2. Code:

The code for simplified Kalman filter to filter out ADC value:

/*****************************************************
*Function name: kalman_filter
 *Function function: ADC_filter
 *Entry parameter: ADC_Value
 *Export parameters: kalman_adc
*****************************************************/
unsigned long kalman_filter(unsigned long ADC_Value)
{
    float x_k1_k1,x_k_k1;
    static float ADC_OLD_Value;
    float Z_k;
    static float P_k1_k1;

    static float Q = 0.0001;//Q: Regulation noise, Q increases, dynamic response becomes faster, and convergence stability becomes worse
    static float R = 0.005; //R: Test noise, R increases, dynamic response becomes slower, convergence stability becomes better
    static float Kg = 0;
    static float P_k_k1 = 1;

    float kalman_adc;
    static float kalman_adc_old=0;
    Z_k = ADC_Value;
    x_k1_k1 = kalman_adc_old;

    x_k_k1 = x_k1_k1;
    P_k_k1 = P_k1_k1 + Q;

    Kg = P_k_k1/(P_k_k1 + R);

    kalman_adc = x_k_k1 + Kg * (Z_k - kalman_adc_old);
    P_k1_k1 = (1 - Kg)*P_k_k1;
    P_k_k1 = P_k1_k1;

    ADC_OLD_Value = ADC_Value;
    kalman_adc_old = kalman_adc;

    return kalman_adc;
}

3. Demo:

  • Blue line raw unfiltered data.
  • Red line filtered data.

Happy coding 🙂

4 Comments

  • Victor Posted March 13, 2022 12:04 am

    Awesome!

  • Michel Posted May 28, 2022 2:12 pm

    Hi
    Thank you for your work.
    Can you explain the use of ADC_OLD_Value ? This variable doesn’t seem to be used in this function.

    • Husamuldeen Posted May 28, 2022 2:32 pm

      ADC_OLD_Value is used to store the passed ADC value for future calculation

      • Michel Posted May 29, 2022 7:40 am

        Thank you !

Add Comment

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