---
title: "Digital control lab: sampled loops in code"
heading: Zero-order-hold discretization, the critical gain of a sampled loop with and without a computation delay, Tustin PI coefficients, prewarping and coefficient rounding
eyebrow: S9 · Lesson 48 · Digital control lab
xp: 60
---

::: hook
Lessons 41 and 42 described what sampling does to a loop: the hold's lag, the computation delay, the Tustin approximation, the trouble with poles near z = 1. In this lab you'll see each effect in numbers by building the pieces of a digital controller: discretize a plant exactly, find by simulation the gain at which a sampled loop goes unstable, write a PI law as a difference equation, design a filter corner that lands where it should after warping, and measure what rounding does to a slow pole.
:::

::: play
- The curves are the closed-loop pole magnitudes of a sampled first-order plant (Φ = 0.607, Γ = 0.787) under proportional control, against the gain $K_p$.
- Without delay the pole is $\Phi - \Gamma K_p$, leaving the unit circle at $K_p = (1 + \Phi)/\Gamma$ = 2.04.
- With one sample of computation delay the poles solve $z^2 - \Phi z + \Gamma K_p = 0$; once complex, their magnitude is $\sqrt{\Gamma K_p}$, which reaches 1 at $K_p = 1/\Gamma$ = 1.27. One sample of delay costs 38% of the usable gain.
:::

```sim plot
view: graph
x: K = 0..2.5
y: m = 0..1.4
plot: abs(0.6065 - 0.7869*K) | label: no delay
plot: step(0.7869*K - 0.6065^2/4)*sqrt(0.7869*K) + step(0.6065^2/4 - 0.7869*K)*(0.6065 + sqrt(abs(0.6065^2 - 4*0.7869*K)))/2 | dashed | label: one-sample delay
plot: 1 + 0*K | dashed | label: unit circle
```

::: predict
## A PI controller ($K_p$ = 1, $T_i$ = 10 ms) is discretized by Tustin's method at T = 1 ms. With the error held at 1 from the first sample, what does it output at sample 4 (the fifth sample)?

- [ ] 1.4
- [x] 1.45
- [ ] 1.5
- [ ] 1.05

::: reveal
Tustin integrates with the trapezoid rule, so a constant error from k = 0 gives $u_k = K_p(1 + (k + \frac12)T/T_i)$: at k = 4, $1 + 4.5 \times 0.1 = 1.45$. The continuous PI would output 1.4 at t = 4 ms; the half-sample lead is the trapezoid counting the first sample's interval as half-filled.
:::
:::

::: nameit
## What the lab computes

- **ZOH discretization** of $K_0/(\tau s + 1)$: $\Phi = e^{-T/\tau}$, $\Gamma = K_0(1 - \Phi)$.
- **Critical gain** of $u_k = K_p(r - y_k)$ (no delay) or $u_k = K_p(r - y_{k-1})$ (one-sample delay): found by simulating the loop and bisecting on whether the response decays, then compared with $(1 + \Phi)/\Gamma$ and $1/\Gamma$.
- **Tustin PI**: $u_k = u_{k-1} + b_0e_k + b_1e_{k-1}$ with $b_0 = K_p(1 + T/2T_i)$ and $b_1 = -K_p(1 - T/2T_i)$.
- **Prewarping**: Tustin maps an analog frequency $\omega_a$ to the digital $\omega_d = \frac2T\tan^{-1}\frac{\omega_aT}{2}$, so a digital corner $f_c$ needs an analog design at $f_a = \frac{f_s}{\pi}\tan\frac{\pi f_c}{f_s}$.
- **Rounding**: a pole $e^{-T/\tau}$ stored to B fractional bits becomes round$(2^Bz)/2^B$, with effective time constant $-T/\ln z_q$.
:::

::: check
kind: python

## Write `critical_gain(Phi, Gamma, delay)`: the gain at which the sampled loop with plant $y_{k+1} = \Phi y_k + \Gamma u_k$ and proportional control (on $y_k$, or on $y_{k-1}$ when delay is True) becomes unstable, by bisection between 0 and 10 on whether $|y_k|$ after 2000 steps from y = 1 (zero reference) is below 1.

```python starter
def critical_gain(Phi, Gamma, delay):
    return (1 + Phi) / Gamma
```

```python solution
def critical_gain(Phi, Gamma, delay):
    def decays(K):
        y, prev = 1.0, 1.0
        for _ in range(2000):
            meas = prev if delay else y
            u = -K * meas
            prev = y
            y = Phi * y + Gamma * u
            if abs(y) > 1e6:
                return False
        return abs(y) < 1
    lo, hi = 0.0, 10.0
    for _ in range(60):
        mid = (lo + hi) / 2
        if decays(mid):
            lo = mid
        else:
            hi = mid
    return lo
```

```python tests
import math
Phi = math.exp(-0.5)
Gamma = 2 * (1 - Phi)
assert abs(critical_gain(Phi, Gamma, False) - (1 + Phi) / Gamma) < 0.01, "No delay: (1 + Φ)/Γ = 2.04."
assert abs(critical_gain(Phi, Gamma, True) - 1 / Gamma) < 0.01, "One-sample delay: 1/Γ = 1.27."
```

::: right
Right. Near the limit the decay is slow, so bisection by simulation lands within about a percent; the closed forms give the exact edge.
:::
:::

::: check
kind: python

## Write `tustin_pi(Kp, Ti, T)` returning $(b_0, b_1)$, and `run_pi(b0, b1, errors)` returning the outputs of $u_k = u_{k-1} + b_0e_k + b_1e_{k-1}$ from rest.

```python starter
def tustin_pi(Kp, Ti, T):
    return Kp, 0.0

def run_pi(b0, b1, errors):
    return [b0 * e for e in errors]
```

```python solution
def tustin_pi(Kp, Ti, T):
    return Kp * (1 + T / (2 * Ti)), -Kp * (1 - T / (2 * Ti))

def run_pi(b0, b1, errors):
    out, u, last = [], 0.0, 0.0
    for e in errors:
        u = u + b0 * e + b1 * last
        last = e
        out.append(u)
    return out
```

```python tests
b0, b1 = tustin_pi(1.0, 0.01, 0.001)
u = run_pi(b0, b1, [1.0] * 10)
assert all(abs(u[k] - (1 + (k + 0.5) * 0.1)) < 1e-12 for k in range(10)), "Constant error: K_p(1 + (k + ½)T/T_i)."
assert abs(u[4] - 1.45) < 1e-12, "1.45 at k = 4."
```

::: right
Right. The trapezoid rule's half sample at the start is why Tustin's PI leads the continuous one by T/2 in its integral.
:::
:::

::: check
kind: python

## Write `prewarp(fc, fs)`: the analog corner that Tustin's method maps to fc at sample rate fs, and `tustin_maps(fa, fs)`: the digital frequency an analog fa lands on.

```python starter
def prewarp(fc, fs):
    return fc

def tustin_maps(fa, fs):
    return fa
```

```python solution
import math

def prewarp(fc, fs):
    return fs / math.pi * math.tan(math.pi * fc / fs)

def tustin_maps(fa, fs):
    T = 1 / fs
    wa = 2 * math.pi * fa
    return 2 / T * math.atan(wa * T / 2) / (2 * math.pi)
```

```python tests
assert abs(prewarp(200, 1000) - 231.27) < 0.01, "A 200 Hz corner at 1 kHz needs a 231.3 Hz analog design."
assert abs(tustin_maps(prewarp(200, 1000), 1000) - 200) < 1e-9, "And lands exactly on 200 Hz."
assert abs(tustin_maps(200, 1000) - 200) > 15, "Without prewarping it lands well below."
```

::: right
Right. The warping compresses the whole analog axis into the band below fs/2, so the higher the corner, the more correction it needs.
:::
:::

::: check
kind: python

## Write `quantized_tau(tau, T, bits)`: round the pole $e^{-T/\tau}$ to the nearest multiple of $2^{-\text{bits}}$ and return the time constant it really represents.

```python starter
def quantized_tau(tau, T, bits):
    return tau
```

```python solution
import math

def quantized_tau(tau, T, bits):
    z = math.exp(-T / tau)
    zq = round(z * 2 ** bits) / 2 ** bits
    return -T / math.log(zq)
```

```python tests
assert abs(quantized_tau(1.0, 0.001, 10) - 1.0235) < 1e-4, "10 bits: 1.0235 s."
assert abs(quantized_tau(1.0, 0.001, 16) - 0.9925) < 1e-4, "16 bits: 0.9925 s."
assert abs(quantized_tau(1.0, 0.01, 16) - 1.0) < 2e-3, "Sampling ten times slower makes the same bits ten times more accurate."
```

::: right
Right. The error scales with τ/T: slow filters at fast sample rates need the most bits, or a form that stores 1 − z directly.
:::
:::

::: explain
## Why does a single sample of computation delay lower the gain at which a sampled loop goes unstable so much?

::: model
Without the delay, the controller reacts to the measurement in the same sample, and the closed loop is first order: the pole moves along the real axis and leaves the unit circle only when the gain pushes it below minus one. A one-sample delay adds a second pole to the loop, and as the gain rises the two poles meet and become a complex pair whose magnitude grows with the square root of the gain, so they reach the unit circle sooner, and the loop rings before it goes unstable. In frequency terms, the extra sample is extra phase lag at every frequency, which eats into the phase margin the loop had.
:::
:::
