---
title: Finding the bit clock
heading: Why the receiver must decide when to sample, the eye diagram and its widest opening, clock drift between two crystals, choosing a sampling phase from the data, tracking it with transitions, and keeping transitions coming with bit stuffing and scrambling
eyebrow: D12 · Lesson 5 · Finding the bit clock
xp: 40
---

::: hook
The transmitter sends a bit every 1/1200 s by its own crystal. The receiver has a different crystal, switched on at a different moment, so it knows neither where each bit starts nor exactly how long a bit lasts. Sample at a bit's edge and the decision is a coin toss; sample near its middle and it's clean. **Clock recovery** finds the best sampling instant from the received signal itself and keeps adjusting it as the two clocks drift apart, which they always do.
:::

::: play
- Eight bits of the byte B sent as half-sine pulses, positive for 1 and negative for 0, with time in bits.
- The dashed line is what the receiver gets by sampling each bit at phase p (a fraction of the bit) and holding the value: full height when p is near the middle, shrinking toward zero at the edges.
- Slide p to each of the eight sample positions an 8-sample-per-bit receiver could choose. The middle two are equally good.
:::

```sim plot
view: graph
x: t = 0..8
y: v = -1.2..1.2
slider: B = 0..255 step 1 = 178
slider: p = 0.0625..0.9375 step 0.125 = 0.4375
plot: (2*(floor(B/2^(7 - floor(t))) - 2*floor(B/2^(8 - floor(t)))) - 1)*abs(sin(pi*t)) | samples: 800 | label: received pulses (t in bits)
plot: (2*(floor(B/2^(7 - floor(t))) - 2*floor(B/2^(8 - floor(t)))) - 1)*sin(pi*p) | dashed | color: ch3 | label: value sampled at phase p
marker: x = p | label: sampling instant
readout: sample, fraction of peak = sin(pi*p) | digits: 3
readout: sample index k = 8*p - 0.5 | digits: 1
```

::: predict
## The receiver's crystal runs 100 parts per million fast compared with the transmitter's. After how many bits has its sampling instant slid half a bit away from where it started?

- [ ] 50
- [ ] 500
- [x] 5000
- [ ] 100,000

::: reveal
Each bit, the sampling instant moves by 100 × 10⁻⁶ of a bit, so half a bit takes 0.5/10⁻⁴ = 5000 bits, about 4 s at 1200 baud. A long packet would end up sampling at the bit edges, so the receiver has to keep correcting its timing during the packet, using the transitions in the data.
:::
:::

::: nameit
## The eye

Overlaying every bit's waveform on one bit interval draws the **eye diagram**: the traces for 1s and 0s separate most widely at the best sampling instant and close together near the edges. Noise and interference (lesson 6) shrink the opening. A half-sine pulse sampled a fraction p into the bit gives $\sin(\pi p)$ of its peak, so with S samples per bit, a sample taken d samples from the center keeps $\cos(\pi d/S)$ of it.

## Choosing the phase

With S samples per bit, a simple receiver tries each of the S phases over a block of bits and keeps the one with the largest average $|y|$, the widest eye. Its timing error is then at most half a sample, $1/(2S)$ of a bit.

## Tracking

Clocks differ by tens of parts per million, so the phase must follow drift. **Early–late** detectors compare samples a little before and after the chosen instant; the **Gardner** detector uses the sample midway between two decisions, which should be zero at a transition when the timing is right. Either one drives a loop that nudges the sampling instant, much like the PLL in lesson 8.

## Keeping transitions coming

A tracker learns nothing from a long run of identical bits. Links keep transitions coming by:

- **Bit stuffing:** HDLC inserts a 0 after five 1s in a row; USB inserts one after six.
- **Scrambling:** an LFSR (C7) whitens the data so long runs become rare.
- **Line codes:** Manchester (lesson 6) has a transition in every bit.
:::

::: example
## A receiver with 8 samples per bit picks the best of its 8 phases. How far off center can it be, and how much signal does that cost with half-sine pulses?

::: solution
1. **Worst timing error.** The best of 8 phases is at most half a sample off:
   $$\frac{1}{2} \times \frac{1}{8} = \frac{1}{16}\ \text{bit}$$
2. **Sample value.** The half-sine pulse there is
   $$\cos\frac{\pi}{16} = 0.981$$
   of the peak.
3. **Loss in decibels.**
   $$20\log_{10}0.981 = -0.17\ \text{dB}$$
4. **What matters more.** Finer timing gains little; drift matters much more.

**Answer:** at most 1/16 of a bit off center, which costs 0.17 dB.
:::
:::

::: example
## What does HDLC's bit stuffing (a 0 after every five 1s in a row) add in the worst case, and on random data?

::: solution
1. **Worst case, all ones.** One extra bit per five:
   $$\frac{1}{5} = 20\%$$
2. **Random data as states.** The count of consecutive 1s runs through states 0 to 4.
3. **Chance of sitting at 4.** In the steady state it is
   $$\begin{aligned} P_4 &= \frac{16/31}{16} \\ &= \frac{1}{31} \end{aligned}$$
4. **Stuffing rate.** A 1 arriving there (probability 1/2) forces a stuffed bit:
   $$\begin{aligned} r &= \frac{1}{2} \times \frac{1}{31} \\ &= \frac{1}{62} \\ &\approx 1.6\% \end{aligned}$$

**Answer:** 20% overhead in the worst case and about 1.6% on random data.
:::
:::

::: example
## The two ends' clocks differ by 100 ppm. How far does the sampling point drift over a 100-bit frame, and over 10,000 bits?

::: solution
1. **Drift over a 100-bit frame.** 100 ppm is $10^{-4}$:
   $$100 \times 10^{-4} = 0.01\ \text{bit}$$
   negligible over a short frame.
2. **Drift over 10,000 bits.**
   $$10\,000 \times 10^{-4} = 1\ \text{bit}$$
3. **What that means.** Long transmissions need clock recovery that keeps tracking; a single phase choice at the start isn't enough.

**Answer:** 0.01 bit over 100 bits, and a whole bit over 10,000.
:::
:::

::: check
kind: python

## Find the best sampling phase and recover the bits.

```python starter
import numpy as np

SPS = 8

def eye_opening(y, k):
    # Average of |y| at the sampling phase k: samples k, k + SPS, k + 2*SPS, ...
    return 0.0

def best_phase(y):
    # The sampling phase k (0 to SPS - 1) where the eye is most open.
    return 0

def recover_bits(y):
    # Sample at the best phase and decide each symbol: 1 if positive, else 0.
    return []
```

```python solution
import numpy as np

SPS = 8

def eye_opening(y, k):
    return float(np.mean(np.abs(y[k::SPS])))

def best_phase(y):
    return int(np.argmax([eye_opening(y, k) for k in range(SPS)]))

def recover_bits(y):
    k = best_phase(y)
    return [1 if v > 0 else 0 for v in y[k::SPS]]
```

```python tests
_rng = np.random.default_rng(11)
_bits = _rng.integers(0, 2, 400)
_pulse = np.sin(np.pi*(np.arange(SPS) + 0.5)/SPS)
_tx = np.convolve(np.kron(2*_bits - 1, np.r_[1, np.zeros(SPS - 1)]), _pulse)[:len(_bits)*SPS]
for _d in (0, 3, 6):
    _y = np.r_[np.zeros(_d), _tx][:len(_tx)] + 0.2*_rng.standard_normal(len(_tx))
    _k = best_phase(_y)
    assert _k in ((_d + 3) % SPS, (_d + 4) % SPS), f"With a delay of {_d} samples the eye is widest at phase {(_d + 3) % SPS} or {(_d + 4) % SPS} (the pulse's middle); got {_k}."
    _r = recover_bits(_y)
    _off = 1 if (_d + 3) >= SPS else 0
    _m = min(len(_r) - _off, len(_bits))
    assert np.mean(np.array(_r[_off:_off + _m]) != _bits[:_m]) < 0.01, "At the best phase nearly every bit should be right."
assert abs(eye_opening(np.array([1.0, 0, 0, 0, 0, 0, 0, 0, -1.0, 0, 0, 0, 0, 0, 0, 0]), 0) - 1) < 1e-12, "eye_opening averages |y| at one phase."
```

::: right
Right. Your receiver finds the widest point of the eye at every delay and recovers the bits there.
:::
:::

::: check
given: e = 20 | 50 | 100 | 500 | 2000
answer: 0.5/(e*1e-6)
tolerance: 0.5%

## Two clocks differ by {e} parts per million. After how many bits has a receiver's sampling instant slid half a bit?

::: right
Right. 0.5/({e} × 10⁻⁶) = {answer} bits.
:::

::: misses
- [1/(e*1e-6)] That's a whole bit; half a bit comes twice as soon.
- [any] Not yet. Half a bit over the drift per bit.
:::
:::

::: check
given: d = 1 | 2 | 3 | 5
answer: cos(pi*d/16)
tolerance: 0.5%

## A receiver takes 16 samples per bit and samples a half-sine pulse {d} samples away from its center. What fraction of the peak does it get?

::: right
Right. $\cos(\pi d/16)$ = {answer}.
:::

::: misses
- [sin(pi*d/16)] The center is the peak: use the cosine of the offset.
- [1 - d/16] The pulse is a half sine, so the loss follows a cosine.
- [any] Not yet. The half sine $d$ samples from its middle.
:::
:::

::: check
given: S = 4 | 8 | 16; R = 300 | 1200 | 9600
answer: 1e6/(2*S*R)
unit: µs
tolerance: 0.5%

## A receiver takes {S} samples per bit at {R} baud and picks the best phase. What's its worst timing error?

::: right
Right. Half a sample, $1/(2SR)$ = {answer} µs.
:::

::: misses
- [1e6/(S*R)] The nearest sample is at most half a sample away.
- [any] Not yet. Half a sample period.
:::
:::

::: check
given: n = 4 | 5 | 6 | 7
answer: 100/n
tolerance: 0.5%

## A link stuffs a 0 after every {n} 1s in a row. What's the overhead, in percent, when the data is all 1s?

::: right
Right. One stuffed bit per {n} data bits: {answer}%.
:::

::: misses
- [100/(n + 1)] That's the stuffed bits' share of the line; the overhead counts them against the data.
- [any] Not yet. One extra bit per run.
:::
:::

::: check
kind: parts
given: p = 20 | 100 | 500; n = 100 | 1000 | 100000

## Two clocks differ by {p} ppm, and a transmission lasts {n} bits.

::: part
answer: p*1e-6*n
unit: bits
tolerance: 0.5%

### How far does the sampling point drift?

::: misses
- [any] Offset × bits.
:::
:::

::: part
answer: 0.25/(p*1e-6)
unit: bits
tolerance: 0.5%

### After how many bits has it drifted a quarter bit?

::: misses
- [any] 0.25 ÷ offset.
:::
:::
:::

::: check
kind: parts
given: N = 4 | 8 | 16

## A receiver with {N} samples per bit picks the best phase for half-sine pulses.

::: part
answer: 1/(2*N)
unit: bits
tolerance: 0.5%

### How far off center can its sample be?

::: misses
- [any] Half a sample.
:::
:::

::: part
answer: 20*log(cos(pi/(2*N)))
unit: dB
tolerance: 1%

### What signal loss does that cost?

::: misses
- [any] $\cos(\pi\delta)$ for an offset of δ bits.
:::
:::
:::

::: explain
## Why does a receiver need transitions in the data to keep its bit clock?

::: model
The receiver can only tell where bit boundaries are from the moments when the signal changes from one symbol to another. During a long run of identical bits the signal looks the same from one bit to the next, so nothing shows whether the receiver's sampling point is drifting toward an edge. Because its crystal never runs at exactly the transmitter's rate, the sampling point does drift, and after enough identical bits it can slide into the next bit and miscount the run. Bit stuffing, scrambling and line codes all exist to guarantee transitions often enough that the timing loop can keep correcting itself.
:::
:::

::: practice

::: check
given: e = 1 | 10 | 30 | 200 | 1000 | 5000
answer: 0.5/(e*1e-6)
tolerance: 0.5%

## Bits until half-bit drift at {e} ppm?

::: misses
- [any] $0.5/e$.
:::
:::

::: check
given: S = 2 | 32; R = 50 | 115200
answer: 1e6/(2*S*R)
unit: µs
tolerance: 0.5%

## Worst timing error, {S} samples per bit at {R} baud?

::: misses
- [any] $1/(2SR)$.
:::
:::
:::
