---
title: "Software radio: from antenna to baseband"
heading: How a software radio digitizes a wide slice of spectrum as complex I/Q samples, why complex samples tell positive from negative frequencies, tuning a station by multiplying with a complex exponential, a windowed-sinc channel filter, and decimating to a lower rate without letting the neighbors fold in
eyebrow: D13 · Lesson 5 · Software radio
xp: 40
---

::: hook
A software-defined radio does almost everything in code. Its hardware is a tuner that shifts a band of spectrum down near zero and an ADC pair that samples it as **I** and **Q**, the real and imaginary parts of a complex signal. Everything after that, choosing a station, filtering out the neighbors, demodulating and decoding, is arithmetic on those samples. This project builds a receiver that picks one narrowband FM station out of a 96 kHz-wide recording and decodes a data packet from it.
:::

::: play
- Three FM stations in a slice of spectrum, 15 kHz apart, the one at 45 kHz four times as strong as the one at 30 kHz you want. The dashed markers show a ±4.8 kHz channel around the tuning frequency $f_0$.
- Tune to each station. The channel filter will pass what's between the markers and throw away the rest.
- Notice how much energy sits just outside the channel: the filter's skirts have to fall fast, or a strong neighbor leaks in.
:::

```sim plot
view: spectrum
x: t = 0..20m s
y: v = -4..4
samples: 4096
freq: f = 0..60k Hz
scale: db
window: hann
slider: f0 = 10000..50000 step 500 = 30000 Hz
plot: cos(2*pi*15000*t + 2500/700*sin(2*pi*700*t)) + 0.5*cos(2*pi*30000*t + 2500/1200*sin(2*pi*1200*t)) + 2*cos(2*pi*45000*t + 2500/1500*sin(2*pi*1500*t)) | label: three FM stations
marker: f = f0 - 4800 | label: channel edge
marker: f = f0 + 4800 | label: channel edge
```

::: predict
## The recording is sampled at 96 kHz. You keep every 10th sample to get 9.6 kHz, without filtering first. Where does a strong station 20 kHz above the wanted one end up?

- [ ] It disappears, since it's outside 9.6 kHz
- [x] At 0.8 kHz, right inside the wanted channel
- [ ] At 20 kHz, unchanged
- [ ] At 10.4 kHz

::: reveal
At 9.6 kHz, frequencies are only distinct modulo 9.6 kHz, so 20 kHz lands at 20 − 2 × 9.6 = 0.8 kHz, on top of the wanted signal and four times stronger. Decimation must always follow a low-pass filter that removes everything the new rate can't represent.
:::
:::

::: nameit
## Complex baseband

With I and Q samples, $x[n] = I[n] + jQ[n]$, a component at frequency f is $e^{j2\pi fn/f_s}$, and f can be negative: a 96 kHz complex stream covers −48 to +48 kHz with no mirror images. A real ADC alone would confuse f with −f.

## Tuning

Multiplying by $e^{-j2\pi f_0n/f_s}$ shifts every frequency down by $f_0$, so the wanted station moves to 0 Hz.

## The channel filter

A **windowed-sinc** low-pass with N taps, cutoff $f_c$ and a Hamming window:

$$h[k] = \frac{2f_c}{f_s}\operatorname{sinc}\left(\frac{2f_c}{f_s}\left(k - \frac{N - 1}{2}\right)\right)w[k]$$

normalized to unit gain at 0 Hz. Its response is 6 dB down at $f_c$, the transition takes about $3.3f_s/N$, and the stopband sits about 53 dB down for the Hamming window (S7). With 129 taps at 96 kHz the transition is about 2.5 kHz wide.

## Decimation

After filtering, keeping every D-th sample gives a rate $f_s/D$ without aliasing, since nothing remains above $f_s/2D$. Each factor of 10 also cuts the computation for every later stage by 10, and the filtering lowers the noise in the channel: the noise that was spread over 96 kHz is now confined to 9.6 kHz.
:::

::: example
## Design the channel filter for a ±4.8 kHz channel at 96 kHz with a Hamming window. How many taps for a 2.5 kHz transition, and how does it do?

::: solution
1. **Estimate the length.**
   $$\begin{aligned} N &\approx 3.3 \times \frac{96\,000}{2500} \\ &\approx 127 \end{aligned}$$
2. **Pick an odd length with some margin.** The estimate is only a guide, so go one odd length past it to 129 taps. An odd length keeps the delay a whole number of samples (64).
3. **Measured response.** The lab's filter measures
   $$\begin{aligned} 4\ \text{kHz:}\ &-0.6\ \text{dB} \\ 4.8\ \text{kHz:}\ &-6.0\ \text{dB} \\ 6\ \text{kHz:}\ &-47\ \text{dB} \\ 9.6\ \text{kHz:}\ &-68.5\ \text{dB} \end{aligned}$$
   with no sidelobe above −55 dB beyond 7 kHz or above −63 dB beyond 20 kHz.
4. **A strong neighbor.** A neighbor four times (12 dB) stronger 20 kHz away comes through at least
   $$63 - 12 = 51\ \text{dB}$$
   below the wanted signal, under 0.3%.

**Answer:** 129 taps, which pass 4 kHz at −0.6 dB and keep a neighbor 20 kHz away at least 51 dB below the wanted signal.
:::
:::

::: example
## A station sits at −25 kHz in the recording, and you tune to +10 kHz. Where does it land, and what happens after the filter and decimation by 10?

::: solution
1. **Tune.** Tuning to +10 kHz shifts the station to
   $$-25 - 10 = -35\ \text{kHz}$$
   far into the stopband, where it's more than 80 dB down.
2. **Decimate to 9.6 kHz.** What's left of it would alias to
   $$-35 + 4 \times 9.6 = 3.4\ \text{kHz}$$
3. **Is it a problem?** At that level it's harmless.

**Answer:** it lands at −35 kHz, more than 80 dB down, and after decimation its remains alias to 3.4 kHz, too weak to matter.
:::
:::

::: check
kind: python

## Tune a station to 0 Hz, filter its channel and decimate to 9.6 kHz.

```python starter
import numpy as np

FS = 96000   # the recording's complex sample rate

def tune(x, f0):
    # Shift the station at f0 Hz down to 0 Hz: multiply sample n by exp(-2j*pi*f0*n/FS).
    return np.asarray(x, dtype=complex)

def lowpass_taps(cutoff, ntaps=129):
    # A windowed-sinc low-pass filter: tap k (0 to ntaps - 1) is
    # 2*cutoff/FS * sinc(2*cutoff/FS*(k - M)) * hamming[k], with M = (ntaps - 1)/2 and
    # hamming = np.hamming(ntaps). Scale the taps so they add up to 1 (unit gain at 0 Hz).
    return np.r_[1.0, np.zeros(ntaps - 1)]

def channelize(x, f0, cutoff=4800.0, decim=10):
    # Tune to f0, filter with np.convolve(..., mode='same'), and keep every decim-th sample.
    return np.asarray(x, dtype=complex)[::decim]
```

```python solution
import numpy as np

FS = 96000   # the recording's complex sample rate

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):
    y = np.convolve(tune(x, f0), lowpass_taps(cutoff), mode='same')
    return y[::decim]
```

```python tests
_n = np.arange(96000)
_cw = lambda f, a: a*np.exp(2j*np.pi*f*_n/FS)
assert np.allclose(tune(_cw(10000, 1.0), 10000), 1.0), "Tuning to a carrier's frequency turns it into a constant."
_h = lowpass_taps(4800)
assert len(_h) == 129 and abs(np.sum(_h) - 1) < 1e-12 and np.allclose(_h, _h[::-1]), "129 symmetric taps with unit gain at 0 Hz."
_H = lambda f: abs(np.sum(_h*np.exp(-2j*np.pi*f*np.arange(129)/FS)))
assert _H(2000) > 0.99 and _H(9600) < 0.003, f"Flat in the channel and at least 50 dB down a channel away: |H(2 kHz)| = {_H(2000):.4f}, |H(9.6 kHz)| = {_H(9600):.5f}."
_x = _cw(-25000, 1.0) + _cw(10000, 0.5) + _cw(30000, 2.0)
_y = channelize(_x, 10000)
assert len(_y) == 9600, "Decimating one second by 10 leaves 9600 samples."
assert np.allclose(np.abs(_y[100:-100]), 0.5, atol=0.005), "The wanted station comes through at its own level, 0.5."
_z = channelize(_cw(-25000, 1.0) + _cw(30000, 2.0), 10000)
assert np.max(np.abs(_z[100:-100])) < 0.005, f"The neighbors, even the one four times stronger, are filtered out before decimation can fold them in; leftover {np.max(np.abs(_z[100:-100])):.4f}."
```

::: right
Right. Your channelizer passes the wanted station at its own level and removes neighbors four times stronger before they can alias.
:::
:::

::: check
given: D = 20 | 25 | 35; F = 9.6 | 12
answer: abs(D - F*round(D/F))
unit: kHz
tolerance: 0.5%

## A signal {D} kHz from the tuned frequency survives into a decimated stream at {F} kHz. Where does it alias to, in absolute frequency from 0?

::: right
Right. Frequencies wrap modulo {F} kHz: {answer} kHz.
:::

::: misses
- [D - F] It keeps wrapping until it lands within half the new rate of zero.
- [any] Not yet. Subtract the nearest multiple of the new sample rate.
:::
:::

::: check
given: s = 48000 | 96000 | 240000; w = 1000 | 2500 | 5000
answer: 3.3*s/w
tolerance: 1%

## About how many taps does a Hamming-windowed sinc filter need for a {w} Hz transition at {s} samples per second?

::: right
Right. $3.3f_s/\Delta f$ ≈ {answer} taps.
:::

::: misses
- [s/w] The Hamming window's transition is about 3.3 bins wide.
- [any] Not yet. Transition width is about $3.3f_s/N$.
:::
:::

::: check
given: s = 96 | 240 | 2400; D = 4 | 10 | 25
answer: s/D
unit: kHz
tolerance: 0.5%

## A {s} kHz stream is filtered and decimated by {D}. What's the new sample rate?

::: right
Right. {answer} kHz.
:::

::: misses
- [s*D] Decimation lowers the rate.
- [any] Not yet. Keep one sample in D.
:::
:::

::: check
kind: parts
given: fs = 2.4 | 2.048; f = 100.3 | 101.1; fc = 100.7 | 100.9

## A software radio samples complex I/Q at {fs} MS/s, tuned to {fc} MHz.

::: part
answer: (f - fc)*1e3
unit: kHz
tolerance: 0.5%

### At what baseband frequency does a station at {f} MHz appear? (Negative if below the tuning.)

::: misses
- [(fc - f)*1e3] Baseband frequency is the station minus the tuning.
- [any] Not yet. $f - f_c$.
:::
:::

::: part
answer: fs*1e3
unit: kHz
tolerance: 0.5%

### How much bandwidth do the complex samples cover in total?

::: misses
- [fs*1e3/2] Complex samples cover $-f_s/2$ to $+f_s/2$: the whole $f_s$.
- [any] Not yet. With I and Q, the span is $f_s$.
:::
:::

::: right
Right. Complex sampling sees both sides of the tuning frequency, unlike a real-valued signal.
:::
:::

::: check
given: fs = 2400 | 2048 | 1920; t = 48 | 240 | 256
answer: fs/t
tolerance: 0.5%

## A software radio decimates {fs} kS/s down to {t} kS/s for one channel. What decimation factor is that?

::: right
Right: {answer}. Filter first, then keep one sample in {answer}, or the out-of-channel signals alias in.
:::

::: misses
- [t/fs] Decimation divides the rate: input over output.
- [any] Not yet. Input rate ÷ output rate.
:::
:::

::: explain
## Why must a receiver filter before it decimates?

::: model
Keeping only every D-th sample lowers the sample rate, and at the new rate frequencies are only distinguishable up to half of it; anything higher folds back and lands on top of lower frequencies, where it can't be separated any more. In a recording full of other stations, those stations would fold right into the wanted channel. Low-pass filtering first removes everything above half the new rate while the higher rate can still tell them apart, so the decimated signal contains only the wanted channel and the noise within it.
:::
:::

::: practice

::: check
given: D = 7 | 13 | 31 | 47; F = 8 | 9.6
answer: abs(D - F*round(D/F))
unit: kHz
tolerance: 0.5%

## Alias of {D} kHz at {F} kHz?

::: misses
- [any] Subtract the nearest multiple of the rate.
:::
:::

::: check
given: s = 8000 | 1e6; w = 100 | 20000
answer: 3.3*s/w
tolerance: 1%

## Taps for a {w} Hz transition at {s} Hz?

::: misses
- [any] $3.3f_s/\Delta f$.
:::
:::
:::
