---
title: Filtering in firmware
heading: Moving averages, exponential smoothing and medians in integer arithmetic
eyebrow: C12 · Lesson 19 · Filtering in firmware
xp: 40
---

::: hook
Raw ADC readings jitter by a few codes, sensors pick up hum, and a loose connector throws in the odd wild spike. Most embedded programs filter their inputs, and almost all of them use one of three filters: a moving average, an exponential smoother, or a median. Each fits in a handful of integer instructions, each has a delay and a noise reduction you can calculate, and each has a classic integer bug worth knowing before it bites.
:::

::: play
- The stems are the step responses of two filters: a moving average of N samples and an exponential smoother with $\alpha = 2^{-k}$.
- The moving average reaches the new value in exactly N samples, in a straight line. The smoother approaches it gradually and never quite arrives.
- The readouts compare their noise reduction: how much of the input's random noise survives each filter.
:::

```sim plot
view: graph
x: n = 0..64 samples
y: y = 0..1.1
slider: N = 2..32 step 1 = 16
slider: k = 1..6 step 1 = 4
plot: (n + 1)/N + (1 - (n + 1)/N)*step(n + 1 - N) | stems | label: moving average
plot: 1 - (1 - 2^(-k))^(n + 1) | stems | label: smoother
readout: moving average noise ratio = 1/sqrt(N) | digits: 3
readout: smoother noise ratio = sqrt(2^(-k)/(2 - 2^(-k))) | digits: 3
```

::: predict
## A program smooths ADC readings with `y = y + ((x - y) >> 4);` in integers. The input sits steady at 1000 and y starts at 0. Where does y end up?

- [ ] Exactly 1000
- [x] Somewhere from 985 to 1000, stuck short of the input
- [ ] It oscillates around 1000
- [ ] It overflows

::: reveal
Once $x - y$ is below 16, shifting it right by 4 gives 0, and y stops moving. Here it stalls at 985, 15 codes short. The fix is to keep the smoother's state with extra fraction bits: store $s = 16y$ and update `s += x - (s >> 4)`, reading `y = s >> 4`.
:::
:::

::: nameit
## Moving average

$y_n = \frac1N\sum_{i=0}^{N-1} x_{n-i}$. Keep a **running sum**: add the new sample, subtract the one leaving the window (stored in a ring buffer). It reduces random noise by $\sqrt N$, delays the signal by $(N-1)/2$ samples, and has nulls at multiples of $f_s/N$: choosing N so that $f_s/N$ = 50 or 60 Hz removes mains hum completely. The sum needs $\lceil\log_2(N \cdot x_\text{max} + 1)\rceil$ bits.

## Exponential smoother

$y_n = y_{n-1} + \alpha(x_n - y_{n-1})$, a one-pole low-pass. With $\alpha = 2^{-k}$ the multiply is a shift. Its time constant is $-1/\ln(1 - \alpha) \approx 2^k$ samples, it reaches within 1% after $\ln 0.01/\ln(1 - \alpha)$ samples, and it passes a fraction $\sqrt{\alpha/(2 - \alpha)}$ of white noise's rms. It needs no buffer, only one variable, kept with k extra fraction bits to avoid the stall.

## Median

The middle of the last 3 or 5 samples. It ignores an isolated spike completely, where an average smears it over N samples, and it preserves sharp steps. It's not linear, so it has no frequency response to speak of; it's often followed by a smoother.
:::

::: example
## ADC readings have 4 codes of rms noise and arrive at 1 kHz. What do a 16-sample moving average and a k = 4 smoother do to the noise, and what delays do they add?

::: solution
1. **Moving average noise.**
   $$\frac{4}{\sqrt{16}} = 1\ \text{code}$$
2. **Moving average delay.** 7.5 samples, which is 7.5 ms at 1 kHz.
3. **Smoother noise.** With $\alpha = 1/16$ it passes a fraction
   $$\sqrt{\frac{1/16}{31/16}} = 0.180$$
   of the noise, so 0.72 codes.
4. **Smoother time constant.** 15.5 samples.
5. **Compare them.** The smoother reduces noise more because its memory is longer: matching its noise needs a moving average of 31 samples.

**Answer:** the moving average leaves 1 code of noise and delays by 7.5 ms; the smoother leaves 0.72 codes, with a time constant of 15.5 samples.
:::
:::

::: example
## Readings arrive at 1 kHz with 50 Hz hum. What moving-average length removes the hum entirely?

::: solution
1. **Where the nulls fall.** A moving average has nulls at multiples of $f_s/N$.
2. **Put one on the hum.**
   $$\frac{1000}{N} = 50 \quad\text{so}\quad N = 20$$
3. **Why it works.** The average then spans exactly one hum cycle, whose average is zero.
4. **60 Hz hum.** At 1 kHz, $1000/60$ isn't whole; sampling at 1.2 kHz with N = 20 works instead.

**Answer:** a 20-sample moving average.
:::
:::

::: example
## How long must the running sum be for a 64-sample average of 12-bit readings?

::: solution
1. **Largest sum.**
   $$64 \times 4095 = 262\,080$$
2. **Bits needed.** That needs 18 bits, so it fits easily in 32 bits.
3. **A 16-bit sum.** It would overflow at a sum of 65,535, which is reached with a reading of about 1024 on every sample.

**Answer:** 18 bits, so a 32-bit running sum holds it easily.
:::
:::

::: check
kind: parts
given: N = 4 | 16 | 64; s = 2 | 5 | 12; f = 100 | 1000

## A moving average of {N} samples runs on readings with {s} codes of rms noise, at {f} Hz.

::: part
answer: s/sqrt(N)
unit: codes
tolerance: 0.5%

### How much noise is left?

::: misses
- [s/N] Random noise falls as $\sqrt N$, not $N$.
- [any] $\sigma/\sqrt N$.
:::
:::

::: part
answer: (N - 1)/2/f*1000
unit: ms
tolerance: 0.5%

### How much delay does it add?

::: misses
- [N/f*1000] The average's center is $(N-1)/2$ samples back.
- [any] $(N - 1)/2$ sample periods.
:::
:::
:::

::: check
kind: parts
given: f = 500 | 1000 | 2000 | 3000; h = 50 | 100

## Readings arrive at {f} Hz with hum at {h} Hz.

::: part
answer: f/h
tolerance: 0

### What moving-average length puts its first null on the hum?

::: misses
- [any] $f_s/f_\text{hum}$.
:::
:::

::: part
answer: (f/h - 1)/2/f*1000
unit: ms
tolerance: 0.5%

### What delay does that average add?

::: misses
- [any] $(N - 1)/2$ samples.
:::
:::
:::

::: check
kind: parts
given: k = 2 | 3 | 5 | 6

## An exponential smoother uses $\alpha = 2^{-\given{k}}$.

::: part
answer: -1/ln(1 - 2^(-k))
unit: samples
tolerance: 0.5%

### What is its time constant?

::: misses
- [2^k] Close; the exact value is $-1/\ln(1 - \alpha)$.
- [any] $-1/\ln(1 - \alpha)$.
:::
:::

::: part
answer: ceil(ln(0.01)/ln(1 - 2^(-k)))
unit: samples
tolerance: 0

### After how many samples is a step within 1% (whole samples)?

::: misses
- [any] $\ln 0.01/\ln(1 - \alpha)$, rounded up.
:::
:::

::: part
answer: sqrt(2^(-k)/(2 - 2^(-k)))
tolerance: 0.5%

### What fraction of white noise's rms passes?

::: misses
- [any] $\sqrt{\alpha/(2 - \alpha)}$.
:::
:::
:::

::: check
kind: parts
given: N = 8 | 64 | 256 | 1024; b = 10 | 12 | 16

## A running sum averages {N} samples of a {b}-bit unsigned ADC.

::: part
answer: N*(2^b - 1)
tolerance: 0

### What is the largest sum?

::: misses
- [N*2^b] The largest reading is $2^b - 1$.
- [any] $N(2^b - 1)$.
:::
:::

::: part
answer: ceil(log(N*(2^b - 1) + 1)/log(2))
unit: bits
tolerance: 0

### How many bits does the sum need?

::: misses
- [any] $\lceil\log_2(\text{max} + 1)\rceil$.
:::
:::
:::

::: check
kind: parts
given: k = 3 | 4 | 6; x = 700 | 1000 | 3000

## A smoother `y = y + ((x - y) >> {k})` without extra fraction bits starts at 0 with a steady input of {x}.

::: part
answer: 2^k - 1
unit: codes
tolerance: 0

### What is the largest gap at which it stops moving?

::: misses
- [2^k] A gap of $2^k$ still shifts to 1.
- [any] Any gap below $2^k$ shifts to 0.
:::
:::

::: part
answer: k
unit: bits
tolerance: 0

### How many fraction bits must the state carry to fix it?

::: misses
- [any] As many as the shift.
:::
:::
:::

::: check
kind: parts
given: c = 20 | 60 | 200; f = 1 | 10 | 50

## A filter costs {c} cycles per sample on the 10 MHz board and runs at {f} kHz.

::: part
answer: c*f*1000/1e7*100
unit: %
tolerance: 0.5%

### What share of the processor does it use?

::: misses
- [any] Cycles × rate ÷ clock.
:::
:::

::: part
answer: 1e7/(c*f*1000)
tolerance: 0.5%

### How many such filters could run, at most?

::: misses
- [any] The reciprocal of the share.
:::
:::
:::

::: check
kind: choice

## A pressure sensor is read at 100 Hz and occasionally returns a single wild value from a loose connector. Which filter suits it best before display?

- [ ] A 64-sample moving average
- [x] A median of 3 or 5, then a light smoother
- [ ] An exponential smoother with k = 1
- [ ] No filter: the display will average it

::: misses
- [1] It spreads each spike over 64 samples, as a long bump of 1/64 the size.
- [3] With k = 1 the spike passes at half its size.
- [4] A display updates too slowly to average; it'll show the spike.
:::
:::

::: check
kind: python

## Write integer-only filters: `moving_average(xs, n)` with a running sum (output the floor of the sum over n once n samples have arrived, nothing before), and `smoother(xs, k)` keeping `s = 2^k y` (output `s >> k` after each sample, s starting at 0).

```python starter
def moving_average(xs, n):
    return []

def smoother(xs, k):
    return []
```

```python solution
def moving_average(xs, n):
    out, total = [], 0
    for i, x in enumerate(xs):
        total += x
        if i >= n:
            total -= xs[i - n]
        if i >= n - 1:
            out.append(total // n)
    return out

def smoother(xs, k):
    s, out = 0, []
    for x in xs:
        s += x - (s >> k)
        out.append(s >> k)
    return out
```

```python tests
assert moving_average([4, 8, 12, 16, 20], 2) == [6, 10, 14, 18], "Pairs averaged."
assert moving_average([1] * 10 + [100] + [1] * 10, 5)[8] == 20, "A spike becomes a bump of 1/5 its size (100 + 4)/5 = 20."
y = smoother([1000] * 200, 4)
assert y[-1] == 1000, "With fraction bits the smoother reaches the input exactly."
assert y[15] < 1000 and y[15] > 600, "After 16 samples, about 1 − e^-1 of the way: 644."
assert smoother([7] * 300, 6)[-1] == 7, "Even small inputs are reached."
```

::: right
Right. Both use only adds, subtracts and shifts, so they run in a few cycles in an interrupt.
:::
:::

::: explain
## Why does an exponential smoother written as `y += (x - y) >> 4` in integers settle short of a steady input, and how does keeping extra fraction bits fix it?

::: model
The shift divides the gap between the input and the output by 16 and throws away the remainder. While the gap is large that's fine, but once it falls below 16 the shifted correction is zero, and the output stops moving, up to 15 codes short of the input. Keeping the state multiplied by 16, as s = 16y, means the update adds the full gap x − y without dividing it first, so even a gap of one code changes s. The division only happens when the output is read, and in steady state s settles where s/16 equals the input.
:::
:::

::: practice
::: check
given: N = 9 | 25 | 100; s = 3 | 8
answer: s/sqrt(N)
unit: codes
tolerance: 0.5%

## Noise after a {N}-sample average of {s} codes rms?

::: misses
- [any] $\sigma/\sqrt N$.
:::
:::

::: check
given: k = 2 | 4 | 7
answer: -1/ln(1 - 2^(-k))
unit: samples
tolerance: 0.5%

## Time constant of a smoother with α = 2^−{k}?

::: misses
- [any] $-1/\ln(1 - \alpha)$.
:::
:::

::: check
given: f = 600 | 1200 | 2400; h = 50 | 60
answer: f/h
tolerance: 0

## Moving-average length for a null at {h} Hz, sampling at {f} Hz?

::: misses
- [any] $f_s/f_\text{hum}$.
:::
:::
:::
