---
title: "Software radio: a complete receiver"
heading: Assembling the software radio from front-end gain to decoded text, planning the analog gain so the ADC is neither overloaded nor buried in its own noise, then tuning, filtering, demodulating FM and decoding an audio-tone packet with a CRC, all in code
eyebrow: D13 · Lesson 7 · Software radio
xp: 120
---

::: hook
The last step joins the pieces: the analog front end sets the level at the ADC, and the code does the rest. The station you want carries a packet the way amateur radio's APRS does: as audio tones, D12's 1200 and 2200 Hz FSK, sent over an ordinary narrowband FM transmitter. Your receiver has to tune to it in a recording that also holds two other stations, one much stronger, demodulate the FM to get the audio, and decode the packet from the audio, finding it at an unknown time and checking its CRC.
:::

::: play
- The front end's level plan: an antenna signal passes an LNA, a mixer and an IF amplifier on its way to a 12-bit ADC whose full scale is 0 dBm.
- The ADC's own noise sits 6.02 × 12 + 1.76 = 74 dB below full scale across 48 kHz; in a 4.8 kHz channel, filtering lowers it a further 10 dB. The readouts show the headroom left before clipping and how far the signal sits above the ADC's noise.
- Too little gain buries a weak station in ADC noise; too much lets a strong neighbor clip the ADC, which wrecks every station at once. Find the gain that suits signals from −110 to −40 dBm.
:::

```sim plot
view: chain
input: S | label: antenna
stage: G | label: LNA
stage: -7 | label: mixer
stage: 20 | label: IF amplifier
stage: -2 | label: anti-alias filter
y: L = -130..10 dBm
slider: S = -120..-20 = -90 dBm
slider: G = 0..40 = 20 dB
readout: headroom before the ADC clips, dB = -(S + G + 11)
readout: above the ADC's noise in the channel, dB = S + G + 11 + 84
```

::: predict
## A 12-bit ADC digitizes 48 kHz of spectrum, and the receiver keeps a 4.8 kHz channel. How far below full scale is the ADC's quantization noise within that channel?

- [ ] 74 dB
- [x] 84 dB
- [ ] 64 dB
- [ ] 94 dB

::: reveal
Quantization noise is 6.02 × 12 + 1.76 = 74 dB below a full-scale sine, spread evenly over 0 to 48 kHz. The channel keeps a tenth of that band, so a tenth of the noise: 10 dB less, 84 dB below full scale. This processing gain is why software radios can use modest ADCs and still hear weak stations.
:::
:::

::: nameit
## Gain planning

The analog gain before the ADC should put the strongest expected signal a few dB below full scale and the weakest wanted one comfortably above the ADC's noise in the channel:

$$\text{SNR}_\text{ADC} = 6.02N + 1.76\ \text{dB}, \qquad \text{in the channel: } + 10\log_{10}\frac{f_s/2}{B}$$

The **dynamic range** between clipping and that floor is what lets a weak station be decoded next to a strong one. Real receivers add automatic gain control to slide the window with conditions.

## The receiver chain

1. **Channelize:** tune the station to 0 Hz, low-pass filter to ±4.8 kHz and decimate from 96 to 9.6 kHz (lesson 5).
2. **Demodulate:** the discriminator turns the FM into audio (lesson 6).
3. **Decode:** the audio carries 1200 baud FSK at 8 samples per bit, so D12's correlators recover the bits; the receiver tries each of 8 sampling offsets, searches for sync words one after another, reads each candidate frame and keeps the first whose CRC checks.

## Why search for more than one sync word

Before the packet, the channel carries noise, and a random stretch of bits matches the sync word within one error about once every 3900 bits (D12). A receiver that gave up after the first match would sometimes miss a perfectly good packet behind a false one. Moving on to the next candidate costs little, and the CRC rejects the false ones.
:::

::: example
## With 20 dB of LNA gain, what's the window of antenna levels the front end can handle?

::: solution
1. **Gain to the ADC.** The other stages add
   $$-7 + 20 - 2 = 11\ \text{dB}$$
   so with the LNA's 20 dB the ADC sees S + 31 dBm.
2. **The window.** Clipping starts at S = −31 dBm, and the ADC's channel noise (−84 dBm at the ADC) is reached at S = −115 dBm:
   $$-31 - (-115) = 84\ \text{dB}$$
3. **A weak station.** A −110 dBm station then sits only 5 dB above the ADC noise, so the gain should be raised until the analog front end's own noise sits above the ADC's and sets the floor.
4. **The cost of more gain.** More LNA gain helps the weak station but brings clipping down to −41 dBm.

**Answer:** antenna levels from −115 dBm to −31 dBm, an 84 dB window.
:::
:::

::: example
## How long does the lab's longest message, "CQ from the software radio" (26 characters), take on the air?

::: solution
1. **Frame length.** D12's frame is
   $$8 \times 26 + 80 = 288\ \text{bits}$$
2. **Airtime at 1200 baud.**
   $$\begin{aligned} t &= \frac{288}{1200}\ \text{s} \\ &= 0.24\ \text{s} \end{aligned}$$
3. **The lead-in.** The lab's recordings start up to 0.094 s (9000 samples at 96 kHz) earlier with unmodulated carrier, where the receiver's bits are just noise and the occasional false sync match.

**Answer:** 0.24 s, after up to 0.094 s of unmodulated carrier in the lab's recordings.
:::
:::

::: check
kind: python

## Build the whole receiver: tune the station, demodulate its FM and decode the packet from its audio.

```python starter
import numpy as np

# From lessons 5 and 6: tuning, the channel filter, decimation and the FM discriminator.
FS = 96000

def tune(x, f0):
    n = np.arange(len(x))
    return np.asarray(x)*np.exp(-2j*np.pi*f0*n/FS)

def lowpass_taps(cutoff, ntaps=129):
    m = (ntaps - 1)/2
    k = np.arange(ntaps)
    h = 2*cutoff/FS*np.sinc(2*cutoff/FS*(k - m))*np.hamming(ntaps)
    return h/np.sum(h)

def channelize(x, f0, cutoff=4800.0, decim=10):
    return np.convolve(tune(x, f0), lowpass_taps(cutoff), mode='same')[::decim]

def fm_demod(z, fs):
    return np.angle(z[1:]*np.conj(z[:-1]))*fs/(2*np.pi)

# From D12: FSK correlators at 9600 samples per second, the sync word and the CRC.
SPS = 8
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]

def fsk_demod(audio):
    n = np.arange(SPS)
    pm, ps = np.exp(-2j*np.pi*1200*n/9600), np.exp(-2j*np.pi*2200*n/9600)
    blocks = np.asarray(audio[:len(audio)//SPS*SPS]).reshape(-1, SPS)
    return list((np.abs(blocks @ pm) > np.abs(blocks @ ps)).astype(int))

def find_sync(bits, start=0, max_errors=1):
    # The index just after the first sync word at or after start, or -1.
    for i in range(start, len(bits) - 15):
        if sum(a != b for a, b in zip(bits[i:i + 16], SYNC)) <= max_errors:
            return i + 16
    return -1

def from_bits(bits):
    v = 0
    for b in bits:
        v = 2*v + b
    return v

def crc16(data):
    reg = 0xFFFF
    for byte in data:
        reg ^= byte << 8
        for _ in range(8):
            reg = ((reg << 1) ^ 0x1021) if reg & 0x8000 else (reg << 1)
            reg &= 0xFFFF
    return reg

def receive_station(iq, f0):
    # iq is a recording at FS samples per second holding several FM stations. Bring the one at
    # f0 Hz down to 9600 samples per second with channelize, demodulate it with fm_demod (its
    # output is the station's audio), then decode a D12 frame from the audio: for each of the
    # SPS sampling offsets, demodulate the bits and look for sync words one after another; after
    # each, read the length byte and payload, and if crc16 of the payload is 0, return its text
    # (the payload without its last two bytes, decoded as ASCII). Return None if nothing passes.
    return None
```

```python solution
import numpy as np

# From lessons 5 and 6: tuning, the channel filter, decimation and the FM discriminator.
FS = 96000

def tune(x, f0):
    n = np.arange(len(x))
    return np.asarray(x)*np.exp(-2j*np.pi*f0*n/FS)

def lowpass_taps(cutoff, ntaps=129):
    m = (ntaps - 1)/2
    k = np.arange(ntaps)
    h = 2*cutoff/FS*np.sinc(2*cutoff/FS*(k - m))*np.hamming(ntaps)
    return h/np.sum(h)

def channelize(x, f0, cutoff=4800.0, decim=10):
    return np.convolve(tune(x, f0), lowpass_taps(cutoff), mode='same')[::decim]

def fm_demod(z, fs):
    return np.angle(z[1:]*np.conj(z[:-1]))*fs/(2*np.pi)

# From D12: FSK correlators at 9600 samples per second, the sync word and the CRC.
SPS = 8
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]

def fsk_demod(audio):
    n = np.arange(SPS)
    pm, ps = np.exp(-2j*np.pi*1200*n/9600), np.exp(-2j*np.pi*2200*n/9600)
    blocks = np.asarray(audio[:len(audio)//SPS*SPS]).reshape(-1, SPS)
    return list((np.abs(blocks @ pm) > np.abs(blocks @ ps)).astype(int))

def find_sync(bits, start=0, max_errors=1):
    # The index just after the first sync word at or after start, or -1.
    for i in range(start, len(bits) - 15):
        if sum(a != b for a, b in zip(bits[i:i + 16], SYNC)) <= max_errors:
            return i + 16
    return -1

def from_bits(bits):
    v = 0
    for b in bits:
        v = 2*v + b
    return v

def crc16(data):
    reg = 0xFFFF
    for byte in data:
        reg ^= byte << 8
        for _ in range(8):
            reg = ((reg << 1) ^ 0x1021) if reg & 0x8000 else (reg << 1)
            reg &= 0xFFFF
    return reg

def receive_station(iq, f0):
    audio = fm_demod(channelize(iq, f0), 9600)
    for k in range(SPS):
        bits = fsk_demod(audio[k:])
        i = find_sync(bits)
        while i >= 0:
            if i + 8 <= len(bits):
                n = from_bits(bits[i:i + 8])
                body = bits[i + 8:i + 8 + 8*n]
                if n >= 2 and len(body) == 8*n:
                    payload = bytes(from_bits(body[8*j:8*j + 8]) for j in range(n))
                    if crc16(payload) == 0:
                        return payload[:-2].decode('ascii', errors='replace')
            i = find_sync(bits, i - 15)
    return None
```

```python tests
def _frame(text):
    d = text.encode('ascii'); c = crc16(d); p = d + bytes([c >> 8, c & 0xFF])
    b = [1, 0]*16 + SYNC + [(len(p) >> (7 - i)) & 1 for i in range(8)]
    for x in p:
        b += [(x >> (7 - i)) & 1 for i in range(8)]
    return b + [1]*8

def _afsk(bits, lead):
    # Audio at FS: silence, then 1200/2200 Hz FSK at 1200 baud (80 samples per bit).
    f = np.r_[np.zeros(lead), np.repeat([1200.0 if b else 2200.0 for b in bits], FS//1200), np.zeros(4000)]
    ph = np.cumsum(2*np.pi*f/FS)
    a = np.cos(ph)
    a[:lead] = 0
    return a

def _station(audio, f0, amp, dev=2500):
    n = np.arange(len(audio))
    return amp*np.exp(1j*(2*np.pi*dev*np.cumsum(audio)/FS + 2*np.pi*f0*n/FS))

def _air(text, rng):
    a = _afsk(_frame(text), int(rng.integers(2000, 9000)))
    t = np.arange(len(a))/FS
    x = _station(a, 10000, 0.5) + _station(np.sin(2*np.pi*700*t), -25000, 1.0) + _station(np.sin(2*np.pi*1500*t), 30000, 2.0)
    return x + 0.02*(rng.standard_normal(len(x)) + 1j*rng.standard_normal(len(x)))

_rng = np.random.default_rng(7)
for _msg in ("CQ from the software radio", "station B, 10 kHz", "decoded!"):
    _got = receive_station(_air(_msg, _rng), 10000)
    assert _got == _msg, f"Tuned to 10 kHz, the packet should come through; sent {_msg!r}, got {_got!r}."
assert receive_station(_air("nothing here", _rng), 30000) is None, "The station at 30 kHz carries only a tone, so there's no packet to find."
```

::: right
Right. Your software radio pulls the packet out of a recording with two other stations, one four times stronger, and finds nothing on a station that carries only a tone.
:::
:::

::: check
given: N = 8 | 10 | 12 | 14 | 16
answer: 6.02*N + 1.76
unit: dB
tolerance: 0.5%

## What SNR does an ideal {N}-bit ADC give for a full-scale sine across its whole band?

::: right
Right. $6.02N + 1.76$ = {answer} dB.
:::

::: misses
- [6.02*N] Add 1.76 dB for a full-scale sine.
- [any] Not yet. About 6 dB per bit.
:::
:::

::: check
given: s = 96 | 240 | 2400; B = 4.8 | 12.5 | 200
answer: 10*log(s/2/B)
unit: dB
tolerance: 0.5%

## A receiver samples at {s} kHz and keeps a {B} kHz-wide channel. How much does filtering lower the ADC's noise in the channel?

::: right
Right. $10\log_{10}\frac{f_s/2}{B}$ = {answer} dB.
:::

::: misses
- [10*log(s/B)] The noise is spread over 0 to $f_s/2$, half the sample rate.
- [any] Not yet. The fraction of the band the channel keeps.
:::
:::

::: check
given: G = 10 | 20 | 30 | 40
answer: -(G + 11)
unit: dBm
tolerance: 0.5%

## In the level plan above, the LNA has {G} dB of gain and the ADC clips at 0 dBm. At what antenna level does clipping begin?

::: right
Right. The chain adds {G} − 7 + 20 − 2 dB, so clipping starts at {answer} dBm.
:::

::: misses
- [-G] Count the mixer, the IF amplifier and the filter too.
- [any] Not yet. Full scale minus the chain's total gain.
:::
:::

::: check
kind: parts
given: fs = 9.6 | 24 | 48; n = 100 | 330

## An AFSK packet at 1200 baud (Bell 202: 1200 and 2200 Hz tones) is sampled at {fs} kHz and has {n} bits.

::: part
answer: fs*1e3/1200
tolerance: 0.5%

### How many samples cover each bit?

::: misses
- [fs*1e3/2200] Bits last 1/1200 s regardless of which tone carries them.
- [any] Not yet. Sample rate ÷ baud.
:::
:::

::: part
answer: n/1200*1e3
unit: ms
tolerance: 0.5%

### How long does the packet last?

::: misses
- [n/2200*1e3] The bit rate is 1200 per second.
- [any] Not yet. Bits ÷ 1200 b/s.
:::
:::

::: right
Right. The decoder correlates each bit's {fs}-kHz samples against both tones and picks the stronger.
:::
:::

::: check
given: f1 = 1300 | 2100 | 2200
answer: f1/1200
tolerance: 0.5%

## How many cycles of a {f1} Hz tone fit in one 1200-baud bit?

::: right
Right: {answer}. A correlator compares how much of each tone fits a bit, so tones that differ by about a whole cycle per bit are easy to tell apart.
:::

::: misses
- [1200/f1] Cycles per bit = tone frequency × bit time.
- [any] Not yet. $f \times (1/1200\text{ s})$.
:::
:::

::: explain
## Why does a software radio filter and decimate before it demodulates?

::: model
The raw recording holds many stations and a wide band of noise at a high sample rate. Filtering to the wanted channel removes the other stations, which would otherwise corrupt the discriminator's phase measurement, and removes most of the noise, since noise is spread across the whole band and the channel keeps only a slice of it. Decimating afterward lowers the sample rate to one just wide enough for the channel, so every later step, demodulation and decoding, handles a tenth or less of the samples. Demodulating first would mix all the stations and the wideband noise into the audio, where they could no longer be separated.
:::
:::

::: practice

::: check
given: N = 6 | 18 | 24
answer: 6.02*N + 1.76
unit: dB
tolerance: 0.5%

## Ideal ADC SNR, {N} bits?

::: misses
- [any] $6.02N + 1.76$.
:::
:::

::: check
given: s = 48 | 20000; B = 3 | 10
answer: 10*log(s/2/B)
unit: dB
tolerance: 0.5%

## Processing gain: {s} kHz rate, {B} kHz channel?

::: misses
- [any] $10\log_{10}(f_s/2B)$.
:::
:::
:::
