Radio from scratch · Chapter 6

Averaging is filtering

Before you startThis chapter uses:

After chapter 5, the station you want sits in the middle of the band, at 0. But its neighbors are still there on both sides, and when we extract the sound (chapter 9) they'd come out as noise and crosstalk (another station's sound leaking into yours). We need a way to keep what's near 0 and remove everything else.

That's a filter, and the surprising thing is how simple the basic idea is: averaging. You've done it a hundred times without calling it filtering.

A moving average smooths out wiggles

Here's a signal made of a slow wave plus a fast wiggle. Let's make a new signal where each point is the average of the last few input points. As the yellow bracket slides along, the yellow output is drawn:

With 1 sample, nothing changes. With 6, the fast wiggle is almost gone and the slow wave survives: the output lies nearly on the dashed green line, which is the slow wave alone. That's a low-pass filter: slow things pass, fast things don't. A moving average of temperatures over a week does the same thing: it removes the day-to-day jitter and keeps the seasonal trend. (In hardware, a single resistor and capacitor make the same kind of filter: try it live in Electronics ch. 2.)

Make the average much longer, 20 samples. The wiggle is gone, but something happens to the slow wave too. What, and why?

It shrinks and shifts to the right: a 20-sample average reaches back far enough to blur even the slow wave, and since it only uses past samples, the output lags behind.

Why it works: averaging cancels spinning

You've already seen the reason, in chapter 4's winding machine (↩ the center of mass). Think of the input as spinning arrows. Averaging L samples of one arrow means averaging L of its positions: a center of mass. (Speeds in this section are in turns per sample: 0.125 turns per sample is one full turn every 8 samples.)

On the left, the faint blue arrows are the L positions being averaged, and the yellow one is their average. On the right, the grey curve shows how much of the arrow survives for every speed. This curve is the filter's frequency response: what the filter does to each frequency.

Try speed 0.125 with an average of 8: exactly one full turn during the 8 samples being averaged, and the average is exactly zero. Every speed that makes a whole number of turns cancels completely: those are the dips in the curve. Between the dips, though, the curve bounces back up: a plain average lets fast things leak through in bumps. We can do better.

Weights shape what gets through

The plain average has two flaws you just saw: its leftovers come back in bumps, and you can't choose what it keeps, since its length fixes that. To pick out one station we need both fixed: a cutoff we set, and far less leaking through. Here's the one change that does it. A plain average gives every sample the same importance. A weighted average gives each position its own weight. That list of weights is the whole filter: engineers call them the filter's taps or coefficients, and the filter is called a FIR filter (for "finite impulse response", because it only ever looks at a finite number of samples).

Here's the beautiful part. To find what a set of weights does to each frequency, you run chapter 4's winding machine on the weights themselves: for each test speed, spin the weights around, and see how far their center of mass lands from zero. The filter's response is the Fourier transform of its weights. So if we know the response we want, we can work backwards to the weights.

Now drag Weights up and down with the windowed sinc: more weights make the edge between "keep" and "remove" steeper. Fewer weights make it gentler. That's the basic trade-off of every filter: sharpness costs arithmetic.

A filter is a weighted average. Its effect on each speed is the winding machine run on its weights, so choosing the weights (a windowed sinc) chooses what passes.

Why is the frequency response the winding machine run on the weights?
  1. Names (Writing it down, below, uses them too): n counts samples, x[n] is input sample n and y[n] output sample n, hk is weight number k, and Σ means "add these up".
  2. Feed the filter one arrow of speed f: sample n is the arrow at angle 2πfn.
  3. Each output is a weighted sum of the last N inputs: y[n] = Σ h_k · x[n − k].
  4. The input k samples ago is today's arrow turned back by 2πfk, so y[n] = today's arrow × Σ h_k · (the arrow at angle −2πfk).
  5. That sum doesn't depend on n: it's one fixed arrow, H(f).
  6. So the filter just stretches and turns an arrow of speed f by H(f), and H(f) is the weights wound around at speed f: chapter 4's machine applied to the weights.
Where it breaks

No filter removes everything. This chapter's best shape, the windowed sinc, leaves leftovers 62 dB down (this chapter's checking script). That sounds like nothing, until the neighbor is 70 dB stronger than your station, as a powerful FM transmitter next to a weak one can be: then 70 − 62 = 8 dB of it still gets through, stronger than your station. The fixes cost arithmetic (more weights) or happen earlier: stop the strong signal before it reaches the radio (chapter 12).

Filtering a real band

Back to the demo band from chapter 5, with its FM station mixed to the center. Our receiver's filter designer takes two numbers: how wide to keep (±cutoff) and how steep the edge should be (the transition width), and works out the weights:

An FM station is about 200 kHz wide, so keeping ±100 kHz keeps all of it. The two neighbors drop by about 60 dB, a millionth of their power. Narrow the edge and watch the number of weights, and the cost, climb: a 20 kHz edge needs 169 weights, which at 2.4 million samples per second is about 800 million multiplications per second. That's why chapter 7 does something clever: throw away samples as you filter, so you only compute the ones you keep.

Lab: remove the neighbors from a real station

Your chosen station, centered (chapter 5), then filtered. Make the passband narrower and wider and watch the neighbors and the HD Radio sidebands (chapter 10) disappear.

  1. At ±100 kHz the station's analog hump survives, while its HD Radio rectangles (which start about 130 kHz from the center) are cut away.
  2. Shrink to ±50 kHz: you start cutting into the station itself. Its music would lose its loud passages (chapter 9 explains why FM needs its full width).
  3. Open up to ±250 kHz: now the HD Radio sidebands (chapter 10) are kept too, and so is part of the next station.

Writing it down

y[n]= ∑k=0N−1 hk·x[n−k] H(f)=∑khk·e−j2πfk hk=sin(2πfcx)πx·w(k)

In code

Show the real code (optional: everything it does is explained above)

Designing the filter (firLowpass()): choose how many weights from the edge width, sample the sinc, fade it with a Hamming window (a close cousin of chapter 4's Hann window: the same gentle bump, slightly raised at the ends), and scale so a signal at 0 Hz passes at exactly 1×:

Names in this code: cutoffNorm and transitionNorm are the cutoff and the edge's width as fractions of the sample rate (100 kHz at 1.024 MS/s is about 0.098). 3.3 is the standard rule of thumb for a Hamming-windowed filter: the number of weights is about 3.3 divided by the edge width. n | 1 makes n odd (it sets the last binary digit to 1), so there's a middle weight. h is the list of weights; dividing by their sum makes a 0 Hz signal come out the same size it went in.

let n = Math.ceil(3.3 / Math.max(transitionNorm, 1e-4));   // steeper edge → more weights
n = Math.min(511, n | 1);                                  // odd, so there's a middle weight; at most 511
for (let i = 0; i < n; i++) {
  const x = i - (n - 1) / 2;                               // distance from the middle
  const sinc = x === 0 ? 2 * cutoffNorm : Math.sin(TAU * cutoffNorm * x) / (Math.PI * x);
  h[i] = sinc * (0.54 - 0.46 * Math.cos((TAU * i) / (n - 1)));   // × Hamming window
  sum += h[i];
}
for (let i = 0; i < n; i++) h[i] /= sum;                   // unity gain at 0 Hz

Frequencies here are "normalized", in turns per sample: a cutoff of 100 kHz at 1.024 MS/s is 100 000 / 1 024 000 ≈ 0.098. The 3.3 is the Hamming window's rule of thumb: the edge width (in turns per sample) times the number of weights is about 3.3.

Running it is the weighted sum, once per output, for I and Q separately. Chapter 7 shows the full version, which also skips outputs we don't need:

Names in this code: buf holds the recent samples as I, Q, I, Q, …, so going back 2 places goes back one sample; base is where this output's newest sample sits; h holds the t weights; r and i collect the weighted I and Q sums.

let r = 0, i = 0;
for (let k = 0; k < t; k++) {               // t weights
  r += buf[base - 2 * k] * h[k];            // I part
  i += buf[base - 2 * k + 1] * h[k];        // Q part
}

Where this chapter's numbers come from. The numbers this chapter computes come from a short checking script behind this page, which also checks each claim and stops if one is wrong. Its output:

average of 8: speed 0.000 turns/sample → 100.0% survives
average of 8: speed 0.050 turns/sample → 76.0% survives
average of 8: speed 0.125 turns/sample → 0.0% survives  (a whole number of turns: cancels completely)
average of 8: speed 0.250 turns/sample → 0.0% survives  (a whole number of turns: cancels completely)
average of 8: speed 0.400 turns/sample → 7.7% survives
plain average          worst leftover beyond 0.22 turns/sample: -28.7 dB
triangle               worst leftover beyond 0.22 turns/sample: -46.9 dB
sinc, chopped          worst leftover beyond 0.22 turns/sample: -36.5 dB
sinc × Hamming window  worst leftover beyond 0.22 turns/sample: -62.1 dB
station + neighbor through a 69-weight low-pass: the neighbor is now -59 dB (0.11% of its original size)
transition 100 kHz wide → 35 weights
transition  50 kHz wide → 69 weights
transition  20 kHz wide → 169 weights
transition   5 kHz wide → 511 weights (our designer caps it at 511; the rule of thumb asks for ~680)
all checks passed

Note the comparison of shapes: the triangle's leftovers are smaller than the chopped sinc's, but only because a 41-weight triangle keeps a much narrower band you can't choose. The windowed sinc is the one that lets you choose where to cut and keeps the leftovers small.

Check yourself

Why does a moving average remove fast wiggles but keep slow ones?

Averaging is a center of mass. A fast arrow turns all the way round within the averaging window, so its positions cancel; a slow arrow barely moves, so its positions add up.

An average of 10 samples. Which arrow speed cancels completely: 0.05, 0.1 or 0.15 turns per sample?

0.1: exactly one full turn in 10 samples. (0.2, 0.3, … also cancel.)

Why don't we just use a plain average as our filter?

You can't choose its cutoff (it's fixed by its length), and its leftovers come back in bumps: with 41 weights, the worst one far from the passband is still only 29 dB down (this chapter's script). A windowed sinc of the same length lets you choose the cutoff and leaves 62 dB.

You want the edge between "keep" and "remove" twice as steep. What does that cost?

About twice as many weights, and so twice the multiplications per sample.

Last updated