---
title: "Bits into frames: start bits, preambles and sync words"
heading: Why a receiver needs structure around the data, the UART's start and stop bits around every byte, packet frames with a preamble for the receiver to lock onto, a sync word chosen to stand out from noise, a length field, and finding the frame in a stream of bits
eyebrow: D12 · Lesson 2 · Frames
xp: 40
---

::: hook
A receiver switched on in the middle of a transmission hears a stream of bits with no idea where anything begins. Which bit is the first of a byte? Is this noise or a message? Every link answers with **framing**. A UART (C12, D10) wraps each byte in a start bit and a stop bit. Packet radios do it once per message: a **preamble** of alternating bits that lets the receiver settle its gain and clock, a **sync word** whose pattern is unlikely in noise and marks exactly where the data begins, and a **length** so the receiver knows when to stop.
:::

::: play
- The bits of one frame carrying a single byte B: 32 preamble bits (1, 0, 1, 0, ...), the 16-bit sync word 0xD391, a length byte (here 1) and the payload byte.
- The preamble's regular pattern is easy to lock onto but carries no information; the sync word is chosen to look nothing like the preamble or shifted copies of itself.
- Change B: only the last 8 bits change.
:::

```sim plot
view: graph
x: n = 0..63
y: b = -0.2..1.2
slider: B = 0..255 step 1 = 72
plot: (1 - (n - 2*floor(n/2)))*step(31.5 - n) | stems | color: ch3 | label: preamble
plot: (floor(54161/2^(47 - n)) - 2*floor(54161/2^(48 - n)))*step(n - 31.5)*step(47.5 - n) | stems | color: ch4 | label: sync word 0xD391
plot: step(n - 54.5)*step(55.5 - n) | stems | color: ch2 | label: length = 1
plot: (floor(B/2^(63 - n)) - 2*floor(B/2^(64 - n)))*step(n - 55.5) | stems | color: ch1 | label: payload byte
readout: payload = B | format: bin8
```

::: predict
## A frame has 32 preamble bits, a 16-bit sync word, a length byte and a 2-byte payload. What fraction of its bits carry the payload?

- [ ] 100%
- [ ] 50%
- [x] About 22%
- [ ] About 8%

::: reveal
32 + 16 + 8 + 16 = 72 bits, of which 16 are payload: 22%. Short messages pay heavily for framing, which is why protocols send longer packets when they can: with a 200-byte payload the same overhead is under 4%.
:::
:::

::: nameit
## Byte framing: the UART

Each byte travels as a **start bit** (0), eight data bits least significant first, and a **stop bit** (1). The falling edge of the start bit resynchronizes the receiver's clock for every byte (D10).

## Packet framing

- **Preamble**: alternating 1s and 0s for the receiver's gain control and clock recovery (lesson 5) to settle.
- **Sync word**: a fixed pattern, here 0xD391, chosen so that it differs from the preamble and from its own shifted copies in many bit positions. The receiver slides it along the incoming bits and declares a match when at most a bit or two disagree, which tolerates noise without matching random data too often.
- **Length** and **payload**, then a check such as a CRC (lesson 12).

## False matches

A random 16-bit window matches a given sync word exactly with probability $2^{-16}$, and within one bit error with probability $17/2^{16}$, about once per 3900 bit positions. Longer sync words, or requiring the CRC to pass as well, cut false frames further.
:::

::: example
## What's the UART frame for the byte 0x4B, and how long is a frame for a 2-byte payload here?

::: solution
1. **The byte in binary.**
   $$\text{0x4B} = 01001011$$
2. **The UART frame.** The start bit 0 comes first, then the data bits least significant first, then the stop bit 1:
   $$0,\ 1, 1, 0, 1, 0, 0, 1, 0,\ 1$$
3. **The packet frame.** Preamble, sync word, length byte and 2 payload bytes:
   $$32 + 16 + 8 + 16 = 72\ \text{bits}$$
4. **Its airtime at 1200 baud.**
   $$\begin{aligned} t &= \frac{72}{1200}\ \text{s} \\ &= 60\ \text{ms} \end{aligned}$$

**Answer:** the UART sends 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, and the 2-byte packet frame is 72 bits, 60 ms at 1200 baud.
:::
:::

::: example
## A 16-bit sync word is searched for in random bits arriving at 1200 bit/s. How often does random data match it by chance?

::: solution
1. **Chance at each position.** Each position matches with probability $2^{-16}$.
2. **False matches per second.**
   $$\begin{aligned} r &= 1200 \times 2^{-16} \\ &= 0.018\ \text{per second} \end{aligned}$$
3. **Time between them.**
   $$\begin{aligned} \frac{1}{r} &= \frac{2^{16}}{1200}\ \text{s} \\ &\approx 55\ \text{s} \end{aligned}$$
4. **Why the frame carries a CRC.** That's why the frame also carries a length and a CRC: a false sync is caught when the CRC fails.

**Answer:** about 0.018 false matches a second, one every 55 s or so.
:::
:::

::: example
## What fraction of the frame is payload for 2 bytes and for 64 bytes, with 32 bits of preamble, 16 of sync and 16 of CRC?

::: solution
1. **Overhead bits.** Preamble, sync word and CRC:
   $$32 + 16 + 16 = 64\ \text{bits}$$
2. **Two bytes.** 16 payload bits in a frame of 80:
   $$\begin{aligned} \frac{16}{16 + 64} &= \frac{16}{80} \\ &= 20\% \end{aligned}$$
3. **Sixty-four bytes.** 512 payload bits in a frame of 576:
   $$\begin{aligned} \frac{512}{512 + 64} &= \frac{512}{576} \\ &= 89\% \end{aligned}$$
4. **What it means.** Short messages pay mostly for overhead, which is why links bundle small messages into larger frames when they can.

**Answer:** the payload is 20% of the frame for 2 bytes and 89% for 64 bytes.
:::
:::

::: check
kind: python

## Build a frame, find its sync word in noise, and read back the payload.

```python starter
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]   # 0xD391

def to_bits(value, n):
    # value as n bits, most significant first.
    return [(value >> (n - 1 - i)) & 1 for i in range(n)]

def make_frame(payload_bits):
    # 32 preamble bits (1, 0, 1, 0, ...), the 16-bit sync word, a length byte giving the payload's
    # length in bytes, then the payload itself.
    return []

def find_sync(bits, max_errors=1):
    # The index just after the first place the sync word appears with at most max_errors bits
    # wrong, or -1 if it never does.
    return -1

def parse_frame(bits):
    # Find the sync word, read the length byte after it, and return that many payload bytes
    # as bits. Return None if there's no sync word.
    return None

def uart_bits(byte):
    # A UART frame for one byte: a 0 start bit, the 8 data bits least significant first,
    # and a 1 stop bit.
    return []
```

```python solution
SYNC = [1,1,0,1, 0,0,1,1, 1,0,0,1, 0,0,0,1]   # 0xD391

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

def make_frame(payload_bits):
    nbytes = len(payload_bits)//8
    return [1, 0]*16 + SYNC + to_bits(nbytes, 8) + list(payload_bits)

def find_sync(bits, max_errors=1):
    n = len(SYNC)
    for i in range(len(bits) - n + 1):
        errors = sum(a != b for a, b in zip(bits[i:i + n], SYNC))
        if errors <= max_errors:
            return i + n
    return -1

def parse_frame(bits):
    k = find_sync(bits)
    if k < 0:
        return None
    length = 0
    for b in bits[k:k + 8]:
        length = 2*length + b
    return list(bits[k + 8:k + 8 + 8*length])

def uart_bits(byte):
    return [0] + [(byte >> i) & 1 for i in range(8)] + [1]
```

```python tests
import random
_hi = [0,1,0,0,1,0,0,0, 0,1,1,0,1,0,0,1]
_f = make_frame(_hi)
assert len(_f) == 32 + 16 + 8 + 16 and _f[:4] == [1, 0, 1, 0], f"A frame for 'Hi' is 32 preamble + 16 sync + 8 length + 16 payload = 72 bits; got {len(_f)}."
assert _f[48:56] == [0,0,0,0,0,0,1,0], "The length byte for a 2-byte payload is 00000010."
assert find_sync(_f) == 48, f"The sync word ends at bit 48 of the frame; got {find_sync(_f)}."
_rng = random.Random(5)
_noise = [_rng.randint(0, 1) for _ in range(37)]
_g = _noise + _f + [_rng.randint(0, 1) for _ in range(20)]
assert parse_frame(_g) == _hi, "The payload should come back from a frame buried in random bits."
_h = list(_g); _h[37 + 40] ^= 1
assert parse_frame(_h) == _hi, "One flipped bit inside the sync word is still accepted."
assert find_sync([1, 0]*40) == -1, "A preamble alone never matches the sync word."
assert uart_bits(0x4B) == [0, 1, 1, 0, 1, 0, 0, 1, 0, 1], f"0x4B as a UART frame is start, 11010010 (LSB first), stop; got {uart_bits(0x4B)}."
```

::: right
Right. Your receiver finds the frame among random bits, even with a flipped sync bit, and recovers the payload.
:::
:::

::: check
given: p = 1 | 2 | 8 | 16
answer: 100*8*p/(32 + 16 + 8 + 8*p)
tolerance: 0.5%

## A frame has 32 preamble bits, a 16-bit sync word, a length byte and a {p}-byte payload. What percentage of its bits are payload?

::: right
Right. {answer}%.
:::

::: misses
- [100*8*p/(32 + 16 + 8*p)] Count the length byte too.
- [any] Not yet. Payload bits over all bits.
:::
:::

::: check
given: n = 8 | 16 | 32
answer: (n + 1)/2^n
tolerance: 0.5%

## A receiver accepts an {n}-bit sync word with at most one bit wrong. What's the chance that a random {n}-bit window is accepted?

::: right
Right. $(n + 1)/2^n$ = {answer}.
:::

::: misses
- [1/2^n] That's an exact match; one error adds n more patterns.
- [any] Not yet. Count the patterns within one bit of the sync word.
:::
:::

::: check
kind: parts
given: k = 8 | 16 | 32; b = 1200 | 9600

## A {k}-bit sync word is searched for in random bits at {b} bit/s.

::: part
answer: b*2^(-k)
tolerance: 0.5%

### How many times a second does random data match it?

::: misses
- [any] Rate × $2^{-k}$.
:::
:::

::: part
answer: 1/(b*2^(-k))
unit: s
tolerance: 0.5%

### On average, how long between false matches?

::: misses
- [any] The reciprocal.
:::
:::
:::

::: check
kind: parts
given: p = 2 | 16 | 64 | 255; o = 64 | 96

## A frame carries {p} payload bytes and {o} bits of preamble, sync, length and CRC.

::: part
answer: 8*p/(8*p + o)*100
unit: %
tolerance: 0.5%

### What fraction of the frame is payload?

::: misses
- [any] Payload bits ÷ total.
:::
:::

::: part
answer: (8*p + o)/1200*1000
unit: ms
tolerance: 0.5%

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

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

::: check
kind: parts
given: P = 16 | 32 | 64; k = 16 | 24 | 32; N = 8 | 32 | 128; n = 1 | 10

## A frame has a {P}-bit preamble, a {k}-bit sync word, an 8-bit length, {N} payload bytes and a 16-bit CRC.

::: part
answer: N*8/(P + k + 8 + N*8 + 16)*100
tolerance: 0.5%

### What percentage of the bits are payload?

::: misses
- [N*8/(N*8 + 16)*100] Count the preamble, sync word and length too.
- [any] Not yet. Payload bits over all bits.
:::
:::

::: part
answer: n*1e6/2^k
tolerance: 0.5%

### Scanning {n} million bits of random noise, about how many false matches of the sync word should the receiver expect?

::: misses
- [n*1e6/k] A specific {k}-bit pattern matches random bits with probability $2^{-k}$.
- [any] Not yet. One chance in $2^k$ at each bit position.
:::
:::

::: right
Right. Longer sync words cost overhead but make false starts rare; the CRC catches the rest.
:::
:::

::: explain
## Why does a packet start with a preamble before the sync word?

::: model
When a transmission begins, the receiver doesn't yet know how strong the signal is or exactly where the bit boundaries fall, so its automatic gain control and clock recovery need some time and some transitions to settle. A preamble of alternating ones and zeros gives them a steady, predictable signal with a transition in every bit, the easiest thing to lock onto. Bits received during that settling time might be wrong, which doesn't matter because the preamble carries no information. Only after the receiver has settled does the sync word arrive, and finding it then marks precisely where the data starts.
:::
:::

::: practice

::: check
given: p = 1 | 8 | 46 | 64 | 256 | 1000 | 1500
answer: 100*8*p/(56 + 8*p)
tolerance: 0.5%

## Payload share with 56 overhead bits and {p} payload bytes?

::: misses
- [any] $8p/(56 + 8p)$.
:::
:::

::: check
given: n = 4 | 8 | 12 | 16 | 24 | 32
answer: (n + 1)/2^n
tolerance: 0.5%

## False-match chance, {n}-bit sync, one error allowed?

::: misses
- [any] $(n + 1)/2^n$.
:::
:::
:::
