---
title: Control loops in firmware
heading: Sampled feedback, fixed-point PI and windup
eyebrow: C12 · Lesson 46 · Control loops in firmware
xp: 40
---

::: hook
A motor holding its speed, a heater holding a temperature, a power supply holding its voltage: each is a feedback loop, and on a microcontroller it's a few lines in a timer interrupt. Read the sensor, compare with the set point, compute an output, write it to the PWM. The control theory carries over from continuous time with three twists that come from the processor: the loop only acts at sample instants, every sample adds delay, and the arithmetic is fixed point. Each one changes the gains a loop can use.
:::

::: play
- The stems are a sampled loop's step response: a first-order plant with a 20 ms time constant, sampled every 1 ms, under proportional control with gain K.
- Small K: slow, with a large steady-state error. Raise K: faster and closer to the set point. Past K = 20 the response alternates sign each sample; past K = 40 it grows without limit.
- The readouts give the loop's discrete pole, whose size sets the decay per sample, and the steady-state error.
:::

```sim plot
view: graph
x: n = 0..40 samples
y: y = -0.5..2
slider: K = 0.5..45 step 0.5 = 4
plot: K*(1 - exp(-0.05))/(exp(-0.05) - 1 + 1 + K*(1 - exp(-0.05)))*(1 - (exp(-0.05) - K*(1 - exp(-0.05)))^n) | stems | label: output
plot: 1 + 0*n | dashed | label: set point
readout: pole = exp(-0.05) - K*(1 - exp(-0.05)) | digits: 3
readout: steady-state error (%) = 100/(1 + K) | digits: 3
```

::: predict
## A speed loop runs at 1 kHz and its crossover is 50 Hz. The ADC sample, the computation and the PWM update together delay the output by about 1.5 samples. How much phase margin does that cost?

- [ ] Under 1°
- [ ] About 5°
- [x] About 27°
- [ ] About 90°

::: reveal
A delay $T_d$ subtracts $360° f T_d$ of phase at frequency f: $360 \times 50 \times 1.5\text{ ms} = 27°$. A loop designed in continuous time with 45° of margin would be left with 18°, ringing hard. Sampling at 10 kHz instead costs only 2.7°; the rule of thumb is to sample at 10 to 20 times the crossover.
:::
:::

::: nameit
## The sampled loop

At each sample: error $e_n = r - y_n$; output $u_n = K_p e_n + I_n$; integrator $I_{n+1} = I_n + K_i T_s e_n$. A first-order plant $\tau\dot y = Gu - y$ sampled every $T_s$ becomes $y_{n+1} = a y_n + b u_n$ with $a = e^{-T_s/\tau}$ and $b = G(1 - a)$. Under proportional control the loop's pole is $a - bK$:
- $|a - bK| < 1$ for stability, so $K < (1 + a)/b$;
- a negative pole alternates sign each sample;
- the steady-state error is $1/(1 + KG)$, which the integrator removes.

## Delay

Everything between reading the sensor and changing the output is delay: conversion, computation, and the zero-order hold of the PWM, worth half a sample on average. A total delay $T_d$ costs $360° f_c T_d$ of phase margin at the crossover $f_c$.

## Fixed point

Gains are stored as integers with fraction bits: $K_p = 0.75$ in Q8 is 192, and $u = (192 e) \gg 8$. Small integral gains need more fraction bits ($K_iT_s = 0.002$ in Q16 is 131, an error of 0.05%) and a wide accumulator.

## Windup

When the output saturates (PWM at 100%), the error persists and the integrator keeps growing; when the error finally reverses, the integrator must unwind before the output leaves the limit, causing a large overshoot. **Anti-windup**: stop integrating while the output is saturated in the direction of the error, or clamp the integrator.
:::

::: example
## The play's plant ($\tau$ = 20 ms, $T_s$ = 1 ms, G = 1) runs with K = 4. What are its pole, its steady-state error and its gain limit?

::: solution
1. **Plant coefficients.** With $T_s/\tau = 0.05$:
   $$\begin{aligned} a &= e^{-0.05} \\ &= 0.951 \end{aligned}$$
   and $b = 0.049$.
2. **The pole.**
   $$\begin{aligned} p &= a - bK \\ &= 0.95123 - 0.04877 \times 4 \\ &= 0.756 \end{aligned}$$
   so errors shrink by a quarter each sample.
3. **Steady-state error.**
   $$\frac{1}{1 + 4} = 20\%$$
4. **Gain limit.**
   $$K < \frac{1 + a}{b} = 40.0$$
5. **Where it starts to alternate.** Past $K = a/b = 19.5$ the pole goes negative and the output alternates.

**Answer:** the pole is 0.756, the steady-state error is 20%, and the gain limit is K < 40.0.
:::
:::

::: example
## Encode $K_p = 0.75$ in Q8 and $K_iT_s = 0.002$ in Q16. What does an error of 100 codes produce from the proportional term?

::: solution
1. **Encode $K_p$ in Q8.**
   $$0.75 \times 256 = 192$$
   exactly.
2. **Encode $K_iT_s$ in Q16.**
   $$0.002 \times 65\,536 = 131.07$$
   stored as 131, which is 0.0019989, 0.05% low.
3. **The proportional term.**
   $$(192 \times 100) \gg 8 = 75$$
4. **Why the integrator gets more fraction bits.** With Q8, the smallest nonzero integral gain would be 1/256 = 0.0039, twice too big.

**Answer:** $K_p$ is 192 in Q8 and $K_iT_s$ is 131 in Q16, and an error of 100 codes gives a proportional term of 75.
:::
:::

::: example
## A heater's PWM saturates at 100% for 30 s while a cold tank warms up, with an error of 500 codes, and the integrator adds $K_iT_s e$ = 0.002 × 500 each millisecond. How much does it wind up?

::: solution
1. **What each sample adds.**
   $$0.002 \times 500 = 1.0$$
2. **Over 30 s.** 30,000 samples add 30,000 output units, far beyond the 100% limit.
3. **What happens next.** When the tank reaches temperature, the output stays saturated until that has unwound, so the tank overshoots badly.
4. **The fix.** Conditional integration (skipping the integrator update while the output is saturated and the error would push it further) keeps the integrator at whatever value holds the set point.

**Answer:** it winds up by 30,000 output units, far beyond the 100% limit.
:::
:::

::: check
kind: parts
given: t = 5 | 20 | 100; T = 0.5 | 1 | 2; K = 1 | 4 | 10

## A plant with G = 1 and τ = {t} ms is sampled every {T} ms under proportional gain {K}.

::: part
answer: exp(-T/t) - K*(1 - exp(-T/t))
tolerance: 0.5%

### Where is the loop's pole?

::: misses
- [exp(-T/t)] That's the open-loop pole; feedback moves it by $-bK$.
- [any] $a - bK$, with $a = e^{-T_s/\tau}$ and $b = 1 - a$.
:::
:::

::: part
answer: (1 + exp(-T/t))/(1 - exp(-T/t))
tolerance: 0.5%

### What is the largest stable gain?

::: misses
- [any] $(1 + a)/b$.
:::
:::
:::

::: check
kind: parts
given: K = 2 | 5 | 20; G = 0.4 | 1.5 | 3

## A loop has proportional gain {K} and plant DC gain {G}.

::: part
answer: 100/(1 + K*G)
unit: %
tolerance: 0.5%

### What is the steady-state error, as a share of the set point?

::: misses
- [100/K] The plant's gain multiplies the controller's.
- [any] $1/(1 + KG)$.
:::
:::

::: part
answer: 100*K*G/(1 + K*G)
unit: %
tolerance: 0.5%

### Where does the output settle?

::: misses
- [any] $KG/(1 + KG)$ of the set point.
:::
:::
:::

::: check
kind: parts
given: f = 1 | 5 | 20; c = 20 | 50 | 100; d = 1.5 | 2 | 2.5

## A loop sampled at {f} kHz crosses over at {c} Hz with a total delay of {d} samples.

::: part
answer: 360*c*d/(f*1000)
unit: °
tolerance: 0.5%

### How much phase margin does the delay cost?

::: misses
- [360*c/(f*1000)] Multiply by the number of samples of delay.
- [any] $360° f_c T_d$.
:::
:::

::: part
answer: f*1000/c
tolerance: 0.5%

### How many times the crossover is the sample rate?

::: misses
- [any] $f_s/f_c$.
:::
:::
:::

::: check
kind: parts
given: k = 0.3 | 0.75 | 1.9; q = 8 | 12; e = 37 | 250

## A gain of {k} is stored in Q{q} and multiplies an error of {e} codes.

::: part
answer: round(k*2^q)
tolerance: 0

### What integer stores the gain?

::: misses
- [any] $k \cdot 2^q$, rounded.
:::
:::

::: part
answer: floor(round(k*2^q)*e/2^q)
tolerance: 0

### What does the product, shifted right by {q}, give?

::: misses
- [any] Multiply, then shift.
:::
:::
:::

::: check
kind: parts
given: g = 0.001 | 0.002 | 0.01; e = 100 | 500; t = 5 | 30; T = 1 | 10

## An integrator adds {g} × e every {T} ms; the output is saturated for {t} s with an error of {e} codes.

::: part
answer: g*e*t*1000/T
tolerance: 0.5%

### How much does the integrator wind up?

::: misses
- [g*e*t] Count the samples: {t} s at one every {T} ms.
- [any] Per-sample increment × number of samples.
:::
:::

::: part
answer: t*1000/T
tolerance: 0.5%

### Over how many samples?

::: misses
- [any] Time ÷ sample period.
:::
:::
:::

::: check
kind: parts
given: c = 10 | 50 | 200; r = 10 | 20

## A loop needs a crossover of {c} Hz and is sampled at {r} times that.

::: part
answer: r*c
unit: Hz
tolerance: 0.5%

### What sample rate?

::: misses
- [any] {r} × crossover.
:::
:::

::: part
answer: 1.5*360/r
unit: °
tolerance: 0.5%

### With 1.5 samples of delay, what phase does it lose?

::: misses
- [any] $360° \times 1.5/r$.
:::
:::
:::

::: check
kind: choice

## A motor's speed loop works well in testing, but after a long stall the motor overshoots wildly when it's freed. What's the likely fix?

- [ ] Raise the proportional gain
- [x] Stop the integrator from accumulating while the output is saturated
- [ ] Sample faster
- [ ] Use a longer moving average on the speed reading

::: misses
- [1] More gain doesn't unwind a saturated integrator any faster.
- [3] The overshoot comes from stored integrator error, not sampling.
- [4] More filtering adds delay and makes it worse.
:::
:::

::: check
kind: python

## Write `pi_step(i_acc, e, kp_q8, ki_q16, umin, umax)`: one sample of an integer PI controller. The output is `((kp_q8 * e) >> 8) + (i_acc >> 16)`, clamped to [umin, umax]. Update the accumulator by `ki_q16 * e` only if that doesn't push a saturated output further into its limit. Return (u, new i_acc).

```python starter
def pi_step(i_acc, e, kp_q8, ki_q16, umin, umax):
    return (0, i_acc)
```

```python solution
def pi_step(i_acc, e, kp_q8, ki_q16, umin, umax):
    raw = ((kp_q8 * e) >> 8) + (i_acc >> 16)
    u = min(max(raw, umin), umax)
    pushing_up = raw >= umax and e > 0
    pushing_down = raw <= umin and e < 0
    if not (pushing_up or pushing_down):
        i_acc += ki_q16 * e
    return (u, i_acc)
```

```python tests
u, acc = pi_step(0, 100, 192, 131, 0, 1000)
assert u == 75 and acc == 13100, "0.75 × 100 = 75; the integrator gains 131 × 100."
u, acc = pi_step(5000 << 16, 500, 192, 131, 0, 1000)
assert u == 1000 and acc == 5000 << 16, "Saturated high with positive error: no integration."
u, acc = pi_step(5000 << 16, -10, 192, 131, 0, 1000)
assert u == 1000 and acc == (5000 << 16) - 1310, "Negative error unwinds even while saturated."
u, acc = pi_step(0, -50, 192, 131, 0, 1000)
assert u == 0 and acc == 0, "Saturated low with negative error: no integration."
```

::: right
Right. That conditional integration is the most common anti-windup scheme in embedded controllers.
:::
:::

::: explain
## Why does a sampled control loop tolerate less gain than the same loop in continuous time?

::: model
A continuous controller reacts to the error the instant it changes, but a sampled one only sees the error at sample instants and then holds its output until the next one, so its reaction is always late by some fraction of a sample period, plus the time to convert and compute. That delay subtracts phase at the crossover frequency, and the higher the gain, the higher the crossover and the more phase the same delay costs. Eventually the correction arrives so late that it pushes in the wrong direction, and the loop oscillates. In the discrete model this shows up as the closed-loop pole moving past −1, which a continuous first-order loop can never do.
:::
:::

::: practice
::: check
given: K = 3 | 8 | 15; G = 1 | 2
answer: 100/(1 + K*G)
unit: %
tolerance: 0.5%

## Steady-state error with P gain {K} and plant gain {G}?

::: misses
- [any] $1/(1 + KG)$.
:::
:::

::: check
given: f = 2 | 10; c = 50 | 250
answer: 360*c*1.5/(f*1000)
unit: °
tolerance: 0.5%

## Phase lost to 1.5 samples of delay at {f} kHz, crossover {c} Hz?

::: misses
- [any] $360° f_c T_d$.
:::
:::

::: check
given: k = 0.6 | 2.4; q = 8 | 10
answer: round(k*2^q)
tolerance: 0

## Q{q} integer for a gain of {k}?

::: misses
- [any] $k \cdot 2^q$.
:::
:::
:::
