Radio from scratch · Chapter 14

Writing the driver

Before you startThis chapter builds directly on:

A driver sounds mysterious. For this dongle it's two things: a list of register writes in exactly the right order, and the knowledge of what each one means. Chapter 13 showed single messages. This chapter shows the whole conversation, every message our driver sends from "open" to "close", and then the code that produces it.

Everything the driver says, in order

Below, the real driver from this site runs through a typical session (open, set the sample rate, tune to 98.45 MHz, set the gain, close) against a pretend dongle: an object that accepts every write and answers like a real one. Every control transfer is recorded and decoded into words. It happens right now in your browser; open each phase:

Some things to look for:

Why does the driver write 16 filter coefficients into the RTL2832U at start-up?

The chip decimates the converter's samples before sending them, and decimating without filtering first lets other stations fold in on top of yours (chapters 3 and 7). Those 16 numbers (chapter 3 lists them) are that anti-aliasing filter.

How anyone knows what to write

Predict: neither chip has a public datasheet. How does anyone know which registers to write?

Captured USB traffic, leaked reference code and experiments, pooled since 2012, when people found the undocumented SDR mode.

Neither chip has a public datasheet. The knowledge in the trace above was pieced together over years by the open-source community: people recorded what Windows TV software sent to these sticks, studied leaked reference code from the chip makers, and experimented. In 2012 they discovered the RTL2832U's undocumented "SDR mode" that ships raw samples, which is what turned a $20 TV stick into a radio receiver. The results live in osmocom's librtlsdr and the Linux kernel's drivers; our driver is a fresh TypeScript implementation of that shared knowledge.

That's also why the trace decoder above can name every register: the names come from the same community work. Writing a driver for a chip without a datasheet means reading other drivers carefully, and testing a lot.

A driver is the right register writes in the right order. This one's knowledge comes from years of open-source work, and it's checked against fake chips, recorded traces and a real station's pilot tone.

Why does the driver keep its own copy of the registers?
  1. Most of the tuner's registers can be written but not read back.
  2. A register is one byte, and many settings use only some of its bits.
  3. To change those bits, the driver must write the whole byte, so it must know the other bits' current values.
  4. Since it can't ask the chip, it keeps its own copy of every byte it has written, and edits that.
  5. That copy is the "shadow" register.
Where it breaks

A copy is only right while nothing else changes the chip. This chapter's bug list has the case where it wasn't: after many resets the tuner's analog side stopped passing any signal while its digital side still answered 0x69 as if all was well. The driver's copy said everything was set; the chip disagreed, and only cutting its power fixed it. Robust drivers reset the chip and rewrite every register from the copy at start-up, rather than trusting what they think is there.

The source, annotated

The trace above showed what the driver says; this is the code that says it, for when you want to change it, port it to another language, or write one for a different chip. Nothing later in the course depends on reading it line by line. The two files, exactly as they are on this site. Click any highlighted part of the code for its explanation, or an explanation to find its code.

The RTL2832U side: USB, registers, streaming

The tuner: R820T

Testing a driver

How could a test check that an FM receiver works on a real station, without anyone listening?

Look for something every FM stereo station sends and that's easy to measure: the 19 kHz pilot. If the demodulated audio has a strong, steady 19 kHz tone, the whole chain from USB to demodulator works.

Hardware code is hard to test, because the hardware isn't always there and doesn't always behave. This driver is tested at four levels, each catching different mistakes:

  1. A fake chip (chapter 12's script): the tuner driver runs against a pretend I2C bus that records writes. Checks: does the driver write the PLL values the math says it should?
  2. A recorded trace (this chapter's script): the whole driver runs against a pretend dongle. Checks: does every message have a known meaning, in a sensible order? (All 216 do.)
  3. The real dongle, with a test that doesn't need ears (npm run hw-test): capture from a real station and check that our FM demodulator finds the 19 kHz stereo pilot (↩ ch. 9). It can only be there if tuning, sample rate and I/Q handling are all right. It measures the real sample rate too, to catch dropped data.
  4. Abuse: open and close the dongle six times in a row, fast. This caught the nastiest bug.

The bugs we actually hit while building this driver, all now handled:

Lab: record the trace from your own dongle

The same session, but with your real dongle instead of the pretend one (Chrome, Edge or Opera, on an https:// or localhost page). The writes should match the trace above exactly; the reads are your chip's real answers.

In code

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

Recording a trace is a small trick worth knowing: wrap the device in a proxy, an object that passes every call through to the real one but writes it down first:

return new Proxy(dev, {
  get(t, k) {
    const v = t[k];
    if (k === "controlTransferOut") return async (s, data) => {
      log.push({ phase: phase.name, dir: "out", value: s.value, index: s.index, data: [...new Uint8Array(data)] });
      return v.call(t, s, data);                    // then do the real thing
    };
    // … the same for controlTransferIn, recording the answer …
    return typeof v === "function" ? v.bind(t) : v;
  },
});

The driver never knows it's being watched.

Where this chapter's numbers come from. The trace above was recorded by a short script behind this page, which runs the real driver against a pretend dongle and prints every message, phase by phase. Its output:

RTL2832U start-up: 86 control transfers
   USB register 0x2000 = 0x09 · USB_SYSCTL (USB block control)
   USB register 0x2158 = 0x00 0x02 · USB_EPA_MAXPKT (packet size)
   USB register 0x2148 = 0x10 0x02 · USB_EPA_CTL (sample endpoint control: 0x1002 = reset FIFO, 0x0000 = run)
   system register 0x300b = 0x22 · DEMOD_CTL_1 (demodulator clock/power)
   system register 0x3000 = 0xe8 · DEMOD_CTL (demodulator power/ADC)
   …
find the tuner and set up for it: 14 control transfers
   tuner: "start reading at register 0x00"
   tuner: read 1 status byte (0x69)
   …
tuner start-up (calibration included): 56 control transfers
   tuner registers 0x05–0x0b = 0x83 0x32 0x75 0xc0 0x40 0xd6 0x6c (bulk initialization)
   …
tune to 98.45 MHz: 23 control transfers
   …
216 control transfers in total; 0 without a known name
all checks passed

Check yourself

Why does nearly every tuner operation start with demod register 0x01 = 0x18?

That switches on the I2C repeater, the gate between the RTL2832U and the tuner's I2C wires. It's switched off again (0x10) afterwards so stray traffic can't reach the tuner.

Why does the tuner driver keep a copy of every register it writes?

Most of the chip's registers can't be read back. To change a few bits, the driver needs to know the rest of the byte, so it keeps its own copy. (Engineers call it a "shadow" register, which has nothing to do with chapter 1's shadows.)

How can you test that tuning works without listening to anything?

Tune to a stereo FM station and check that the demodulated signal contains the 19 kHz pilot. Wrong tuning, a wrong sample rate or mixed-up I/Q would all destroy it.

Last updated