Radio from scratch · Chapter 5

Moving a station

Before you startThis chapter uses:

Chapter 4 gave us a picture of the whole slice of radio band the dongle captures: dozens of stations side by side. But you want to listen to one of them. (An old radio did this with a coil and a capacitor, a tuned circuit that only rings at one station's frequency: try it in Electronics ch. 3. We'll do it with numbers instead.) Why not build a separate filter at whatever frequency your station happens to sit on? Because the tools that come next (a filter that keeps one station, chapter 6, and the step that turns it into sound, chapter 9) are far simpler when the station sits in one fixed place: the center, 0 Hz, where its arrow isn't spinning round at all. So instead of building new tools for every station, we slide whichever station you want to the center, and use the same tools every time.

The station you want is rarely there. When you ask for 98.7 MHz, the dongle is deliberately tuned a quarter of a MHz lower (to avoid its own spike at 0 Hz, ↩ ch. 4), so 98.7 shows up at +250 kHz. This chapter is about sliding it to the center.

Slide the whole band

You already know the trick from chapter 4: multiplying by an arrow spinning backwards subtracts its speed from everything (↩ un-spinning). There, we used it to test for one speed at a time. Here we use it to move things: multiply the whole signal, sample by sample, by an arrow spinning backwards at 200 kHz, and every station in the band slows down by exactly 200 kHz.

The demo band below has an FM station at +200 kHz. On the left, in slow motion, is its arrow. On the right is the whole band. Slide:

Predict: you multiply the whole band by an arrow spinning backwards at 250 kHz. Where does a station at +100 kHz end up?

Every frequency moves down by 250 kHz: 100 − 250 = −150 kHz.

As the shift approaches 200 kHz, the FM station's arrow slows down. At exactly 200, it stops going around and just wobbles back and forth. That wobble is the music (↩ ch. 1: FM is a wobble in the speed). On the right, the station's hump has arrived on the pink center line.

Three things to notice:

This operation is called mixing, or more precisely frequency shifting, and the spinning arrow you multiply by is the local oscillator.

Multiplying every sample by an arrow spinning backwards at some speed f₀ slides the whole band down by f₀. With both shadows, everything moves one way only.

Why does every station move by the same amount?
  1. A station is an arrow spinning at its frequency f.
  2. Our own arrow (the local oscillator) spins backwards at f₀.
  3. Multiplying adds the angles (chapter 2), so after t seconds the product's angle is that of a speed f − f₀.
  4. The band is a sum of stations, and multiplying a sum multiplies each part: every station gets the same treatment.
  5. So every frequency moves down by exactly f₀, and nothing changes shape.
Where it breaks

Sampled frequencies live on a circle (chapter 3), so a shift can push a station off one edge and onto the other. At 1.024 MS/s the honest zone is −512 to +512 kHz. Move a station at +450 kHz up by 200 kHz (mix by −200 kHz) and it should land at +650 kHz, which doesn't exist: it appears at 650 − 1024 = −374 kHz, on the opposite side. Receivers keep the station they want well inside the zone, and filter before shifting anything far.

Why it takes both shadows

Old radios mix too, with real electronics. But a simple electronic mixer can only multiply by a plain wave going up and down: a cosine, one shadow of the spinning arrow (↩ ch. 1: two shadows). What happens if we do that? Tick the box:

With only cos, every station appears twice: once shifted down by 200 kHz, as we wanted, and once shifted up by 200 kHz. Here's why. A cosine is what you get when you add an arrow spinning forward and an arrow spinning backward, at half length each: their sideways parts add, and their up-down parts cancel. (That's chapter 1's game in reverse: the sideways shadow can't tell the two directions apart, because it contains both.) So multiplying by cos is like multiplying by both arrows at once, which moves every station in both directions.

Multiplying by the full arrow (cos for I and sin for Q, chapter 2's arrow multiplication) moves everything one way only. That's one more reason software radios work with I and Q.

Pause and ponderEach copy in the one-shadow picture is about 6 dB weaker than the original. Why? (Hint: each of the two half-length arrows inside a cosine carries a quarter of the power, and 10·log10(¼) ≈ −6.)

Making the spinning arrow: the NCO

To mix, we need a perfectly steady arrow spinning at the shift frequency, one position per sample. Chapter 2 showed one way to make it: multiply by a small step arrow again and again (↩ ch. 2: multiply again and again). Real code uses a simpler idea: keep a running angle, add a fixed step to it every sample, and compute the arrow from the angle each time:

Each dot on the dial is one sample's angle. On the right are the two shadows of each one: cos (the I part) and sin (the Q part). This is called a numerically controlled oscillator (NCO): an oscillator made of arithmetic.

Lab: center a real station

Live radio, before and after mixing. The dongle is tuned 250 kHz below the frequency you choose, so your station starts at +250 kHz in the top picture. Mix by 250 kHz and watch it land on the pink line in the bottom picture.

  1. With the mix at 250 kHz, the station you chose sits on the pink line, with its HD Radio rectangles on both sides.
  2. Move the slider to center a different station instead, for example the next hump over.
  3. Set it to 0: the bottom picture is the same as the top. Mixing by nothing changes nothing.

Writing it down

y[n]=x[n]· e−j2πf0n/fs cos⁡θ=ejθ+e−jθ2

In code

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

The whole mixer, as it runs in this site's receiver:

Names in this code: ph is the phase (chapter 1's word for an arrow's angle): here, the running angle on the NCO's dial above. step is how far the dial turns per sample, negative because we spin backwards; fs is the sample rate and freq the shift. TAU is 2π, a full turn in radians. (c, s) is the NCO's arrow: the cos and sin of the angle. A class keeps the angle together with the code that uses it, and process handles one batch of samples (chapter 8 explains why batches).

export class Mixer {
  private ph = 0;                     // the running angle, remembered between chunks
  private step: number;
  constructor(fs: number, freq: number) { this.step = (-TAU * freq) / fs; }   // angle per sample
  process(iq: Float32Array): Float32Array {
    const out = new Float32Array(iq.length);
    let ph = this.ph;
    for (let k = 0; k < iq.length; k += 2) {
      const c = Math.cos(ph), s = Math.sin(ph);           // the NCO's arrow for this sample
      out[k] = iq[k] * c - iq[k + 1] * s;                 // complex multiplication (chapter 2)
      out[k + 1] = iq[k] * s + iq[k + 1] * c;
      ph += this.step;                                    // step the dial
      if (ph < -Math.PI) ph += TAU; else if (ph > Math.PI) ph -= TAU;   // keep the angle small
    }
    this.ph = ph;
    return out;
  }
}

Two details matter. The step is negative (−2π f₀ / fs) because we spin backwards to move things down. And the angle is saved on the object at the end of each chunk, so the next chunk continues exactly where this one stopped. Chapter 8 explains why that matters for live radio.

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:

before mixing, stations at (kHz): [ 100, 250 ]
after mixing by 250 kHz:         [ -150, 0 ]
cos-only mixing by 100 kHz: copies at +150 kHz (-6.0 dB) and +350 kHz (-6.0 dB); the full arrow gives one copy at -0.0 dB
after 10 million repeated multiplications: length off by 4.6e-10 (64-bit numbers), 5.6e-6 (32-bit numbers)
with a running angle, every arrow is computed fresh: its length is exactly 1 every time
all checks passed

The last two lines are why the NCO keeps an angle. Multiplying by a step arrow over and over does drift: tiny with 64-bit numbers, larger with the 32-bit numbers signal code often uses, and it never stops growing. Computing each arrow fresh from the angle means errors can't pile up, at no extra cost.

Check yourself

A station is at +300 kHz. You mix by 100 kHz. Where is it now?

At +200 kHz: everything moves down by the mixing frequency.

You mix by −150 kHz. What happens to a station at −150 kHz?

It moves to 0: subtracting −150 means adding 150, so −150 + 150 = 0. Mixing by a negative frequency moves everything up.

Why does mixing with cos alone produce two copies of every station?

A cosine is half a forward-spinning arrow plus half a backward-spinning one. Multiplying by it shifts every station both down and up.

What would happen if the NCO forgot its angle at the end of every chunk (chapter 8's pieces of a live stream) and restarted at 0?

The local oscillator would jump back to angle 0 every ~55 ms. The shifted signal would jump too, which you'd hear as a click 18 times a second (chapter 8).

Last updated