Discrete PID: From Equations to Code
The roadmap's second practical project is "implement speed control using a microcontroller". Everything so far was transfer functions; the microcontroller needs about thirty lines of code that run in a timer interrupt every millisecond. Those lines decide whether the loop works: how the integral and the derivative are discretised, where the derivative filter goes, how the output is limited, how the integrator is protected and what happens at the very first sample. This lesson writes that code (in Python so you can run it here; it translates line for line to C on the target), tests it against an exact discrete model of the course's DC motor, and lists the implementation traps. Sampling effects and the choice of are in Sampled-Data Loops.
Discretising each term
With sample period and :
| Term | Continuous | Discrete (common choice) |
|---|---|---|
| P | ||
| I | forward Euler (or Tustin: ) | |
| D (filtered, on ) | backward Euler |
Backward Euler is used for the derivative filter because it is stable for any , even ; forward Euler there would be unstable when . Tustin is the most accurate choice when the sample rate is low (Bilinear Transform). Each term above is a first-order difference equation.
Positional and velocity forms. The table is the positional form: it computes itself. The velocity (incremental) form computes the change :
It has no explicit integrator: windup protection is simply clamping , and bumpless transfer is automatic. It is common in PLCs and for actuators that integrate themselves (stepper positions, motorised valves).
The controller code
class PID:
"""Discrete PI(D): setpoint weight b, filtered D on the measurement, output limits, clamping anti-windup."""
def __init__(self, Kp, Ki, Kd=0.0, Ts=1e-3, N=10.0, b=1.0, umin=-1.0, umax=1.0):
self.Kp, self.Ki, self.Kd, self.Ts, self.b = Kp, Ki, Kd, Ts, b
self.Tf = Kd / (Kp * N) if Kd > 0 else 0.0
self.umin, self.umax = umin, umax
self.I = 0.0
self.D = 0.0
self.y_prev = None
def update(self, r, y):
if self.y_prev is None: # first call: no derivative kick from y_prev = 0
self.y_prev = y
P = self.Kp * (self.b * r - y)
if self.Kd > 0:
self.D = (self.Tf * self.D - self.Kd * (y - self.y_prev)) / (self.Tf + self.Ts)
self.y_prev = y
v = P + self.I + self.D
u = min(max(v, self.umin), self.umax)
e = r - y
if not ((v > self.umax and e > 0) or (v < self.umin and e < 0)):
self.I += self.Ki * self.Ts * e # forward Euler, only when not winding up
return uOn a microcontroller the same structure goes into the timer interrupt: read the encoder count, compute the speed, call update, write the PWM compare register. Keep the period fixed (a hardware timer, not a delay() in the main loop) and do the floating-point or fixed-point work in a bounded time.
Worked example: a 1 kHz speed controller for the course motor
Given: the reference motor (, , , , ), supply through an H-bridge, the PI of the Bode lesson (, ), , the new voltage applied one sample after the measurement.
Find: the response to a speed step from to , with and without anti-windup, and the dip after a load torque of at .
Solve: the step asks for at the first sample: the bridge saturates at for a few milliseconds. In steady state at the motor needs ; the load adds . The motor is simulated with the exact ZOH discretisation of its two-state model (current and speed), so between samples it is the real continuous motor:
import numpy as np
from scipy.linalg import expm
class PID:
def __init__(self, Kp, Ki, Ts, umin, umax, antiwindup=True):
self.Kp, self.Ki, self.Ts, self.umin, self.umax, self.aw = Kp, Ki, Ts, umin, umax, antiwindup
self.I = 0.0
def update(self, r, y):
e = r - y
v = self.Kp * e + self.I
u = min(max(v, self.umin), self.umax)
if not self.aw or not ((v > self.umax and e > 0) or (v < self.umin and e < 0)):
self.I += self.Ki * self.Ts * e
return u
Ra, La, k, J, b = 2.0, 1e-3, 0.02, 2e-6, 1e-6
A = np.array([[-Ra / La, -k / La], [k / J, -b / J]]) # x = [current, speed]
B = np.array([[1 / La, 0.0], [0.0, -1 / J]]) # inputs = [voltage, load torque]
Ts = 1e-3
M = expm(np.block([[A, B], [np.zeros((2, 4))]]) * Ts) # exact ZOH discretisation
Ad, Bd = M[:2, :2], M[:2, 2:]
def run(antiwindup):
pid = PID(0.05754, 6.105, Ts, -12.0, 12.0, antiwindup)
x = np.zeros(2)
u_next = 0.0
log = []
for n in range(300):
t = n * Ts
speed = x[1]
load = 5e-3 if t >= 0.15 else 0.0
u_now = u_next # the voltage computed last sample is applied now
u_next = pid.update(300.0, speed)
x = Ad @ x + Bd @ np.array([u_now, load])
log.append((t, speed, u_now, x[0]))
return np.array(log)
for aw in (False, True):
L = run(aw)
t, w, u, i = L.T
first = t[np.argmax(w >= 0.98 * 300)]
before = w[(t > 0.10) & (t < 0.15)]
after = w[t >= 0.15]
print(f"anti-windup {aw!s:5s}: 98 % at {1e3 * first:5.1f} ms, peak {w[t < 0.15].max():6.1f} rad/s, "
f"saturated {np.sum(abs(u) >= 12)} samples, speed at 0.149 s {before[-1]:6.1f} rad/s, "
f"V = {u[t < 0.15][-1]:.2f} V")
print(f"{'':18s} load step: dip to {after.min():6.1f} rad/s, back to {after[-1]:6.1f} rad/s at 0.299 s, "
f"V = {u[-1]:.2f} V, current {i[-1]:.3f} A")anti-windup False: 98 % at 8.0 ms, peak 349.8 rad/s, saturated 7 samples, speed at 0.149 s 300.0 rad/s, V = 6.03 V
load step: dip to 292.8 rad/s, back to 300.0 rad/s at 0.299 s, V = 6.53 V, current 0.265 A
anti-windup True : 98 % at 29.0 ms, peak 300.0 rad/s, saturated 4 samples, speed at 0.149 s 300.0 rad/s, V = 6.03 V
load step: dip to 292.8 rad/s, back to 300.0 rad/s at 0.299 s, V = 6.53 V, current 0.265 A
The first line of each pair is the setpoint response, the second the load response. Without anti-windup the speed passes 98 % after only but overshoots to (17 %): during the seven saturated samples the integrator collected error the bridge could not act on. With clamping it takes and arrives without overshoot; which one you prefer depends on the application, but only the clamped loop behaves like its linear design for every step size. The load step is identical in both (the bridge does not saturate): a dip of , full recovery, the voltage up by and the current at , i.e. for the load plus for friction.
Lab: the continuous loop the code approximates
The PID lab is the continuous version of the same structure. Its default PID (, , ) settles in ; a digital version running at would be practically indistinguishable (the sample rate is about 200 times the closed-loop bandwidth of ), while at it would not.
Guided lab: microcontroller speed control (roadmap project)
Hand calculation. Measure (ohmmeter on the stalled motor, several shaft positions), (spin the motor with another motor or by hand-drill at a known speed and measure the open-circuit voltage, or run it unloaded and use minus the drop), and the mechanical time constant from a voltage step. Design the PI with the Bode lesson's method for a crossover a decade below your sample rate.
Simulation. Put your constants into the program; check the saturation time and overshoot for the steps you will test.
What you would measure. A small brushed motor (a 6–12 V hobby motor) on a current-limited bench supply, an H-bridge module, an encoder (or a slotted disc and an optical sensor), and a microcontroller board on USB. Timer interrupt at ; speed from the encoder count difference (or the period between edges at low speed); PWM at . Stream over the serial port and plot it. Steps of and : expect the measured rise time and overshoot within about 20 % of the simulation, a steady speed ripple of a few counts per sample (quantisation), and a visible improvement in overshoot for large steps when clamping is enabled.
Hazards and safe setup. Supply at most with the current limit at about (the stall current of a small motor can be several amperes), the motor clamped, nothing on the shaft that can fly off, the bridge's enable on a switch, and a firmware speed limit. Power the microcontroller from USB and share only the ground with the bridge.
Pitfalls
- A variable sample period (a delay loop instead of a timer): the integral and derivative are scaled by the wrong .
- A derivative kick at start-up from
y_prev = 0: initialise it with the first measurement. - Integer overflow or lost precision in the integrator in fixed-point code: the increment can be smaller than one LSB at small errors; keep the integrator in more bits than the output.
- Speed from encoder differences at low speed: one count per sample is a large quantisation step; use edge timing or a longer window.
Practice
- Write the difference equation of a PI in velocity form (no D).
- A loop runs at with and the integrator is a 16-bit integer scaled so 1 LSB is . What is the smallest error (in the measurement's unit) that still changes the integrator per sample?
- Why is backward Euler preferred for the derivative filter?
Answer
- .
- : units; smaller errors are lost unless the integrator keeps extra fractional bits.
- It is stable for every , also when ; forward Euler becomes unstable for .
Test yourself
Which discretisation keeps a derivative filter stable for any and ?
- forward Euler
- backward Euler
- no discretisation
- a zero-order hold on the derivative
In the velocity (incremental) form of PID, windup protection is
- impossible
- clamping the output to the actuator range
- an extra integrator
- back-calculation with
Why initialise y_prev with the first measurement?
- to save memory
- to avoid a derivative kick at the first sample
- to remove the steady-state error
- for anti-windup
At 300 rad/s, the course motor needs about how much voltage in steady state?
- 0.5 V
- 6 V
- 12 V
- 17 V