Digital filters: FIR and IIR
Moving averages, FIR and IIR filters, biquads and notch filters.
Cleaning up signals in firmware
Real sensor data is noisy: mains hum on an ECG, vibration on an accelerometer, quantisation noise on an ADC. Digital filters remove what you do not want and keep what you do. This lesson covers the two filter families every embedded engineer should be able to write and reason about: FIR and IIR. (The fixed-point lesson covers the integer arithmetic they usually run in.)
Describing a filter
| Term | Meaning |
|---|---|
Sample rate fs | Samples per second; the highest representable frequency is fs / 2 (Nyquist) |
| Low-pass, high-pass, band-pass, notch | Which frequencies are kept |
| Cut-off frequency | Where the response has fallen by 3 dB (to 70.7% of amplitude) |
| Order | How many past samples it uses; higher order means a sharper transition and more computation |
| Phase delay / group delay | How long the filter delays the signal; matters in control loops |
The moving average: the simplest FIR
An N-point moving average outputs the mean of the last N samples. It is a low-pass filter, excellent at removing random noise while keeping step changes sharp, and trivial to run in a ring buffer with a running sum (one add and one subtract per sample, regardless of N).
FIR filters
A finite impulse response filter computes each output as a weighted sum of the last N inputs:
y[n] = b0·x[n] + b1·x[n−1] + ... + b(N−1)·x[n−N+1]
The coefficients b define the filter; they are designed offline (windowed-sinc, Parks-McClellan, tools such as Python's scipy.signal.firwin). Properties:
- Always stable: no feedback.
- Linear phase when the coefficients are symmetric: every frequency is delayed equally, so wave shapes are preserved (important for ECG, audio, communications).
- Cost: N multiply-accumulates per sample. Sharp filters need many taps, which is where DSP instructions (
SMLADon Cortex-M4) and CMSIS-DSP'sarm_fir_q15help.
#include <stdio.h>
#include <math.h>
#define TAPS 5
/* A 5-tap low-pass FIR (symmetric, coefficients sum to 1, so DC gain is 1). */
static const double b[TAPS] = { 0.1, 0.2, 0.4, 0.2, 0.1 };
static double history[TAPS];
static int head;
static double fir(double x) {
history[head] = x;
double y = 0;
int idx = head;
for (int k = 0; k < TAPS; k++) {
y += b[k] * history[idx];
idx = (idx == 0) ? TAPS - 1 : idx - 1; /* walk backwards through the ring */
}
head = (head + 1) % TAPS;
return y;
}
int main(void) {
/* A slow signal (level 1.0) with fast alternating noise added. */
for (int n = 0; n < 10; n++) {
double noise = (n % 2) ? 0.3 : -0.3;
double x = 1.0 + noise;
printf("in %5.2f out %5.2f\n", x, fir(x));
}
return 0;
}
After the filter fills (the first four outputs are a ramp-up), the alternating ±0.3 noise at half the sample rate is reduced to ±0.06: these coefficients pass DC unchanged and attenuate the highest frequencies.
IIR filters
An infinite impulse response filter also feeds back past outputs:
y[n] = b0·x[n] + b1·x[n−1] + b2·x[n−2] − a1·y[n−1] − a2·y[n−2]
That is one biquad (second-order section). Feedback makes IIR filters far more efficient: a biquad gives a response that would need dozens of FIR taps. The price:
- Can be unstable if coefficients are wrong or quantised poorly. Higher orders are always built as a cascade of biquads, never as one high-order equation, to stay numerically stable.
- Non-linear phase: different frequencies are delayed by different amounts.
- Sensitive to arithmetic: in fixed point, feedback can amplify rounding errors and overflow; use enough fractional bits and saturation.
The simplest IIR is the exponential moving average (one-pole low-pass), the workhorse of sensor smoothing:
y += alpha * (x - y); /* 0 < alpha <= 1; smaller alpha = heavier smoothing */
y += (x - y) >> k; /* the integer version with alpha = 1 / 2^k */
Choosing
| FIR | IIR | |
|---|---|---|
| Stability | Always | Must be checked |
| Phase | Can be exactly linear | Non-linear |
| Cost for a sharp filter | High (many taps) | Low (few biquads) |
| Fixed-point behaviour | Benign | Needs care |
| Typical use | Audio, communications, ECG, decimation | Sensor smoothing, control loops, notch filters, tone detection |
Notch filters and mains hum
A narrow notch (one biquad) removes a single frequency such as 50 Hz or 60 Hz mains interference while leaving neighbouring frequencies almost untouched. Biomedical and weighing products often have one, selectable for the region.
Decimation and oversampling
To reduce the sample rate (for example from a fast ADC or a PDM microphone), first low-pass filter to below the new Nyquist frequency, then keep every Mth sample. Skipping the filter aliases the high-frequency content into the result. CIC filters do cheap first-stage decimation in hardware.
Practical points
- Design filters with a tool, then verify their response by feeding them test signals (a step, an impulse, sine sweeps) in a unit test on the host.
- Filter delay matters in control: a heavily smoothed sensor makes a control loop sluggish or unstable.
- Use CMSIS-DSP or vendor DSP libraries on Cortex-M4/M7/M33: they use SIMD and saturating instructions and have been carefully tested.
Pitfall: Converting a working floating-point IIR filter to fixed point by just scaling the coefficients often makes it unstable or noisy, because small poles near the unit circle need more precision. Use a biquad cascade with Q31 or a higher-precision accumulator, and test with real data.
Interview question: When would you choose an FIR filter over an IIR filter on a microcontroller?
Answer: When linear phase matters, so the waveform shape must be preserved (audio, ECG, communications), when guaranteed stability and benign fixed-point behaviour matter more than computation, or for decimation filters. Choose IIR when computation or memory is tight and phase does not matter, for sensor smoothing, notch filtering of mains hum, or control loops, implemented as a cascade of biquads with careful fixed-point scaling.
Interview question: How would you remove 50 Hz mains interference from a 500 Hz sampled signal?
Answer: Apply a second-order IIR notch filter centred on 50 Hz with a narrow bandwidth, designed for fs = 500 Hz, and add a 60 Hz option for other regions. If the harmonics at 100 and 150 Hz matter too, cascade notches or use a comb filter. Also reduce pickup in hardware (differential measurement, shielding, a good analog anti-alias filter), and verify the response with test signals in a host-side unit test.
Build it: notch out the motor's vibration
This is step 1 of the module project, a handheld camera gimbal: three brushless motors that hold a camera level while the person holding it walks, runs or turns. Its control loop runs at 1 kHz from a gyro that also picks up the motors' own vibration, a strong tone at 250 Hz. Fed back into the loop, that tone makes the gimbal buzz. A notch filter removes it and passes the slow movements the loop must correct. The microcontroller has no FPU, so the filter is a fixed-point biquad.
Lab: A fixed-point biquad, with rounding and saturation
biquad(f, x) filters one sample with the coefficients in f (in Q14: 16384 is 1.0) and returns the output:
y = (b0·x + b1·x1 + b2·x2 − a1·y1 − a2·y2) / 2^14
where x1, x2 are the previous two inputs and y1, y2 the previous two outputs (Direct Form I).
- Accumulate in 32 bits; the products of 16-bit samples and coefficients do not fit in 16.
- Round, rather than truncate: add
1 << 13before shifting right by 14 (>>on a negative value is an arithmetic shift here). - Saturate the result to the
int16_trange (−32768 to 32767) instead of letting it wrap: a wrapped sample is a full-scale spike, which a gimbal motor turns into a violent jerk. - Store the saturated output as
y1, so the filter's memory holds what was actually output.
Going deeper
Interview question: How would you remove mains hum and muscle noise from a wearable ECG signal?
Answer: A high-pass at about 0.5 Hz for baseline wander, a notch at 50 or 60 Hz (or an adaptive filter for its harmonics), and a low-pass around 40 Hz for muscle noise, chosen so the QRS shape survives. Implement them in fixed point, as IIR biquads for efficiency or FIR where linear phase matters, and check them on recorded ECG data.
Interview question: Why does heavy filtering of a sensor make a control loop worse?
Answer: Every low-pass filter adds delay (phase lag) to the signal it smooths. In a feedback loop that lag means the controller reacts to old information, which reduces the phase margin; as lag grows the loop overshoots, oscillates or becomes unstable, and the gains must be lowered, making it sluggish. Filter only as much as needed, prefer filters with little delay at the loop's crossover frequency, and account for the filter when tuning.
Interview question: What is the difference between a filter's group delay and its phase response?
Answer: The phase response gives the phase shift at each frequency; group delay is the negative derivative of phase with respect to frequency and gives the time delay of a narrow-band signal's envelope at each frequency. A linear-phase filter (symmetric FIR) has constant group delay, (N−1)/2 samples, so all frequencies are delayed equally and waveforms keep their shape; IIR filters have frequency-dependent group delay, which distorts transient shapes.
Explain it: In your own words, explain the main difference between FIR and IIR filters and the trade-off it creates.
Answer: An FIR filter computes each output only from current and past inputs, so it has no feedback: it is always stable and can have exactly linear phase, but a sharp response needs many coefficients and many multiply-accumulates per sample. An IIR filter also feeds back past outputs, so a few coefficients achieve a sharp response cheaply, but the feedback means it can be unstable, its phase is not linear, and it is sensitive to rounding in fixed-point arithmetic. So FIR trades computation for safety and phase linearity, and IIR trades those for efficiency.