Ground Embedded KO Subscribe

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.

GROUND EMBEDDED · NOTESensors & Signal Processing 03Digital filtersMCUTempI2CIMUSPIHallGPIORangeUARTCurrentADC

Moving average

New sampleBuffer of the last 4Sum ÷ 4Output
Moving average. Add the latest N and divide by N. When a new value comes in, the oldest leaves.

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)

New input × α+Previous output × (1 − α)New output
First-order IIR. Mixes the previous output and the new input in a ratio. No buffer needed.
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".

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →