Radio · developer guide
Build for your own dongle
Everything you need to write your own software for an RTL-SDR dongle, in a web page, with no drivers to install and no libraries: how the browser reaches USB, the protocols the dongle speaks, what the data looks like, and how to stream it from a server instead. Every snippet is taken from the working code on this site.
Open the 80-line starter app → Have a HackRF Pro? Its driver, step by step →The layers, from antenna to your code
src/rtlsdr.ts + src/r820t.ts~550 lines of TypeScript, no dependenciesnavigator.usb)built into Chrome, Edge, Opera (desktop and Android)Or, through the network: your page → HTTP → server.ts on a computer with the dongle → the same driver (running in Node) → the dongle. Your page sees the same bytes either way.
Setup: what each visitor needs
Browser
Chrome, Edge, Opera or another Chromium browser, on desktop or Android. Safari and Firefox don't support WebUSB; offer them the network source or file playback instead.
A secure page
WebUSB only exists on https:// pages and on http://localhost. On a plain-HTTP network address, navigator.usb is missing entirely.
macOS · ChromeOS
Nothing to install. Plug in and connect.
Windows
Windows needs the generic WinUSB driver on the dongle, installed once with Zadig: Options → List All Devices → pick "Bulk-In, Interface (Interface 0)" → WinUSB → Replace Driver. If you've used SDR# before, it's already done.
Linux
The kernel grabs the dongle as a TV tuner. Unload it and keep it off: echo 'blacklist dvb_usb_rtl28xxu' | sudo tee /etc/modprobe.d/rtl-sdr.conf, and allow your user to open it with a udev rule: SUBSYSTEM=="usb", ATTRS{idVendor}=="0bda", ATTRS{idProduct}=="2838", MODE="0666".
Android
Chrome with a USB-OTG adapter. Android asks for permission when the page connects. Phone + dongle makes a pocket receiver.
Only one program can use a dongle at a time. If SDR#, GQRX, SDR++, rtl_tcp or a server SDR has it open, the page can't claim it (see troubleshooting).
The WebUSB API in five calls
1. Ask for a device. The browser shows its own picker, filtered to the IDs you pass. It only opens in response to a click, so a page can't silently grab hardware.
button.onclick = async () => {
const device = await navigator.usb.requestDevice({
filters: [{ vendorId: 0x0bda, productId: 0x2838 }, { vendorId: 0x0bda, productId: 0x2832 }],
}); // rejects with NotFoundError "No device selected." if the user cancels
};
The browser remembers the permission for your site. Next visit, skip the picker: const [device] = await navigator.usb.getDevices();
2. Open it and claim interface 0. Claiming tells the OS "this page talks to this device now".
await device.open();
if (!device.configuration) await device.selectConfiguration(1);
await device.claimInterface(0); // fails if another program or OS driver holds it
3. Control transfers read and write the chip's registers (next section):
await device.controlTransferOut(
{ requestType: "vendor", recipient: "device", request: 0, value, index }, new Uint8Array(bytes));
const r = await device.controlTransferIn(
{ requestType: "vendor", recipient: "device", request: 0, value, index }, length);
// r.data is a DataView with the bytes the chip sent back
4. Bulk transfers carry the radio samples, from endpoint 1 (written 0x81 in USB terms: "endpoint 1, direction in"):
const r = await device.transferIn(1, 262144); // up to 256 KiB of samples
const bytes = new Uint8Array(r.data.buffer); // I, Q, I, Q, …
5. Clean up, and react to unplugging:
await device.releaseInterface(0); await device.close();
navigator.usb.addEventListener("disconnect", (e) => { if (e.device === device) stopEverything(); });
USB in one minute
A USB device has configurations (almost always one), each with interfaces (a group of functions; ours is interface 0), each with endpoints, which are one-way channels. Two kinds matter here:
| Transfer type | Used for | Properties |
|---|---|---|
| Control (endpoint 0) | Register reads/writes, setup | Small, acknowledged, carries a "setup packet" with request, value and index fields. |
| Bulk (endpoint 0x81) | The sample stream | Large and fast, delivered whenever the bus has time. The host must keep asking, or the dongle's buffer overflows and samples are lost. |
The dongle needs 2.4 MS/s × 2 bytes = 4.8 MB/s, comfortable for USB 2.0's 480 Mbit/s.
The RTL2832U register protocol
There is no official documentation; this is what the open-source community (osmocom's librtlsdr) worked out, and what our driver implements. Every register access is a vendor control transfer with request 0; the value and index fields say what to touch:
| Target | value | index | Notes |
|---|---|---|---|
| USB / system block register | register address | block << 8, +0x10 to write | Blocks: 1 = USB, 2 = system. Writes are big-endian. |
| Demodulator register | (addr << 8) | 0x20 | page, +0x10 to write | After each write, do a dummy read of page 0x0a register 1. Reads come back little-endian. |
| I2C (the tuner chip) | I2C address (0x34) | 6 << 8, +0x10 to write | First enable the I2C repeater: demod page 1 reg 1 = 0x18 (0x10 to disable). |
In code, all of it reduces to two helpers (src/rtlsdr.ts):
private writeReg(block: number, addr: number, val: number, len = 1) {
return this.out(addr, (block << 8) | 0x10, RtlSdr.be(val, len));
}
private async demodWrite(page: number, addr: number, val: number, len = 1) {
await this.out((addr << 8) | 0x20, 0x10 | page, RtlSdr.be(val, len));
await this.in((0x01 << 8) | 0x20, 0x0a, 1); // the chip expects this dummy read
}
Identifying the tuner: with the repeater on, read register 0 of I2C address 0x34 (R820T) or 0x74 (R828D). Both answer 0x69. Note that the R820T returns every byte you read with its bits in reverse order.
Start-up is about 30 register writes: power the demodulator, soft-reset it, load the resampler's filter, switch to SDR mode, then initialize the tuner. The full sequence, each write explained, is in initBaseband() and, decoded write by write, in course chapter 14.
Tuning and sample rate
Frequency is set in the tuner by programming its PLL: pick a divider that puts its internal oscillator between 1.77 and 3.54 GHz, then split the ratio to the 28.8 MHz crystal into an integer and a 16-bit fraction. From the driver:
const vcoFreq = freq * mixDiv;
const vcoDiv = Math.floor((this.xtal + 65536 * vcoFreq) / (2 * this.xtal));
const nint = Math.floor(vcoDiv / 65536), sdm = vcoDiv % 65536; // integer and fraction
Sample rate is one number in the RTL2832U: the ratio between its 28.8 MHz ADC and the rate you want. Valid rates: 225–300 kS/s and 900 kS/s–3.2 MS/s; above about 2.4 MS/s most dongles start dropping samples.
const ratio = Math.floor((28.8e6 * 2 ** 22) / rate) & 0x0ffffffc;
await this.demodWrite(1, 0x9f, ratio >>> 16, 2);
await this.demodWrite(1, 0xa1, ratio & 0xffff, 2);
Gain on the R820T is a ladder of LNA and mixer steps, 0 to ~48 dB, or automatic. The public API of our driver:
const sdr = await RtlSdr.request(); // picker + open + init
await sdr.setSampleRate(2_400_000); // returns the exact achieved rate
await sdr.setCenterFrequency(98.45e6);
await sdr.setGain(30); // dB, or null for automatic
await sdr.setPpm(0); // crystal correction, parts per million
await sdr.stream((bytes) => { /* … */ }); // until sdr.stop()
await sdr.close();
The data: what arrives
- Format: unsigned 8-bit, interleaved: I₀ Q₀ I₁ Q₁ … Each pair is one complex sample (course chapter 2). This is the same as
rtl_sdr's.cu8files, so recordings are interchangeable. - To numbers:
(byte − 127.5) / 127.5gives −1…+1. - What you're looking at: a slice of the radio band as wide as the sample rate, centered on the tuned frequency (course chapter 3). At 2.4 MS/s: center ± 1.2 MHz.
- Artifacts to expect: a spike at exactly 0 Hz (DC offset), so tune a little to one side of what you want; a faint mirror image of strong signals (I/Q imbalance); 8 bits ≈ 50 dB of range, so set the gain so strong signals don't clip.
Saving a recording other tools can open is a few lines with the File System Access API (Chrome):
const file = await (await showSaveFilePicker({ suggestedName: "fm_98.45M_2.4M.cu8" })).createWritable();
await sdr.stream((bytes) => file.write(bytes)); // later: sdr.stop(); await file.close();
Streaming without losing samples
The host must always have a bulk request waiting, or the dongle's small buffer overflows. So keep several transfers in flight and handle them strictly in order (stream() in the driver):
const queue = Array.from({ length: 4 }, () => dev.transferIn(1, 262144));
while (streaming) {
const r = await queue.shift(); // oldest first: samples stay in order
queue.push(dev.transferIn(1, 262144)); // immediately ask for more
onData(new Uint8Array(r.data.buffer));
}
Why "ask ahead"? The dongle has only a small buffer of its own. It fills at a steady rate no matter what your page is doing, and it's only emptied while a request from the computer is waiting. Below, a simulation with 1 ms steps. Compare the two strategies, and make the page slower:
With the naive loop, every time the page is busy (pink) there's no request waiting (no green), the dongle's buffer fills (blue), and once it's full (red) radio is thrown away. Occasional hiccups (here, 15% of chunks take 3× longer, like a browser pausing to tidy memory) are enough to lose data even when the page is fast on average. Untick it: with four requests queued, one is always waiting, the buffer never fills, and nothing is lost, as long as the page keeps up on average.
At 2.4 MS/s each 256 KiB transfer is about 55 ms of radio. Your onData must finish well within that on average. Heavy processing belongs in a Web Worker (post each chunk's ArrayBuffer as a transferable, so it moves without copying), and audio output in an AudioWorklet. Check for drops by comparing received bytes per second with 2 × the sample rate.
How the waterfall is drawn
The waterfall is the most recognizable picture in radio, and it's built from everything above in seven steps, repeated ~8–18 times a second. Here's every step on one screen, fed by a pretend radio band: two steady stations and a third that keeps switching on and off (watch it appear and vanish in the waterfall).
- Bytes from USB. Raw unsigned bytes, I and Q alternating; 127.5 means zero (blue I, pink Q bars).
- Numbers.
(byte − 127.5) / 127.5, so −1…+1. On their own they look like noise: several stations are added together (course chapter 3). - Window. Multiply each block by a smooth bump (yellow) that fades its ends to zero, so the block's edges don't create fake frequencies (course chapter 4).
- FFT → power. How much of each frequency is present. On a normal scale, only the strongest station shows; weak ones are smaller than a pixel.
- Decibels.
10 × log10(power)squeezes a range of a million to one into something you can see: now all three stations stand out. - Colors. Find the noise floor (the median bin), then color each bin by how far above it is: black → blue → magenta → yellow over 35 dB.
- Scroll. Shift the whole picture down one pixel and paint the new row on top. Time runs downward: the bottom is a few seconds ago.
Speed budget. At 2.4 MS/s, a 256 KiB chunk arrives every ~55 ms. Turning it into one row costs 16 FFTs of 512 points (about 0.01 ms each in a browser) plus 512 color lookups: well under a millisecond, which leaves plenty of time for audio. Drawing happens at the screen's pace (requestAnimationFrame), not the data's.
Choosing the FFT size. More bins mean finer detail in frequency but coarser in time. 512 bins across 1.024 MHz means each column is 2 kHz wide, plenty to separate FM stations 200 kHz apart. To see narrow signals (Morse, data bursts), use more bins (4096+) and average fewer blocks.
Read the real code
Three files, shown exactly as they are on this site (loaded from the source when the page is built, so they can't go out of date). Click any highlighted part of the code to jump to its explanation, or click an explanation to find its code.
The starter app: the whole thing
The waterfall
The driver
The network source: our server's API
server.ts runs the same driver in Node (through the usb package's WebUSB implementation), owns the dongle, and serves plain HTTP. Three endpoints:
| Request | Does |
|---|---|
GET /api/state | JSON: {"tuner":"R820T","rate":2400000,"center":98450000,"gain":32.8,"listeners":1,"half":1080000} |
POST /api/tune body {"center":98450000,"gain":30} | Retunes the shared dongle (either field optional; gain: null = automatic). A center that would leave someone's slice outside the window is refused (409). |
GET /api/stream?center=Hz&width=240000|1200000&id=… | An endless application/octet-stream of cu8 bytes: your slice of the dongle's shared 2.4 MHz window, centered on center (header x-center) at the rate in x-sample-rate (the width). Without parameters: the window's middle, 1.2 MHz wide. ?raw=1 (the whole window) works only on the server's own network. The dongle opens on the first listener and closes 5 s after the last; a slice the shared window can't reach gets 409 with the reason. |
POST /api/slice body {"id":"…","center":100300000} | Moves your slice. The window moves only if it can still cover everyone's slices (else 409). |
GET /api/overview | Server-sent events: band (window center, rate, gain, listeners, everyone's slices) and row (a 1024-bin spectrum of the whole window, base64 bytes, ¼ dB above the floor per step). |
# record 5 seconds from the command line
curl -s http://your-server:8073/api/stream --max-time 5 -o capture.cu8
# retune
curl -X POST http://your-server:8073/api/tune -d '{"center": 100.3e6}'
In a page, fetch() reads the stream chunk by chunk (src/remote.ts). Network reads arrive in odd sizes, so regroup them, and keep I/Q pairs together:
const reader = (await fetch("/api/stream")).body.getReader();
for (;;) {
const { value, done } = await reader.read(); // a Uint8Array of any size
if (done) break;
// append to a buffer; hand on whole I/Q pairs once you have ~64 KiB
}
Bandwidth: at 1.024 MS/s the raw stream is 2 MB/s per listener. That's fine on a home network but too much for the internet; a public server must instead send each listener only the narrow slice they're tuned to (the course's chapter 15).
The standard alternative: rtl_tcp, which many SDR apps speak. On connect it sends a 12-byte header ("RTL0", tuner type, gain count as big-endian 32-bit numbers), then raw cu8 forever; commands are 5 bytes each: a command byte plus a big-endian 32-bit value (1 = frequency in Hz, 2 = sample rate, 3 = gain mode, 4 = gain in tenths of a dB). Browsers can't open raw TCP sockets, which is why our server speaks HTTP.
Things you could build
A recorder
Stream to a .cu8 file (snippet above), then open it in Spectrum Lab, GQRX or SDR++.
A band scanner
Step the frequency, measure the strength of each channel, list the strong ones. Our scripts/fm-scan.ts does this for the FM band in ~60 lines.
A spectrum logger
Record the strength across a band every minute for a day: when is the band busy? Great for finding interference.
ADS-B plane tracker
Tune 1090 MHz at 2 MS/s and decode the short pulses aircraft send. Pure byte crunching, no audio needed.
Weather radio alerts
NOAA weather radio on 162.4–162.55 MHz (narrow FM), plus a squelch: notify when someone speaks.
Your own receiver
Follow the course: every chapter's code is the real receiver, one piece at a time.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
Connect button disabled, navigator.usb undefined | Not a secure page, or not a Chromium browser. Use https:// or localhost, in Chrome/Edge/Opera. |
| Picker shows no devices | Dongle not plugged in, or its USB IDs aren't in your filter (some dongles use 0bda:2832). |
| "Access denied" (Windows) | No WinUSB driver on the dongle. Install it with Zadig. |
| "The dongle is in use" / can't claim interface | Another program has it (SDR#, GQRX, rtl_tcp, a server SDR), or on Linux the TV driver. Close it or blacklist dvb_usb_rtl28xxu. |
| "Unsupported tuner" | An old E4000 / FC0012 / FC0013 dongle. Our driver supports R820T, R820T2 and R828D. |
| Samples per second below the rate you set | Too few bulk transfers in flight, or onData too slow. Move processing to a worker; lower the rate. |
| Only noise where a station should be | Check the spectrum first: is the station there and strong? Then check gain (clipping or too low), the antenna connection, and nearby electronics (laptops and chargers radiate at radio frequencies). |
| Errors right after reconnecting | A dongle closed moments ago can stall its first commands. Our driver resets it and retries once; if yours doesn't, wait a second before reopening. |
Credits: the RTL2832U and R820T register knowledge comes from years of community reverse-engineering, above all osmocom's librtlsdr and the Linux kernel drivers. The implementation here is our own TypeScript.
Last updated