Notes / Sensors & Signal Processing
Digital filters: moving average, IIR, FIR
Reduce measurement noise by calculation on the MCU. The one-line first-order IIR filter used most often, and how to choose a filter.
Moving average
The average of the latest N values. Easy to implement and effective against white noise, but N values have to be stored and the delay is N/2 samples. Keep a running sum and subtract the oldest value and each update is O(1).
First-order IIR (exponential average)
y = y + alpha * (x - y); // 0 < alpha ≤ 1
- Memory is one previous output
- The smaller alpha, the smoother and slower
- Cut-off roughly fc ≈ alpha · fs / (2π) (for small alpha)
It is the digital counterpart of an RC low-pass filter, and the filter used most often.
FIR
Multiplies N coefficients by the latest N inputs and adds them. The phase is linear (every frequency has the same delay), so the waveform shape is preserved, but the computation is heavy. The DSP instructions of the Cortex-M4 and the CMSIS-DSP library handle it quickly.
RoadmapSee where this note sits in Sensors & Signal Processing→How to choose
| Situation | Filter |
|---|---|
| Simple noise removal | First-order IIR |
| Removing outliers (spikes) | Median filter |
| Sharp cut-off, waveform preserved | FIR |
| Removing one frequency (vibration) | IIR notch |
Do not forget
A filter always adds delay. The harder you filter a sensor inside a control loop, the smaller the phase margin and the more it oscillates. The principle is to filter "only as much as needed".