Primers
Feedback control
Feedback control is measuring what a machine is doing, comparing it with what you wanted, and correcting by the difference, over and over. It’s how a robot’s wheel holds a speed when the floor tilts, the battery sags or one motor is a little weaker than the other. The most common recipe is PID: proportional, integral and derivative.
The examples on this page hold the speed of one wheel on a small robot: a 60 mm wheel, a geared motor that does about 330 mm/s at full power, and an encoder that gives about 4,300 counts a wheel turn. If counts are new to you, read encoders and odometry first. Pick your level at the top of the page.
High school
Open loop: set it and hope
The simplest way to drive a motor at 200 mm/s is to work out the power that gives 200 mm/s and send that. On a flat desk, 67% power might do it. That’s open loop: nothing checks what happened.
Then the robot starts up a slope. The motor has more to push, and at the same 67% it slows to 160 mm/s. Nothing notices. The same thing happens as the battery runs down, or when one motor is a bit stiffer than the other, which is why a robot driven open loop drifts off a straight line.
Closed loop: measure and correct
Closed loop adds a measurement. The encoder counts how far the wheel turned since the last check, which gives its speed. A small program, the controller, does three things, 100 times a second:
- Measure the speed.
- Work out the error: the speed you wanted minus the speed you got.
- Change the power to make the error smaller.
You do this when you ride a bike up a hill. You feel yourself slowing, and you push harder. The power isn’t set in advance. It’s whatever it takes.
Hold each wheel’s speed this way and a two-wheeled robot with one weaker motor drives much straighter, because the weaker side gets more power. Steering toward a point works the same way: the error is which way the robot should face minus which way it does face.
P: push in proportion to the error
The first rule is proportional control:
power = gain × error
Way too slow, push hard. Nearly there, push gently. The gain sets how hard. With a gain of 0.01, an error of 50 mm/s gives 0.5, half power.
P has a catch. It only pushes when there’s an error. To keep a motor going at all it needs some power, so it needs some error. With a gain of 0.01, this wheel settles at about 149 mm/s, not 200: 51 mm/s short is exactly the error that makes the power it needs. A bigger gain makes the gap smaller, but it never closes.
I: add up the error over time
The fix is integral control. Keep a running total of the error, and add some of it to the power. While the wheel is slow, the total keeps growing, so the push keeps growing, until the error is gone. Then the total stops changing and holds the power right where it’s needed. P and I together are a PI controller, and they hold this wheel at 200 mm/s, slope or no slope.
The running total needs one guard. The power can’t go past full. If the wheel is stuck, or still speeding up from rest, the error stays large and the total keeps growing. When the wheel finally gets going, that big total keeps the power high for too long and the wheel shoots past the speed you asked for. That’s called windup. One cure is to stop adding to the total while the power is already at full.
D: watch how fast the error changes
Derivative control looks at how fast the error is changing and pushes against the change, like easing off the pedals before you reach the speed you want. It helps machines that swing past their target, like a heavy arm.
For a wheel’s speed it often does more harm than good. The speed comes from counting, and the count jumps by whole counts, so the measured speed jitters a little every check. D reacts to every jitter, and the power jumps about. PI, with D left out, is common for exactly this reason.
Tuning
Tuning means picking the gains. A common way to do it by hand: start with P only, and raise its gain until the wheel gets up to speed quickly. Too much, and the power starts to jump about or the speed swings back and forth, so back off. Then add I, a little at a time, until the leftover error goes away quickly without overshooting.
Check yourself
- A robot is driven open loop at a fixed power. Name two things that would change its speed.
- With P control and a gain of 0.01, the motor needs 0.6 power to hold its speed. How far below the target will it settle?
- Why does PI reach the target when P alone doesn’t?
- Why is D often left out of a wheel’s speed control?
<details><summary>Answers</summary>
- Any two of: a slope, a different floor, the battery running down, a stiffer motor or gearbox, more weight on board.
- Power = gain × error, so the error is 0.6 ÷ 0.01 = 60 mm/s below the target.
- P needs an error to make any power at all. The integral keeps growing while there’s an error, so it can supply the power by itself once the error is zero.
- The speed is measured by counting, so it jitters by a count or so each check. D reacts to every jitter and makes the power jumpy.
</details>
College
The loop in code
A digital controller runs at a fixed period h, here 10 ms (100 Hz). Each tick k:
eₖ = r − yₖ (the error: target minus measurement)
uₖ = sat(Kₚ eₖ + Kᵢ Iₖ), then Iₖ₊₁ = Iₖ + eₖ h
The output goes to the motor first and the integral is updated after, so the time from reading the encoder to writing the duty stays short. sat() clamps the output to what the actuator can do: PWM duty from −1 (full reverse) to +1 (full forward). Kᵢ is per second, so the integral uses the real period h. If the loop’s period changes, the integral’s effect changes with it, which is one reason the loop runs from a hardware timer at a fixed rate, not as fast as it can.
PID adds a derivative term. Taking it on the measurement, not the error, avoids a spike in the output when the target steps (the “derivative kick”):
Dₖ = −Kd (yₖ − yₖ₋₁) ÷ h
Speed from counts
The measurement is counts since the last tick, scaled:
yₖ = Δcountₖ ÷ N × πD ÷ h
With N = 4,300 counts a turn, D = 60 mm and h = 10 ms, one count in a tick is 188.5 ÷ 4,300 ÷ 0.01 ≈ 4.4 mm/s. At 200 mm/s a tick sees about 45 or 46 counts, so the measurement steps between neighbouring values. Through P that step is a jump of Kₚ × 4.4 in the duty, 0.044 at Kₚ = 0.01. Through D it’s worse: a 4.4 mm/s step over 10 ms is 440 mm/s² of apparent acceleration, from nothing but counting.
Why P leaves an error
Model the motor in steady state as speed = K × duty − L, where K is the speed per unit duty (330 mm/s) and L is what the load costs. Put in u = Kₚ(r − y) and solve:
y = (K Kₚ r − L) ÷ (1 + K Kₚ)
With K Kₚ = 3.3 and L = 20 mm/s, a 200 mm/s target gives 149 mm/s. On a slope, L = 60, it’s 140. Raising Kₚ shrinks the error by 1 ÷ (1 + K Kₚ), but noise and stability limit how far you can go. The integral changes the steady state completely: I can only stop changing when e = 0.
Saturation and windup
At start-up the error is 200 mm/s, Kₚe = 2, and the duty clamps at 1. While it’s clamped, the loop is open: the output no longer depends on the measurement. The integral keeps growing anyway, and has to be unwound by error of the other sign, which means overshoot. Two common guards:
- Conditional integration (clamping): don’t add to I while the output is saturated.
- Limits on I: cap the integral so it alone can’t ask for more than full output.
Tuning by hand
- Kᵢ = Kd = 0. Step the target and raise Kₚ until the rise is quick. Back off when the duty starts to chatter or the speed overshoots and rings.
- Add Kᵢ until the steady error goes away in a time you can live with. Too much and it overshoots and oscillates slowly. A starting point for a motor with a time constant τ is Kᵢ = Kₚ ÷ τ.
- Try the cases that break things: a step from rest (it will saturate), a load step (a slope, a hand on the wheel), and a slow target, where there are few counts a tick.
- Add D only if the response still rings, and filter it.
Ziegler and Nichols published tuning rules in 1942 from the gain at which a P loop starts to oscillate. They’re a starting point. Åström and Murray, in Learn more, note that the loops they give are sensitive to changes in the process.
Check yourself
- With K = 330 mm/s, L = 20 mm/s and Kₚ = 0.03, where does P settle for a 200 mm/s target?
- The loop period drifts between 8 and 14 ms, but the code assumes 10 ms. What goes wrong with I, and with speed?
- Why take D on the measurement rather than on the error?
- Holding 20 mm/s, how many counts does a 10 ms tick see? What does that do to the control?
<details><summary>Answers</summary>
- K Kₚ = 9.9, so (9.9 × 200 − 20) ÷ 10.9 ≈ 180 mm/s.
- Both are scaled by the wrong h. The speed reads high on long ticks and low on short ones, which looks like noise, and the integral’s effective gain wanders. Time each tick, or run the loop from a hardware timer.
- A step in the target is a step in the error, and its derivative is a spike in the output. The measurement can’t step, so its derivative doesn’t spike.
- About 4 or 5. The measurement steps by 20% of the target, so P and D turn it into a jumpy duty. Use a longer window for the speed, time the edges, or lower the gains at low speed.
</details>
University
A discrete-time model
A small DC motor’s speed, with the current’s dynamics much faster than the mechanics, is close to first order: τ dω/dt = K u − L − ω. With the duty held for each period h (a zero-order hold), it’s exactly
ωₖ₊₁ = a ωₖ + b uₖ − (1 − a) L, with a = e^(−h/τ) and b = K(1 − a)
For τ = 0.1 s and h = 10 ms, a ≈ 0.905 and b ≈ 31.4 mm/s per unit duty.
Stability
With P acting on a measurement of ωₖ, uₖ = Kₚ(r − ωₖ), the closed loop’s pole is a − b Kₚ. It leaves the unit circle at Kₚ = (1 + a) ÷ b ≈ 0.061. In continuous time a first-order loop is stable at any gain. Sampling is what puts a limit on it. A delay lowers the limit: compute the duty from the previous tick’s measurement and the characteristic polynomial is z² − a z + b Kₚ, which reaches the unit circle at Kₚ = 1 ÷ b ≈ 0.032. Keep the time from reading the encoder to writing the duty short, and count any filter as delay.
PI and where its poles go
The PI in code above is C(z) = Kₚ + Kᵢ h ÷ (z − 1). The pole at z = 1 makes the loop type 1, so the steady error to a step in the target or the load is zero (the final value theorem).
In continuous time, choosing Tᵢ = Kₚ ÷ Kᵢ = τ cancels the motor’s pole. The loop gain G(s) = K Kₚ ÷ (τs) gives a first-order closed loop with time constant τ ÷ (K Kₚ), 30 ms for these numbers. That’s how the gains in Try it were picked. The cancellation is only in the response to the target. The motor’s pole is still there in the response to a load, so a load step is corrected with the slower time constant τ, which shows in Try it after the slope starts.
Anti-windup
When the output saturates, the integrator integrates an error the actuator can’t act on. Conditional integration freezes it. Back-calculation feeds the difference between the saturated and unsaturated output back into the integrator, as Åström and Murray write it, with I here the integral term itself:
Iₖ₊₁ = Iₖ + Kᵢ h eₖ + (h ÷ Taw)(sat(vₖ) − vₖ)
where vₖ is the output before the clamp, and the tracking time Taw sets how fast the integrator is pulled back.
Derivative filtering
An ideal derivative has gain rising without bound with frequency, and encoder quantisation is broadband noise of about one count a tick. The usual fix replaces Kds with Kds ÷ (1 + s Tf), with Tf = Td ÷ N and N typically 5 to 20. Discretised with a backward difference:
Dₖ = Tf ÷ (Tf + h) × Dₖ₋₁ − Kd ÷ (Tf + h) × (yₖ − yₖ₋₁)
The coefficient Tf ÷ (Tf + h) is between 0 and 1 for any h, so the filter is stable however coarse the sampling. The filter adds lag, which eats into the phase margin D was meant to add. A first-order plant lags by at most 90°, so a PI loop around it has little phase to win back, and a speed loop like this one can do without D.
Feed-forward
If you know the motor’s curve, compute most of the duty in advance: uff = (r + L̂) ÷ K, from a measured table of duty against speed. The feedback then corrects only the model’s error, so it works at small error, far from saturation, and a change of target is followed at once instead of after the integral catches up. Small geared motors often don’t turn at all below some duty (static friction), and a feed-forward table is a good place to step over that dead band.
Check yourself
- With a = 0.905 and b = 31.4, what P gain puts the pole at 0, a “deadbeat” loop? Would it work on a real wheel?
- Show that with PI and Tᵢ = τ, the target response is first order. Why isn’t the load response?
- A loop at 100 Hz runs its speed through a moving average of 8 ticks before the controller. What happens to the largest stable gain, roughly, and why?
- Why must the integral term, unlike P and D, always act on the error and not on the measurement alone?
<details><summary>Answers</summary>
- Kₚ = a ÷ b ≈ 0.029. In the model the speed settles in one tick, at P’s steady state, still short of the target. On a real wheel the duty saturates on any large step, and a gain that high turns every count of quantisation into a duty jump of about 0.13. It’s a limit, not a design.
- G(s) = K Kₚ(1 + sτ) ÷ (sτ(1 + sτ)) = K Kₚ ÷ (sτ), so the target’s response is 1 ÷ (1 + sτ ÷ (K Kₚ)). The load enters at the motor, with P(s) = K ÷ (1 + sτ), and its response P(s) ÷ (1 + G(s)) keeps the pole at −1/τ.
- It falls. An 8-tick average delays the measurement by about 3.5 ticks, 35 ms, which costs phase at the crossover, and the largest stable gain drops with it. Average less, or use a filter with less delay.
- The integral stops changing only when what it adds up is zero. Adding up the error, that’s at the target. Adding up the measurement alone, it would be at zero speed.
</details>
Try it
No motor needed: a toy wheel in Python, under P and under PI, side by side. The loop runs 100 times a second and sees the speed only through encoder counts, as a real one does. At 1.5 s the robot starts up a slope. The motor’s numbers are typical round ones, not any one motor’s. You need only a container runtime. Start a shell with Python in it:
container
container run --rm -it docker.io/library/python:3.14-alpine sh
docker
docker run --rm -it python:3.14-alpine sh
podman
podman run --rm -it docker.io/library/python:3.14-alpine sh
Inside it, save the program and run it:
cat > speed_hold.py <<'EOF'
"""A wheel's speed held by P and by PI control, 100 times a second, from encoder counts.
The motor is a toy: full power is 330 mm/s, and it takes about 0.1 s to get most of the way to a new speed. The
numbers are typical round ones for a small geared motor, not any one motor's. Change them and run it again.
"""
TOP = 330.0 # mm/s at full power, with no load
TAU = 0.10 # s: the motor's time constant
COUNTS = 4300 # encoder counts per wheel turn
TURN = 188.5 # mm a wheel turn (a 60 mm wheel)
DT = 0.01 # s: the loop runs 100 times a second
TARGET = 200.0 # mm/s
KP = 0.01 # power per mm/s of error
KI = 0.10 # power per mm/s of error, per second it lasts
ANTI_WINDUP = True # stop adding to the integral while the power is at its limit
def load(t):
return 20.0 if t < 1.5 else 60.0 # mm/s the load takes off; at 1.5 s the robot starts up a slope
def run(ki):
speed, travel, last_count, integral = 0.0, 0.0, 0, 0.0
rows = []
for n in range(301):
t = n * DT
count = int(travel / TURN * COUNTS) # what the encoder reads now
measured = (count - last_count) / COUNTS * TURN / DT # counts since the last loop, as mm/s
last_count = count
error = TARGET - measured
wanted = KP * error + ki * integral
power = max(-1.0, min(1.0, wanted)) # the PWM can't go past full
if not ANTI_WINDUP or power == wanted:
integral += error * DT
if n in (0, 5, 10, 20, 50, 100, 150, 155, 160, 170, 200, 300):
rows.append((t, speed, power))
for _ in range(10): # the motor between two loops, in small steps
speed += (TOP * power - load(t) - speed) / TAU * DT / 10
travel += speed * DT / 10
return rows
print(f"Target {TARGET:.0f} mm/s. The load goes from 20 to 60 mm/s at 1.5 s.")
print(" time P: speed power PI: speed power")
for (t, sp, pp), (_, si, pi) in zip(run(0.0), run(KI)):
print(f"{t:5.2f} s {sp:6.0f} mm/s {pp:4.2f} {si:6.0f} mm/s {pi:4.2f}")
EOF
python speed_hold.py
Target 200 mm/s. The load goes from 20 to 60 mm/s at 1.5 s.
time P: speed power PI: speed power
0.00 s 0 mm/s 1.00 0 mm/s 1.00
0.05 s 122 mm/s 0.86 122 mm/s 0.86
0.10 s 149 mm/s 0.51 164 mm/s 0.69
0.20 s 150 mm/s 0.51 188 mm/s 0.66
0.50 s 149 mm/s 0.51 200 mm/s 0.65
1.00 s 148 mm/s 0.55 200 mm/s 0.65
1.50 s 149 mm/s 0.51 200 mm/s 0.65
1.55 s 139 mm/s 0.64 192 mm/s 0.76
1.60 s 139 mm/s 0.60 195 mm/s 0.76
1.70 s 140 mm/s 0.60 198 mm/s 0.79
2.00 s 140 mm/s 0.60 200 mm/s 0.77
3.00 s 140 mm/s 0.60 200 mm/s 0.77
The speed columns are the wheel’s real speed, the power columns what the controller sent. Both start at full power, clamped. P settles at 149 mm/s, 51 mm/s short, and on the slope it drops to 140. PI reaches 200 by half a second, is down to 192 just after the slope starts, and is back at 200 by 2 s, with the power up from 0.65 to 0.77 to pay for the slope. The power steps by 0.04 here and there: that’s one encoder count, 4.4 mm/s, times the gain.
Now switch anti-windup off. Save a copy first, then edit it and run the first rows again:
cp speed_hold.py original.py
sed -i 's/ANTI_WINDUP = True/ANTI_WINDUP = False/' speed_hold.py
python speed_hold.py | head -6
Target 200 mm/s. The load goes from 20 to 60 mm/s at 1.5 s.
time P: speed power PI: speed power
0.00 s 0 mm/s 1.00 0 mm/s 1.00
0.05 s 122 mm/s 0.86 122 mm/s 1.00
0.10 s 149 mm/s 0.51 197 mm/s 1.00
0.20 s 150 mm/s 0.51 219 mm/s 0.67
The integral now grows while the power is clamped at full, and PI overshoots to 219 mm/s at 0.2 s, where before it was still climbing at 188.
Then go back to the copy, turn the gain up to KP = 0.05 and run it:
cp original.py speed_hold.py
sed -i 's/^KP = 0.01/KP = 0.05/' speed_hold.py
python speed_hold.py
Target 200 mm/s. The load goes from 20 to 60 mm/s at 1.5 s.
time P: speed power PI: speed power
0.00 s 0 mm/s 1.00 0 mm/s 1.00
0.05 s 122 mm/s 1.00 122 mm/s 1.00
0.10 s 197 mm/s 0.36 197 mm/s 0.36
0.20 s 186 mm/s 0.79 187 mm/s 0.90
0.50 s 190 mm/s 0.36 195 mm/s 0.92
1.00 s 195 mm/s 0.36 194 mm/s 0.66
1.50 s 185 mm/s 0.58 201 mm/s 0.75
1.55 s 186 mm/s 0.58 198 mm/s 0.76
1.60 s 180 mm/s 1.00 196 mm/s 0.77
1.70 s 174 mm/s 1.00 190 mm/s 1.00
2.00 s 186 mm/s 0.58 198 mm/s 0.58
3.00 s 188 mm/s 0.79 195 mm/s 1.00
P now gets closer, 185 to 195 mm/s before the slope, but the power jumps between 0.36 and full from one row to the next, and the speed wanders with it. One count of noise is now 0.22 of full power. A higher gain makes a smaller error and a rougher push.
Type exit to leave.
Learn more
- K. J. Åström and R. M. Murray, Feedback Systems, second edition, free to read online. Chapter 11, PID control, covers windup, derivative filtering, setpoint weighting and a computer implementation.
- Wikipedia’s PID controller page, for history and tuning methods.
- Microchip’s application note AN937, Implementing a PID Controller Using a PIC18 MCU: a PID in integer arithmetic on an 8-bit microcontroller, with limits on the integral.
- B. Beauregard, Improving the Beginner’s PID, by the author of the Arduino PID library: sample time, derivative kick, reset windup, one change at a time.