Radio from scratch · Chapter 4
The winding machine
- Chapter 2: multiplying arrows (lengths multiply, angles add)
- Chapter 3: samples, decibels, and noise
- Chapter 1: a signal is a sum of spinning arrows
In chapter 1 we built tangled shapes by chaining spinning arrows. Now the question runs the other way. Someone hands you the tangle. Which arrows was it made from?
The yellow path was drawn by the tip of a few spinning arrows (you can see them faintly, chained together). But suppose you only had the path, sampled 400 times, as a list of I/Q numbers: exactly what a radio gives you. How fast is each hidden arrow spinning, and how long is it?
For a radio, this isn't a puzzle. It's the whole job: the air is one giant tangle, and every station is one hidden arrow inside it. The machine that untangles it is called the Fourier transform, and by the end of this chapter you'll have built it twice: once simply, and once fast.
The trick: un-spin the signal
Chapter 2 taught us that multiplying arrows adds their angles. So if one arrow spins at 3 turns per second and you multiply it, moment by moment, by an arrow spinning backwards at g turns per second, the result spins at 3 − g. The two speeds subtract.
Slide to exactly 3, and the result stops spinning. It just sits there, pointing in one direction. That's the trick: un-spinning by an arrow's own speed freezes it. Every other speed leaves it turning.
The winding machine
Now apply the trick to the whole tangle at once. Pick a test speed. Un-spin every one of the 400 samples by it. Then take the average of all the un-spun samples, their center of mass, as if each sample were a little weight.
- Any hidden arrow spinning at the test speed freezes: its contribution points the same way every time, and adds up.
- Every other hidden arrow keeps spinning: its contributions point in all directions and cancel out.
So the center of mass sits near zero, unless the test speed matches a hidden arrow. Then it jumps out, by exactly that arrow's length. Try it, or tick Sweep automatically and watch:
On the left, the blue path is the whole second of signal, un-spun by the test speed. Most of the time it's a tangle wrapped around the middle, and the center of mass stays close to zero. But at 2, −3 and 7 turns per second, the path suddenly bunches to one side and the center of mass leaps out.
On the right is how far the center of mass is from zero, for every test speed. Three spikes, at exactly the three hidden speeds, and each spike's height is that arrow's length: 1, 0.55, 0.35. We've untangled the signal.
That graph has a name: the spectrum. And this machine is the Fourier transform. It's the same picture you see in Spectrum Lab's top plot, and in every waterfall: each column is one test speed, and the brightness is how far the center of mass jumped.
Why do all the other speeds cancel?
- Names: N is the number of samples in the block (400 above); k is the test speed and m a hidden arrow's speed, both in turns per block.
- Un-spinning by test speed k turns an arrow of speed m into one of speed m − k (chapter 2: angles add).
- If m − k is a whole number of turns per block, other than 0, its N positions are spread evenly around the circle.
- Turn that whole set of positions by one step: each position lands where the next one was, so the set, and its sum, is unchanged.
- But turning a sum turns it too. A sum that stays the same when turned must be zero.
- So every speed except k averages to exactly zero, and speed k, which stops turning, averages to its own arrow.
- That's why the center of mass picks out one speed at a time.
Speeds that fall between the cracks
Before we point the winding machine at real radio, we have to fix a problem that would otherwise ruin our spectrum display: a single strong local station can splatter fake energy across the whole band and hide weak stations next to it. Why? Because a computer can't try every test speed; it tries a fixed list. If it looks at a block of N samples (a block is the stretch of samples it un-spins together: the 400 samples above were one second of signal, so there "turns per block" and "turns per second" were the same thing), it tries whole numbers of turns per block: 0, 1, 2, …, plus the same negative ones. Those are the yellow dots below. The grey curve shows what every speed in between would have given.
The vertical scale here is in decibels (dB), a scale where each step of 20 dB means the arrow is 10× shorter (chapter 3: 10× shorter is 100× less power, and every 10 dB is 10× the power). It stretches the bottom of the graph so you can see tiny leftovers, which matters because a weak station may be thousands of times weaker than a strong one next to it.
- Speed exactly 3.00: one dot at the top and all the others at the very bottom (zero). The signal makes exactly three whole turns in the block, so every other test speed cancels perfectly.
- Speed 3.50: now the signal makes three and a half turns in the block. No test speed freezes it, and its energy leaks into every dot, falling off only slowly with distance. A weak station anywhere nearby would be buried under this leakage.
- Now tick Fade the ends and try 3.50 again. Fading the signal in and out at the start and end of each block (a gentle bump called a Hann window) stops the sudden jump at the block's edges, which is what caused most of the leakage. The peak gets a little wider, but the leakage far away drops dramatically.
Real stations never spin at whole numbers of turns per block, so real spectrum displays always use a window. Ours does.
Where it breaks
A speed halfway between two test speeds never cancels anywhere. For 3.5 turns per block (computed by this chapter's checking script for 256 samples), the plain machine shows it at −3.9 dB at test speeds 3 and 4, still −30 dB ten speeds away, and −41 dB at speed 40. A weak station anywhere near a strong one hides under that. The Hann window trades a slightly wider peak (−1.4 dB at speed 3) for leftovers of −71 dB ten speeds away and −104 dB at speed 40, which is why every real spectrum display uses a window.
The fast way: the FFT
The plain machine is slow. To test N speeds, it un-spins all N samples for each one: N × N steps. For the 1024-sample blocks behind Spectrum Lab's waterfall that's over a million steps per row, many times per second.
You won't have to write an FFT, and nothing later depends on how it works inside, only on what it gives: the same spectrum, fast enough to draw live. This section is the one idea behind the speed, so the FFT in our code isn't a black box. Happy to trust it? Skip ahead to going back.
Estimate first: the plain machine un-spins all N samples for each of N test speeds. For a 1024-sample block, about how many million steps is that?
In 1965, Cooley and Tukey published a shortcut (Gauss had found it around 1805, but it was only printed after his death). The insight: the work for different test speeds overlaps. Split the samples into the even-numbered ones and the odd-numbered ones, and run the winding machine on each half separately. For a block of N samples, the answers for any test speed k and for the speed half a block's worth higher, k + N/2, come out of the same two half-machines, combined once with a plus and once with a minus. Then split each half again, and again, until you're left with single samples.
Each crossing in the diagram is one combine step, called a butterfly: one multiplication by a spinning arrow, one addition and one subtraction. There are log₂N layers of them (log₂N is how many times N can be halved before reaching 1: 10 for 1024), with N/2 butterflies per layer. That's the Fast Fourier Transform (FFT): identical answers, but N × log₂N steps instead of N × N. At N = 1024 it's 100 times less work, and the gap keeps growing.
Going back: the inverse FFT
The winding machine turns a signal into a list of arrows: for each speed, how long its arrow is and at what angle it started. Why would a radio receiver ever want to go the other way — from the spectrum back to a time signal? Two reasons we'll use soon: in chapter 6, we'll draw the rectangular frequency filter we want and run the machine backward to get the filter's weights; and in chapter 19, we'll clean up noisy speech by taking the FFT, turning down the speeds that contain only hiss, and turning the remaining arrows back into sound. You already know how going back works: chapter 1 built shapes by chaining spinning arrows tip to tail. Take every arrow the machine found, set each one spinning at its own speed from its own starting angle, and add them up. Out comes the original signal. That's the inverse FFT: the same butterflies, with every arrow spun forwards instead of backwards.
Predict: below, the signal from the top of this chapter is rebuilt from the three arrows the machine found. What happens if you leave out the fastest one, 7 turns per second, length 0.35?
- The whole path collapses
- The overall shape stays, but the extra curls the fast arrow drew disappear
- Nothing visible changes
Leave an arrow out and that speed is simply gone from the rebuilt signal, while everything else stays exactly as it was. That makes the round trip a tool: go to arrows, change the length of some, come back. It's how frequency-based audio effects work, and chapter 19 uses exactly this to turn hiss down.
The spectrum is the signal written as a list of spinning arrows. Adding the arrows back up (the inverse FFT) gives the signal back, so you can change a signal one speed at a time.
Your real radio, untangled
Here are the 4000 real samples from chapter 3, the fuzzy ring recorded at 98.45 MHz, run through the winding machine (the fast version, with a window, averaged over 7 blocks):
The ring from chapter 3 turns out to be mostly one arrow: 98.7 FM, a quarter of a MHz above the center, standing far above everything else. That's why its snapshots formed a ring: one dominant arrow of nearly constant length. The smaller bumps are other stations, and the narrow spike exactly in the middle is the dongle's own leftover at 0 Hz: a small constant offset in its measurements, an "arrow" that doesn't spin at all, so it lands at speed 0. Engineers call a constant like that DC (from "direct current", which never changes direction). That spike is why the live radio tunes a little to one side of the station you want.
Lab: a live spectrum
Now run the machine on live radio: every frame, the latest samples are cut into 512-sample blocks, windowed, put through our FFT, and averaged. Below the spectrum, each new spectrum becomes one row of a waterfall, newest on top, so you also see how the band changes over time.
- Find 98.7 FM's hump. Compare its width with the 0.2 MHz spacing between FM channels. The dongle is tuned 0.25 MHz below the station you ask for, so the station sits clear of the spike in the middle.
- See the flat rectangles on both sides of the hump? That's HD Radio: the same station sending digital audio in two sidebands (bands beside the main signal: chapter 10) next to its analog signal. On the waterfall, the flat tops make them look like solid bars.
- Type other frequencies (97.1, 100.3, 92.3) and watch different stations move into view. The axis is in real MHz.
- Try a frequency with no stations nearby, like 107.0, and look at the noise floor: the level the spectrum settles to where there's no station, which is chapter 3's noise seen one frequency at a time (chapter 18 measures it). Then raise the gain: the floor rises, and so does every station, by the same amount (chapter 3: gain can't change how far a station stands above the noise).
- Look for the narrow spike in the middle that never moves: that's the dongle's own 0 Hz leftover, not a station.
Writing it down
- x[n]: the samples, n = 0 … N−1.
- e−j2πkn/N: the un-spinning arrow (chapter 2's arrow at an angle, with a minus sign to spin backwards) at test speed k turns per block.
- (1/N) Σ: add them all up and divide by how many: the center of mass.
- X[k]: where the center of mass lands, for test speed k. Its length is the strength of speed k in the signal; its angle is the hidden arrow's starting angle (its phase).
- The inverse: every found arrow X[k], spinning forwards at its speed k, added up. (No 1/N here, because the forward machine already divided by N.)
- Power is the length squared. Every 10 dB is 10× the power; 3 dB is about 2×.
In code
Show the real code (optional: everything it does is explained above)
The plain winding machine is two loops, one over test speeds and one over samples. From this chapter's checking script:
Names in this code: re and im are I and Q: code often uses mathematicians' names for an arrow's two parts, "real" and "imaginary". TAU is 2π, a full turn in radians, so -TAU * k * t / n is the un-spinning angle for test speed k at sample t, and c, s are that arrow's two shadows (chapter 1). n is how many samples are in the block.
for (let k = 0; k < n; k++) { // every test speed…
for (let t = 0; t < n; t++) { // …un-spin every sample and add it up
const a = (-TAU * k * t) / n, c = Math.cos(a), s = Math.sin(a);
outRe[k] += re[t] * c - im[t] * s; // chapter 2's multiplication
outIm[k] += re[t] * s + im[t] * c;
}
}
The FFT that runs Spectrum Lab. First it reorders the samples (so that each split into even and odd halves is already sitting side by side), then it runs the butterflies layer by layer. The heart of it:
Names in this code: len is the size of the blocks being combined in this layer (2, 4, 8, …); a and b are the positions of a butterfly's two inputs; (cr, ci) is the un-spinning arrow for this butterfly, and (tr, ti) the odd half's answer after it's been turned by it. <<= 1 doubles len.
for (let len = 2; len <= n; len <<= 1) { // layers: blocks of 2, 4, 8, … samples
for (let i = 0; i < n; i += len) {
for (let k = 0; k < len / 2; k++) { // one butterfly:
const a = i + k, b = a + len / 2;
const tr = re[b] * cr - im[b] * ci; // turn the odd half's answer
const ti = re[b] * ci + im[b] * cr;
re[b] = re[a] - tr; im[b] = im[a] - ti; // minus → speed k + len/2
re[a] += tr; im[a] += ti; // plus → speed k
// …then turn (cr, ci) a little further for the next k
}
}
}
The spectrum you see adds the window, the FFT and the dB conversion (powerSpectrum()):
Names in this code: w is the Hann window's height at sample i; start is where this block begins in the samples. wsum is the window's total: dividing by it makes a full-strength arrow read 0 dB. The tiny 1e-20 keeps the logarithm away from zero, which has no logarithm.
const w = 0.5 - 0.5 * Math.cos((TAU * i) / n); // the Hann window: fade in and out
re[i] = iq[2 * (start + i)] * w; im[i] = iq[2 * (start + i) + 1] * w;
fft(re, im);
out[i] = 10 * Math.log10((re[j] ** 2 + im[j] ** 2) / wsum ** 2 + 1e-20); // power in dB
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. It builds the plain machine, checks the FFT against it, races them, and finds the station in the real samples. Its output:
hidden arrows found: 2 turns/block (length 1.00), 7 turns/block (length 0.35), -3 turns/block (length 0.55)
FFT vs plain machine on 1024 random samples: biggest difference 3.0e-6 (float rounding)
inverse FFT of the FFT: back to the samples within 1.3e-7 (float rounding)
time for 1024 samples: plain machine 15.6 ms, FFT 21 µs (753× faster)
real samples around 98.45 MHz: strongest station at 98.73 MHz, 25 dB above the noise floor
3.5 turns/block, no window : speed 3 -3.9 dB, speed 14 -30.3 dB, speed 40 -40.9 dB
3.5 turns/block, Hann window: speed 3 -1.4 dB, speed 14 -71.1 dB, speed 40 -103.7 dB
all checks passed
Check yourself
You un-spin a signal by 5 turns per second, and the center of mass stays at zero. What does that tell you?
There's no hidden arrow spinning at 5 turns per second (more precisely: nothing that freezes at that speed, so everything kept spinning and cancelled).
The center of mass jumps out to a distance of 0.4 at test speed −2. What's hidden in the signal?
An arrow of length 0.4 spinning clockwise at 2 turns per second (a negative frequency).
Why does a station whose speed falls between two test speeds show up in many of them?
No test speed freezes it, so it never fully cancels anywhere; its energy leaks across the whole list. A window (fading each block in and out) keeps that leakage near the true speed.
How many steps does the plain machine need for 4096 samples, and how many does the FFT need?
4096 × 4096 ≈ 16.8 million, vs 4096 × 12 ≈ 49 thousand: about 340 times less work.
Last updated