---
title: Carrier recovery with a phase-locked loop
heading: Why a receiver's carrier never quite matches the transmitter's, the constellation spinning under a frequency offset, the phase-locked loop with its phase detector, loop filter and oscillator, the Costas detector that ignores the data, loop bandwidth and damping, and the 180° ambiguity
eyebrow: D12 · Lesson 8 · Carrier recovery
xp: 40
---

::: hook
Coherent demodulation needs the receiver's carrier to match the transmitter's in frequency and phase. It never does: two crystals differ by tens of parts per million, which at 2.4 GHz is tens of kilohertz, and the path delay sets an arbitrary phase. Any frequency offset makes the constellation spin. A **phase-locked loop** measures the leftover rotation of each received symbol and steers its own oscillator to cancel it, the same feedback idea as a thermostat applied to phase.
:::

::: play
- The phase error of a second-order PLL after the incoming carrier jumps in frequency by Δf, for a loop of natural frequency $f_n$ and damping ζ.
- The error rises, overshoots and settles back to zero: a loop with an integrator in its filter tracks a frequency offset with no lasting phase error.
- A slow loop (small $f_n$) lets a big error build first. Past the dashed line at 90°, a BPSK Costas loop can slip to the wrong lock point and invert every bit.
:::

```sim plot
view: graph
x: t = 0..200
y: e = -20..120
slider: df = 1..20 step 1 = 5
slider: fn = 2..50 step 1 = 10
slider: z = 0.3..2 step 0.05 = 0.7
plot: (df/fn)*(180/pi)*Re(exp(-z*2*pi*fn*t/1000)*sinh(sqrt(z^2 - 1 + 1e-9)*2*pi*fn*t/1000)/sqrt(z^2 - 1 + 1e-9)) | samples: 600 | label: phase error, degrees (t in ms)
plot: 90 + 0*t | dashed | color: ch3 | label: 90°
readout: rotation without the loop, degrees per ms = 0.36*df | digits: 3
```

::: predict
## A 1200 baud BPSK receiver's carrier is 12 Hz off. How far does the constellation rotate from one symbol to the next?

- [ ] 0.01°
- [ ] 1°
- [x] 3.6°
- [ ] 12°

::: reveal
360° × 12 Hz/1200 symbols per second = 3.6° per symbol. After 25 symbols it has turned 90° and BPSK decisions are coin tosses; after 50 every bit is inverted. Even a tiny offset defeats a fixed phase reference, so the receiver must track continuously.
:::
:::

::: nameit
## The loop

1. A **phase detector** measures the phase error of each received sample against the local oscillator's.
2. A **loop filter**, here proportional plus integral, smooths that error and accumulates it.
3. A **numerically controlled oscillator** (NCO) advances its phase by the filter's output each sample.

In software, for each corrected sample $y = z\,e^{-j\theta}$:

$$e = \operatorname{Im}(y)\operatorname{sign}(\operatorname{Re}(y)), \qquad f \leftarrow f + k_ie, \qquad \theta \leftarrow \theta + f + k_pe$$

The integral path f learns the frequency offset, so in the steady state the phase error is zero.

## Dynamics

With the integrator, the loop is second order, with natural frequency $\omega_n$ and damping ζ. A frequency step Δω gives a phase error

$$\theta_e(t) = \frac{\Delta\omega}{\omega_n}\,\frac{e^{-\zeta\omega_nt}\sin\left(\sqrt{1 - \zeta^2}\,\omega_nt\right)}{\sqrt{1 - \zeta^2}}$$

whose peak at ζ = 0.707 is $e^{-\pi/4}\,\Delta f/f_n$ = 0.456 Δf/f_n radians. A wide loop follows offsets and jitter quickly but lets more noise through; a narrow one is quiet but slow. A loop without the integrator (first order, gain K) is left with a steady error of Δω/K.

## Costas loops and ambiguity

The data flips BPSK's phase by 180°, which would confuse a plain phase detector. The **Costas** detector multiplies by the sign of the decision, so both phases give the same error. The price is that the loop can lock at 0° or 180° equally, inverting every bit. Links resolve it with a known preamble or with **differential encoding**, where the bit is the change in phase. QPSK uses the same idea with a four-way ambiguity.
:::

::: example
## A transmitter and receiver each have 20 ppm crystals. What's the worst carrier offset at 1800 Hz and at 2.4 GHz?

::: solution
1. **Total error.** The two crystals together can be off by up to 40 ppm.
2. **At 1800 Hz.**
   $$\begin{aligned} \Delta f &= 1800 \times 40 \times 10^{-6} \\ &= 0.072\ \text{Hz} \end{aligned}$$
   harmless in this audio modem.
3. **At 2.4 GHz.**
   $$\begin{aligned} \Delta f &= 2.4 \times 10^9 \times 40 \times 10^{-6} \\ &= 96\ \text{kHz} \end{aligned}$$
   many times a narrow loop's bandwidth.
4. **How radios cope.** Radios estimate and remove most of such an offset from the preamble first, then let the PLL track what's left.

**Answer:** up to 0.072 Hz at 1800 Hz, and up to 96 kHz at 2.4 GHz.
:::
:::

::: example
## A loop with $f_n$ = 10 Hz and ζ = 0.707 meets a 5 Hz frequency step. What's its peak phase error?

::: solution
1. **Peak phase error.** For ζ = 0.707 it is 0.456 times the step over the natural frequency:
   $$\begin{aligned} \theta_{\text{pk}} &= 0.456 \times \frac{5}{10} \\ &= 0.228\ \text{rad} \\ &= 13.1^\circ \end{aligned}$$
2. **Compare with the slip point.** That's well short of the 90° where a BPSK Costas loop could slip.
3. **A slower loop.** The same step on a 2 Hz loop would peak at 65°.

**Answer:** 0.228 rad, or 13.1°.
:::
:::

::: example
## About how long does the 10 Hz, ζ = 0.707 Costas loop take to lock?

::: solution
1. **Decay rate of the transients.**
   $$\begin{aligned} \zeta\omega_n &= 0.707 \times 2\pi \times 10 \\ &= 44\ \text{s}^{-1} \end{aligned}$$
2. **Settling time.**
   $$\begin{aligned} t_s &\approx \frac{4}{\zeta\omega_n} \\ &\approx 90\ \text{ms} \end{aligned}$$
3. **In bits.** At 1200 baud that's roughly 110 bits.
4. **What it means for the preamble.** The preamble must be at least that long, or the first bits arrive before the loop is ready.

**Answer:** about 90 ms, roughly 110 bits at 1200 baud.
:::
:::

::: check
kind: python

## Write a Costas loop that locks onto a spinning BPSK constellation.

```python starter
import numpy as np

def costas_track(z, kp, ki):
    # z holds one complex BPSK sample per symbol, rotated by an unknown, drifting carrier phase.
    # Keep a phase estimate theta and a frequency estimate f (radians per symbol), both starting at 0.
    # For each sample: y = z*exp(-1j*theta), the corrected symbol; e = y.imag*sign(y.real), the
    # Costas phase detector; then f += ki*e and theta += f + kp*e. Return all the y's as an array.
    return np.array(z, dtype=complex)
```

```python solution
import numpy as np

def costas_track(z, kp, ki):
    theta, f = 0.0, 0.0
    out = np.empty(len(z), dtype=complex)
    for i, v in enumerate(z):
        y = v*np.exp(-1j*theta)
        out[i] = y
        e = y.imag*np.sign(y.real)
        f += ki*e
        theta += f + kp*e
    return out
```

```python tests
_rng = np.random.default_rng(8)
_d = _rng.choice([-1.0, 1.0], 3000)
_n = np.arange(3000)
_z = _d*np.exp(1j*(1.0 + 0.01*_n)) + 0.1*(_rng.standard_normal(3000) + 1j*_rng.standard_normal(3000))
_y = costas_track(_z, 0.1, 0.004)
assert np.allclose(costas_track(np.array([1.0 + 0j, -1.0 + 0j]), 0.1, 0.004), [1, -1]), "With no rotation, the first corrected symbols are the inputs."
_tail = _y[1000:]
_agree = np.mean(np.sign(_tail.real) == _d[1000:])
assert _agree > 0.999 or _agree < 0.001, f"After locking, every decision should match the data (or all be inverted, the 180° ambiguity); {100*_agree:.1f}% match."
assert np.sqrt(np.mean(np.angle(_tail**2)**2))/2 < 0.15, "Once locked, the residual phase error should be small, about the noise alone."
_raw = np.mean(np.sign(_z[1000:].real) == _d[1000:])
assert 0.3 < _raw < 0.7, "Without tracking, the spinning carrier makes the raw decisions useless."
```

::: right
Right. Your loop learns the frequency offset, stops the spin and keeps every decision right (up to the 180° ambiguity).
:::
:::

::: check
given: f = 1 | 5 | 20; R = 300 | 1200 | 2400
answer: 360*f/R
unit: °
tolerance: 0.5%

## A receiver's carrier is {f} Hz off and symbols arrive at {R} per second. How far does the constellation rotate per symbol?

::: right
Right. 360° × Δf/R = {answer}°.
:::

::: misses
- [2*pi*f/R] That's in radians.
- [any] Not yet. The offset's turns per symbol, in degrees.
:::
:::

::: check
given: d = 2 | 5 | 10; n = 10 | 20 | 50
answer: exp(-pi/4)*d/n*180/pi
unit: °
tolerance: 0.5%

## A PLL with natural frequency {n} Hz and damping 0.707 meets a {d} Hz frequency step. What's the peak phase error?

::: right
Right. $e^{-\pi/4}\Delta f/f_n$ = {answer}°.
:::

::: misses
- [d/n*180/pi] That's the size of $\Delta\omega/\omega_n$; damping brings the peak down to $e^{-\pi/4}$ of it.
- [any] Not yet. The peak of the frequency-step response.
:::
:::

::: check
given: f = 10 | 50 | 100; K = 1000 | 5000 | 20000
answer: 360*f/K
unit: °
tolerance: 0.5%

## A first-order PLL with loop gain {K} s⁻¹ tracks a {f} Hz frequency offset. What steady phase error does it settle at?

::: right
Right. Δω/K = 2π{f}/{K} rad = {answer}°.
:::

::: misses
- [2*pi*f/K] Give it in degrees.
- [any] Not yet. The loop needs a steady error to keep its oscillator offset.
:::
:::

::: check
kind: parts
given: p = 10 | 20 | 50; f = 1.8 | 2400 | 433000

## Each end's crystal is within {p} ppm, at a carrier of {f} kHz.

::: part
answer: 2*p*1e-6*f*1000
unit: Hz
tolerance: 0.5%

### What is the worst carrier offset?

::: misses
- [p*1e-6*f*1000] Both ends can be off, in opposite directions.
- [any] $2 \times$ ppm × carrier.
:::
:::

::: part
answer: 2*p*1e-6*f*1000/1200
tolerance: 0.5%

### How many 1200 Hz bit rates is that?

::: misses
- [any] Offset ÷ 1200.
:::
:::
:::

::: check
kind: parts
given: f = 2 | 10 | 50; z = 0.5 | 0.707; d = 1 | 5

## A loop with $f_n$ = {f} Hz and ζ = {z} meets a {d} Hz frequency step.

::: part
answer: 4/(z*2*pi*f)*1000
unit: ms
tolerance: 0.5%

### About how long does it take to settle?

::: misses
- [any] $4/(\zeta\omega_n)$.
:::
:::

::: part
answer: 0.456*d/f*180/pi
unit: °
tolerance: 2%

### Roughly what peak phase error does it reach (using 0.456 Δω/ω_n)?

::: misses
- [any] 0.456 × Δf/f_n radians.
:::
:::
:::

::: explain
## Why does a Costas loop for BPSK have a 180° ambiguity, and how do links deal with it?

::: model
BPSK sends data by flipping the carrier's phase by 180°, so a received signal at some phase looks exactly like the opposite data at the phase 180° away. The Costas detector is built to ignore the data by multiplying the error by the sign of each decision, which means it also can't tell those two phase references apart, and the loop settles happily at either one. If it settles at the wrong one, every bit comes out inverted. Links resolve this either by sending a known pattern such as a sync word and checking whether it arrives inverted, or by differential encoding, where each bit is carried by whether the phase changed, which is the same whichever reference the loop chose.
:::
:::

::: practice

::: check
given: f = 0.1 | 100; R = 50 | 1e6
answer: 360*f/R
unit: °
tolerance: 0.5%

## Rotation per symbol: {f} Hz offset at {R} symbols/s?

::: misses
- [any] $360\Delta f/R$.
:::
:::

::: check
given: d = 1 | 3 | 30; n = 3 | 100
answer: exp(-pi/4)*d/n*180/pi
unit: °
tolerance: 0.5%

## Peak error: {d} Hz step, $f_n$ = {n} Hz, ζ = 0.707?

::: misses
- [any] $e^{-\pi/4}\Delta f/f_n$.
:::
:::
:::
