Radio from scratch · Chapter 14
Writing the driver
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:
- RTL2832U start-up (the biggest phase): power on the demodulator (the chip's own name for its signal-processing half, built to decode TV; nothing to do with chapter 9's FM demodulator), reset it, then write the 16 coefficients of the resampler's filter (the resampler is the chip's decimator, chapter 7), packed into 20 registers (chapter 3's anti-aliasing filter), switch to SDR mode, and turn off everything that was meant for TV.
- Find the tuner and set up for it: "start reading at register 0x00", and the answer 0x69: that's how the driver knows it's an R820T. Then the RTL2832U is told about the tuner's 3.57 MHz IF.
- Tuner start-up: four batches of the 27 start-up values (7 at a time, the I2C bridge's limit), then the IF filter calibration: the PLL goes to 56 MHz, a trigger bit is pulsed, a code is read back.
- Tune: notice registers 0x14, 0x15 and 0x16 (the PLL integer and fraction from chapter 12) and the status read that checks the lock bit.
- Almost every tuner phase starts with "I2C repeater on" (the switch inside the RTL2832U that connects its I2C wires through to the tuner) (demod register 0x01 = 0x18) and ends with it off (0x10).
Why does the driver write 16 filter coefficients into the RTL2832U at start-up?
How anyone knows what to write
Predict: neither chip has a public datasheet. How does anyone know which registers to write?
- The makers publish it under license
- The open-source community recorded and reverse-engineered what TV software sent
- Trial and error by each driver author
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?
- Most of the tuner's registers can be written but not read back.
- A register is one byte, and many settings use only some of its bits.
- To change those bits, the driver must write the whole byte, so it must know the other bits' current values.
- Since it can't ask the chip, it keeps its own copy of every byte it has written, and edits that.
- 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?
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:
- 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?
- 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.)
- 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. - 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:
- A string the dongle can't serve. Its configuration has a name that its firmware returns broken. Browsers don't care, but Node's USB package crashed reading it. Fix: don't ask for it.
- A false alarm. A throughput test reported 2.307 million samples per second instead of 2.4, which looked like lost data. The timer had included closing the device. Lesson: check the measurement before the thing measured.
- A dongle that ignores you. Reopened quickly after closing, the chip sometimes stalls its first commands. librtlsdr's fix is a USB reset. But on macOS the reset makes the dongle disappear and reappear as a new device, so the driver now finds it again and starts over.
- Registers that stall. Writing a demodulator register while the demodulator is powered down stalls (chapter 13's lab hit this). Order matters: power first.
- A stuck tuner. Once, after many resets, the tuner's analog side stopped passing any signal: every byte was 126–129, even in other software. Its digital side still answered 0x69. Only unplugging it (cutting its power) fixed it. Some states can't be reached from software at all.
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