---
title: "Capstone: an acoustic modem"
heading: Putting every stage together into a modem that sends text as sound, framing with a CRC, FSK modulation, a receiver that finds the frame at an unknown time and sampling phase through echoes and noise, and estimating how far apart a speaker and a microphone can be
eyebrow: D12 · Lesson 14 · Capstone
xp: 120
---

::: hook
Everything so far adds up to a complete link: text to bits, bits to a frame with a sync word and a CRC, the frame to FSK tones, tones through a room with an unknown delay, echoes and noise, and back. In this capstone you build the transmitter and the receiver end to end and send messages through a simulated room. The receiver has to find the message on its own, at an unknown moment and sampling phase, and it accepts only frames whose CRC checks, so a damaged message is rejected rather than printed wrong.
:::

::: play
- How often a message gets through, against the distance from speaker to microphone. The speaker produces L dB SPL at 1 m, the room's noise in the modem's 4 kHz band is N dB SPL, and the message is n characters long.
- Sound falls 6 dB per doubling of distance. $E_b/N_0$ is the SNR times 4000/1200, and each bit is wrong with probability $\frac{1}{2}e^{-E_b/2N_0}$ for orthogonal noncoherent FSK (this modem's tones leak at −14 dB, so it does a little worse).
- A frame needs all its 8n + 40 checked bits right, so success collapses quickly once the SNR runs out. Longer messages fail sooner.
:::

```sim plot
view: graph
x: d = 0.1..30 log
y: P = 0..1.05
slider: L = 50..90 step 1 = 70
slider: N = 20..60 step 1 = 45
slider: n = 1..100 step 1 = 20
plot: (1 - 0.5*exp(-10^((L - 20*log(d) - N)/10)*(10/3)/2))^(8*n + 40) | samples: 600 | label: chance a frame gets through (d in m)
readout: range for 90% success, m = 10^((L - N + 10*log(10/3) - 10*log(-2*ln(2*(1 - 0.9^(1/(8*n + 40))))))/20) | digits: 3
readout: frame airtime, s = (8*n + 80)/1200 | digits: 3
```

::: predict
## A phone that decodes reliably 1 m from the speaker is moved to 4 m. How much SNR does it lose?

- [ ] 4 dB
- [ ] 6 dB
- [x] 12 dB
- [ ] 16 dB

::: reveal
Sound pressure from a small source falls as 1/d, so the level drops by $20\log_{10}(4)$ = 12 dB, 6 dB for each doubling. Echoes in a real room add some energy back, but the direct path is what the receiver locks onto.
:::
:::

::: nameit
## The transmitter

1. The text's ASCII bytes, then their CRC-16 (lesson 12), make the **payload**.
2. The frame is 32 preamble bits, the sync word 0xD391, a length byte counting the payload's bytes, the payload, and 8 tail bits so the last real bit isn't cut short (lesson 2). That's 8n + 80 bits for n characters.
3. Continuous-phase FSK at 1200 baud, 1200 and 2200 Hz, 9600 samples per second (lesson 3).

## The receiver

1. The frame can start at any sample, so the receiver tries each of the 8 sampling offsets (lesson 5).
2. For each, it demodulates with tone correlators (lesson 4) and searches for the sync word, allowing one wrong bit.
3. It reads the length and the payload, and accepts the frame only if the CRC over the payload, CRC included, comes out 0.

Wrong offsets either miss the sync word or produce a payload that fails the CRC, so the first frame that passes is the right one with a false-acceptance chance of $2^{-16}$ per attempt.

## Link budget

With the speaker's level L at 1 m and noise N in the band, the SNR at distance d is $L - 20\log_{10}d - N$ dB, and $E_b/N_0$ is that plus $10\log_{10}(4000/1200)$ = 5.2 dB. A frame of $N_b$ checked bits survives with probability $(1 - p)^{N_b}$.

## Through real air

Pyodide in the browser can't use the microphone, so this lab sends its audio through a simulated room. The same functions work on a laptop: play `transmit()`'s samples at 9600 samples per second on one device, record on another, and pass the recording to `receive()`. Real sound cards add a sample-rate mismatch of tens of parts per million, which a 200-bit frame tolerates easily (lesson 5).
:::

::: example
## A speaker plays at 70 dB SPL at 1 m in a 45 dB room. How far away can a 20-character message get through 90% of the time?

::: solution
1. **Count the checked bits.**
   $$\begin{aligned} N_b &= 8 \times 20 + 40 \\ &= 200 \end{aligned}$$
2. **Bit error rate for 90% success.**
   $$\begin{aligned} (1 - p)^{200} &= 0.9 \\ p &= 5.27 \times 10^{-4} \end{aligned}$$
3. **Required $E_b/N_0$.** Solve $\frac{1}{2}e^{-x/2} = p$ for $x = E_b/N_0$:
   $$\begin{aligned} x &= -2\ln(2p) \\ &= 13.7 \end{aligned}$$
   or 11.37 dB.
4. **Required SNR.** $E_b/N_0$ is the SNR plus $10\log_{10}(4000/1200) = 5.23$ dB:
   $$\begin{aligned} \text{SNR} &= 11.37 - 5.23 \\ &= 6.1\ \text{dB} \end{aligned}$$
5. **Solve for the distance.**
   $$\begin{aligned} 70 - 20\log_{10}d - 45 &= 6.1 \\ d &= 8.8\ \text{m} \end{aligned}$$

**Answer:** about 8.8 m.
:::
:::

::: example
## How long does that 20-character frame take to send?

::: solution
1. **Frame length.**
   $$8 \times 20 + 80 = 240\ \text{bits}$$
2. **Airtime at 1200 baud.**
   $$\begin{aligned} t &= \frac{240}{1200}\ \text{s} \\ &= 0.2\ \text{s} \end{aligned}$$
3. **Going faster.** A higher bit rate would need tones farther apart or a more efficient modulation such as QPSK or OFDM, along with the carrier recovery and equalization of lessons 8, 11 and 13.

**Answer:** 0.2 s.
:::
:::

::: example
## How much SNR does halving the distance from the speaker gain?

::: solution
1. **How the level falls.** Sound pressure falls as 1/r in the open, so halving the distance raises the level by
   $$20\log_{10}2 = 6.0\ \text{dB}$$
   while the room's noise stays the same.
2. **In a real room.** In a reverberant room the gain is smaller, because reflections keep the level up far from the speaker.

**Answer:** 6.0 dB in the open, and less in a reverberant room.
:::
:::

::: check
kind: python

## Build the whole modem: a framed, CRC-checked FSK transmitter, and a receiver that finds the message in a noisy, echoing room.

```python starter
import numpy as np

# From earlier lessons: framing (2), FSK (3, 4) and the CRC (12).
FS, BAUD, F_MARK, F_SPACE = 9600, 1200, 1200.0, 2200.0
SPS = FS//BAUD
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]

def to_bits(value, n):
    return [(value >> (n - 1 - i)) & 1 for i in range(n)]

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

def fsk_modulate(bits):
    freqs = np.repeat([F_MARK if b else F_SPACE for b in bits], SPS)
    phase = np.concatenate(([0.0], np.cumsum(2*np.pi*freqs/FS)[:-1]))
    return np.cos(phase)

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

def find_sync(bits, max_errors=1):
    for i in range(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 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 frame_bits(text):
    # The payload is the text's bytes followed by their CRC-16 (high byte, then low byte).
    # Return 32 preamble bits (1, 0, ...), SYNC, a length byte counting the payload's bytes
    # (CRC included), the payload's bits, then 8 tail bits of 1 so the last bit isn't cut short.
    return []

def transmit(text):
    # The frame as FSK samples.
    return fsk_modulate(frame_bits(text))

def receive(audio):
    # The frame can start at any sample. For each of the SPS sampling offsets k: demodulate
    # audio[k:], find the sync word, read the length byte and that many payload bytes, and if
    # crc16 of the payload (text and CRC together) is 0, return the text (decoded as ASCII).
    # Return None if no offset gives a frame that passes its check.
    return None
```

```python solution
import numpy as np

# From earlier lessons: framing (2), FSK (3, 4) and the CRC (12).
FS, BAUD, F_MARK, F_SPACE = 9600, 1200, 1200.0, 2200.0
SPS = FS//BAUD
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]

def to_bits(value, n):
    return [(value >> (n - 1 - i)) & 1 for i in range(n)]

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

def fsk_modulate(bits):
    freqs = np.repeat([F_MARK if b else F_SPACE for b in bits], SPS)
    phase = np.concatenate(([0.0], np.cumsum(2*np.pi*freqs/FS)[:-1]))
    return np.cos(phase)

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

def find_sync(bits, max_errors=1):
    for i in range(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 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 frame_bits(text):
    data = text.encode('ascii')
    c = crc16(data)
    payload = data + bytes([c >> 8, c & 0xFF])
    bits = [1, 0]*16 + SYNC + to_bits(len(payload), 8)
    for byte in payload:
        bits += to_bits(byte, 8)
    return bits + [1]*8

def transmit(text):
    return fsk_modulate(frame_bits(text))

def receive(audio):
    for k in range(SPS):
        bits = fsk_demod(audio[k:])
        i = find_sync(bits)
        if i < 0 or i + 8 > len(bits):
            continue
        n = from_bits(bits[i:i + 8])
        body = bits[i + 8:i + 8 + 8*n]
        if n < 2 or len(body) < 8*n:
            continue
        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')
    return None
```

```python tests
def _room(x, rng, snr_db=15):
    # A small room: an unknown start, a quieter signal, two wall echoes and background noise.
    d = int(rng.integers(300, 700))
    y = np.r_[np.zeros(d), 0.3*np.asarray(x), np.zeros(400)]
    e = y.copy()
    e[30:] += 0.3*y[:-30]
    e[70:] += 0.15*y[:-70]
    p = np.mean((0.3*np.asarray(x))**2)/10**(snr_db/10)
    return e + np.sqrt(p)*rng.standard_normal(len(e))

_f = frame_bits("Hi")
assert len(_f) == 32 + 16 + 8 + 32 + 8, f"'Hi' plus its CRC is 4 payload bytes, so the frame is 96 bits; got {len(_f)}."
assert _f[48:56] == [0, 0, 0, 0, 0, 1, 0, 0], "The length byte counts the CRC too: 4."
assert receive(transmit("Hello, modem")) == "Hello, modem", "A clean frame comes back."
_rng = np.random.default_rng(14)
for _msg in ("Hello from the speaker", "Ohmwork D12", "73 and good night"):
    _got = receive(_room(transmit(_msg), _rng))
    assert _got == _msg, f"Through the room the message should survive; sent {_msg!r}, got {_got!r}."
assert receive(0.1*_rng.standard_normal(20000)) is None, "Noise alone isn't a message."
_bad = frame_bits("Secret")
_bad[60] ^= 1
assert receive(fsk_modulate(_bad)) is None, "A frame whose CRC fails must be rejected."
```

::: right
Right. Your modem finds each message at an unknown time and sampling phase through echoes and noise, and rejects frames that fail their CRC.
:::
:::

::: check
given: n = 5 | 20 | 100
answer: (8*n + 80)/1200
unit: s
tolerance: 0.5%

## How long does this modem take to send a {n}-character message, frame included?

::: right
Right. (8 × {n} + 80) bits at 1200 baud: {answer} s.
:::

::: misses
- [8*n/1200] Count the frame: preamble, sync word, length, CRC and tail add 80 bits.
- [any] Not yet. Frame bits over the bit rate.
:::
:::

::: check
given: s = 5 | 10 | 15; B = 4000 | 8000; R = 300 | 1200
answer: s + 10*log(B/R)
unit: dB
tolerance: 0.5%

## A receiver measures {s} dB of SNR in a {B} Hz band and receives {R} bits per second. What's its Eb/N0?

::: right
Right. SNR × B/R is {answer} dB.
:::

::: misses
- [s - 10*log(B/R)] Each bit gathers energy over a time 1/R, while the noise is spread over B: Eb/N0 is higher than the SNR when B > R.
- [any] Not yet. Convert from power over bandwidth to energy per bit.
:::
:::

::: check
given: p = 0.001 | 0.003 | 0.01; n = 10 | 50
answer: (1 - p)^(8*n + 40)
tolerance: 0.5%

## Bits are wrong with probability {p}. What's the chance that a {n}-character frame's 8n + 40 checked bits all arrive right?

::: right
Right. $(1 - p)^{8n + 40}$ = {answer}.
:::

::: misses
- [(1 - p)^(8*n)] Count the 40 bits of sync word, length and CRC too.
- [any] Not yet. Every bit has to be right.
:::
:::

::: check
kind: parts
given: c = 10 | 20 | 50; h = 40 | 80; s = 0.8 | 0.9 | 0.99

## A message of {c} characters carries 8 bits each plus {h} bits of checked framing, and must arrive whole with probability {s}.

::: part
answer: 1 - s^(1/(8*c + h))
tolerance: 1%

### What bit error rate can be tolerated?

::: misses
- [any] Solve $(1 - p)^n = s$.
:::
:::

::: part
answer: (8*c + h)/1200
unit: s
tolerance: 0.5%

### How long does it take at 1200 baud?

::: misses
- [any] Bits ÷ baud.
:::
:::
:::

::: check
kind: parts
given: L = 60 | 70 | 80; N = 35 | 45 | 55; r = 1 | 2 | 4

## A speaker plays at {L} dB SPL at 1 m in a room whose noise is {N} dB SPL.

::: part
answer: L - 20*log(r) - N
unit: dB
tolerance: 0.5%

### What SNR is there at {r} m, in the open?

::: misses
- [any] Level falls as 1/r: $-20\log_{10}r$.
:::
:::

::: part
answer: L - 20*log(r/2) - N
unit: dB
tolerance: 0.5%

### And at half that distance?

::: misses
- [any] 6 dB better.
:::
:::
:::

::: explain
## Why does the receiver check the CRC before trusting a frame, even when it found the sync word?

::: model
Finding the sync word only means some stretch of bits looked like it, which can happen by chance in noise or at a wrong sampling offset, and even a genuine frame can have bits flipped by noise or echoes in its payload. Without a check, the receiver would print garbage or a subtly wrong message as if it were real. The CRC is computed by the transmitter over the exact payload, so if any bit changed, the receiver's remainder comes out nonzero and the frame is rejected; only about one corrupted frame in 65,536 slips through. That lets the receiver try every sampling offset and accept the first frame that passes, knowing it's almost certainly the message that was sent.
:::
:::

::: practice

::: check
given: n = 1 | 50 | 500
answer: (8*n + 80)/1200
unit: s
tolerance: 0.5%

## Airtime for {n} characters?

::: misses
- [any] $(8n + 80)/1200$.
:::
:::

::: check
given: r = 2 | 3 | 10 | 30
answer: 20*log(r)
unit: dB
tolerance: 0.5%

## Level lost moving {r} times farther from the speaker?

::: misses
- [10*log(r)] Sound pressure falls as $1/d$: use 20 log.
- [any] $20\log_{10}r$.
:::
:::
:::
