Marcio Cunha

Implementation of Kalman Filters in Embedded Systems for Sensor Noise Reduction

Learn how to apply Kalman filters in microcontrollers to clean noisy physical sensor data. Discover practical mathematics, design decisions, and functional C code for real-time embedded systems.

Marcio Cunha•5 min
Also available in:EspañolPortuguês
Summary
  • The Kalman filter solves the problem of estimating a system's hidden state by combining inaccurate measurements and predictive mathematical models in real time.
  • Embedded systems with limited processing resources require matrix optimizations to execute the Kalman algorithm without exhausting microcontroller clock cycles.
  • The estimation error covariance matrix acts as a dynamic trust regulator between what the sensor reads and what the physical model expects.
  • Tuning the process noise matrix and measurement variance defines the filter's dynamic behavior between rapid tracking and aggressive smoothing.
  • Practical implementation in C language uses fixed-point arithmetic or optimized floating-point depending on the target chip architecture.

The Challenge of Noise in Real-World Physical Sensors

Anyone who has tried measuring ambient temperature, motor speed, or distance using an ultrasonic sensor quickly notices an annoying problem: the data never stays still. Even with the equipment perfectly stationary, readings constantly oscillate up and down. This unwanted behavior is electronic noise, caused by electromagnetic interference, power grid instabilities, and physical limitations inherent to the transducer itself, which is the component responsible for turning a physical quantity into an electrical signal.

In embedded systems, which are dedicated computers running inside devices like drones, pacemakers, and industrial robots, ignoring this noise means accepting severe operational failures. A drone with noisy gyroscope readings can lose flight control and crash. In practice, engineers face the classic dilemma between delaying the system response to smooth the signal or keeping the response fast while accepting false peaks that can damage mechanical actuators.

The Principle of Operation of Statistical Estimation

To resolve this conflict, control engineering uses mathematical estimation algorithms. A simple filter, such as a moving average, merely calculates the mean of the last read values. Although easy to program, the moving average suffers from a major flaw: it delays the system response because it gives the same weight to old data and current data. When a robot avoids an obstacle, it cannot wait for the signal to pass through a long moving average to react.

This is where the Kalman Filter stands out as an elegant and powerful tool. Instead of just looking at the past or blindly trusting the current measurement, the algorithm operates in two continuous steps called prediction and update. In prediction, the filter uses the known physical laws of the system to guess where the object should be. In update, it compares this guess with the actual sensor reading and calculates an intelligent compromise based on the uncertainty of both.

In practice, this means that if the sensor is very noisy, the filter trusts the mathematical model more. If the physical model is uncertain but the sensor is precise, the algorithm gives more weight to the current reading. This dynamic adjustment is done through mathematical matrices that calculate the variance and statistical standard deviation of the data at each microcontrollers clock cycle.

Mathematical Anatomy of the Two-Phase Algorithm

The filter's operational cycle is divided into two distinct mathematical phases that repeat infinitely while the system is powered on. The first phase is time prediction, where the future state is projected using the state transition matrix. In simple terms, the microcontroller calculates what the next value should be based on the physics of the problem, such as velocity multiplied by elapsed time.

The second phase is measurement correction, where the Kalman gain comes into play. The Kalman gain is a dynamically calculated weighting factor that decides whether the new sensor reading deserves credit or should be treated as mere spurious fluctuation. If sensor uncertainty is high, the gain decreases and the filter practically ignores the raw value. If uncertainty is low, the gain increases and the reading quickly corrects the estimated trajectory.

To calculate this gain, the algorithm manipulates three main matrices: the estimated error covariance, the process noise covariance, and the measurement noise covariance. Correctly configuring these parameters is the most critical part of the engineering design, requiring empirical tests on the workbench with real hardware connected to an oscilloscope and data logger.

Practical Implementation in C Language for Microcontrollers

Below we present a lean and functional implementation of a one-dimensional Kalman Filter written in the C language, ideal for simple microcontrollers like the ARM Cortex-M or AVR family that lack a dedicated high-performance floating-point unit.

#include <stdio.h>typedef struct {  float x; // Estimated state (filtered value)  float P; // Estimation error covariance (uncertainty)  float Q; // Process noise covariance  float R; // Measurement noise covariance  float K; // Kalman gain} KalmanFilter;void kalman_init(KalmanFilter *kf, float initial_value, float process_noise, float measurement_noise) {  kf->x = initial_value;  kf->P = 1.0f;  kf->Q = process_noise;  kf->R = measurement_noise;}float kalman_update(KalmanFilter *kf, float measurement) {  // 1. Prediction  // Since state does not actively change in simple model, we project the same value  // P = P + Q  kf->P = kf->P + kf->Q;  // 2. Update  // Calculate Kalman Gain: K = P / (P + R)  kf->K = kf->P / (kf->P + kf->R);  // Update state with difference between measurement and estimate  kf->x = kf->x + kf->K * (measurement - kf->x);  // Update error covariance: P = (1 - K) * P  kf->P = (1.0f - kf->K) * kf->P;  return kf->x;}

This code encapsulates the essence of the filter in a few lines and consumes very little RAM, allowing its execution in extremely fast sampling cycles, in the kilohertz range, which are essential for closed-loop control in motors and stabilization systems.

Performance Considerations and Hardware Limitations

Although the code above works perfectly for single-axis sensors, such as thermocouples or isolated pressure gauges, complex systems with multiple axes require multidimensional matrices. When we migrate to 3x3 matrices or higher, matrix multiplication consumes a significant number of clock cycles, which can choke 8-bit microcontrollers or low-cost boards if the sampling rate is too high.

Another critical point is the use of floating-point numbers. In processors without a hardware floating-point unit, operations with float variables are emulated by software, generating considerable computational overhead. In these extreme cases, engineers resort to fixed-point arithmetic techniques, converting decimal numbers into scaled integers to drastically accelerate mathematical processing without losing the precision needed for control.

Conclusion and Next Steps in Sensor Optimization

The adoption of Kalman Filters in embedded systems transforms chaotic and unstable readings into clean, predictable, and highly reliable data streams for real-time decision making. Mastering this technique requires understanding the delicate balance between the physical model and the statistical behavior of the physical hardware used on the workbench.

Understanding noise parameters and correctly tuning covariance matrices allows electronic devices to operate with surgical precision even in severe and noisy industrial environments. The recommended next step is to expand this logic to extended state models, allowing you to handle non-linear dynamics in advanced mobile robotics.