Noise and filtering
Why every sensor reading wobbles, and how moving-average and exponential filters smooth it, at the unavoidable cost of delay.
Lesson 2 of 6 · 30 min · Self-paced · Free
Why readings wobble
Read the same sensor a hundred times while nothing changes, and you will not get the same number a hundred times. A distance sensor pointed at a wall might report 20.4, 19.7, 20.2, 19.5 cm. This variation is noise: small, rapid, unpredictable errors added to the true value.
Noise comes from many places: thermal motion of electrons in resistors, electrical interference from motors and switching power supplies, vibration, and the ADC itself, which can only report whole counts. You can reduce noise at the source with good wiring, shielding and stable power. Whatever remains, firmware can reduce by filtering.
Noise matters for robots because decisions amplify it. A controller that reacts to every wobble in a sensor will twitch its motors. A gripper that closes when force exceeds a threshold might trigger on a noise spike. Smoothing the signal first makes behaviour calmer and more reliable.
The key idea: averaging cancels randomness
Random errors are as likely to be positive as negative. If you average several readings, the errors partly cancel while the true value stays. For independent noise, averaging N readings reduces the typical size of the noise by a factor of about √N. Averaging 4 readings halves the noise; averaging 100 reduces it tenfold.
But there is a catch. Averaging over time means mixing in old readings. If the true value changes, the average takes time to catch up. Every smoothing filter trades noise against lag. There is no free lunch, only choices.
The moving average
A moving average of length N reports the mean of the most recent N readings. Each new sample enters the window and the oldest leaves.
A moving average of length N delays a signal by about (N − 1)/2 samples on average, and takes N − 1 samples to fully respond to a sudden step. A longer window is smoother but slower.
On a microcontroller you do not need to re-add N numbers every time. Keep a running sum in a small ring buffer: subtract the sample that leaves, add the one that arrives.
#define WINDOW 4
typedef struct {
float samples[WINDOW];
float sum;
int index;
int count;
} MovingAverage;
float ma_update(MovingAverage *ma, float x)
{
if (ma->count == WINDOW) {
ma->sum -= ma->samples[ma->index]; /* drop the oldest */
} else {
ma->count++;
}
ma->samples[ma->index] = x;
ma->sum += x;
ma->index = (ma->index + 1) % WINDOW; /* wrap around */
return ma->sum / ma->count;
}Start it with MovingAverage ma = {0};. Until the window fills, it averages however many samples it has. One subtle point: with floats, repeatedly adding and subtracting can let tiny rounding errors build up in sum over millions of updates. With integer samples this cannot happen, which is one reason firmware often filters raw integer counts.
The exponential filter
The exponential moving average (EMA), also called a first-order low-pass filter, needs only one stored number:
y = y + α · (x − y)Here x is the new reading, y is the filtered value and α (alpha) is between 0 and 1. Read it as: "move a fraction α of the way from where you are towards the new reading". With α = 1 there is no filtering at all; with α = 0.1 each reading nudges the output only a little, giving heavy smoothing and slow response.
The name comes from how it weighs the past: the newest reading has weight α, the one before α(1 − α), then α(1 − α)², and so on, fading away exponentially. Nothing is ever completely forgotten, but old readings soon stop mattering.
If you sample every dt seconds and want the filter to have a time constant τ (roughly, how long it takes to cover 63 % of a step), choose:
α = dt / (τ + dt)For example, sampling at 100 Hz (dt = 0.01 s) with τ = 0.09 s gives α = 0.01 / 0.10 = 0.1.
Comparing them on real-looking data
These readings are made up for illustration. The true value is 20.0 until sample 8, then genuinely steps to 30.0.
readings = [20.4, 19.7, 20.2, 19.5, 20.6, 19.9, 20.3, 19.6,
30.2, 29.6, 30.5, 29.8, 30.1, 29.7, 30.4, 29.9]
def moving_average(xs, n):
out = []
for i in range(len(xs)):
window = xs[max(0, i - n + 1): i + 1]
out.append(sum(window) / len(window))
return out
def exponential(xs, alpha):
out = []
y = xs[0]
for x in xs:
y = y + alpha * (x - y)
out.append(y)
return out
ma = moving_average(readings, 4)
ema = exponential(readings, 0.3)
print(" k raw MA(4) EMA(0.3)")
for k, (r, m, e) in enumerate(zip(readings, ma, ema)):
print(f"{k:2d} {r:5.1f} {m:6.2f} {e:7.2f}")Output:
k raw MA(4) EMA(0.3)
0 20.4 20.40 20.40
1 19.7 20.05 20.19
2 20.2 20.10 20.19
3 19.5 19.95 19.99
4 20.6 20.00 20.17
5 19.9 20.05 20.09
6 20.3 20.07 20.15
7 19.6 20.10 19.99
8 30.2 22.50 23.05
9 29.6 24.93 25.02
10 30.5 27.48 26.66
11 29.8 30.02 27.60
12 30.1 30.00 28.35
13 29.7 30.02 28.76
14 30.4 30.00 29.25
15 29.9 30.02 29.44Before the step, the raw readings span 1.1 units (19.5 to 20.6). After the first sample, which both filters simply copy, the moving average stays within 19.95 to 20.10, and the EMA within 19.99 to 20.19: both are much calmer. After the step, the moving average has fully arrived by sample 11, three samples later, exactly as (N − 1) predicts. The EMA with α = 0.3 is still only at 29.44 seven samples later: each update closes 30 % of the remaining gap, so after the eight updates from sample 8 to sample 15, 0.7⁸ ≈ 6 % of the gap is still left.
Neither filter is "better". The EMA is cheaper in memory; the moving average responds in a fixed, predictable number of samples. A smaller α or a longer window would be smoother still and even slower.
Spikes need a different tool
Averaging filters spread a single wild reading across several outputs instead of removing it. A median filter, which reports the middle value of the last few readings (for example 3 or 5), ignores isolated spikes almost completely while preserving sharp steps. It costs a little sorting. Many sensor pipelines use a short median filter to reject spikes, followed by an EMA to smooth what remains.
Project
Python project: the noise–lag trade-off
Using the made-up readings in this lesson (or your own list of at least 30 invented readings with a step in the middle):
- Run the moving average with N = 2, 4 and 8, and the EMA with α = 0.5, 0.3 and 0.1.
- For each filter, measure (a) the spread (max − min) of its output over the steady part before the step, and (b) how many samples after the step it takes to get within 1.0 of the new value.
- Print a small results list and describe the pattern you see in two or three sentences.
- Add one deliberate spike (for example 55.0) to the steady part and compare an EMA with a 3-sample median filter that you write yourself.
No hardware is needed.
Deliverables
- A Python script with your filter functions
- A results list of spread and response time for each setting
- A short written comparison, including the spike experiment
Knowledge check
Check your understanding
Go further
- Moving average — Wikipedia ↗
Simple, weighted and exponential moving averages compared.
- Exponential smoothing — Wikipedia ↗
More on the exponential filter, including its link to the time constant.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.