TExcelTAD
Home › Control Systems & Automation › Discrete PID: From Equations to Code

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 TsT_s are in Sampled-Data Loops.

Discretising each term

With sample period TsT_s and ek=rk−yke_k = r_k - y_k:

Term Continuous Discrete (common choice)
P Kp(b r−y)K_p(b\,r - y) Pk=Kp(b rk−yk)P_k = K_p(b\,r_k - y_k)
I Ki∫e dtK_i\int e\,dt forward Euler Ik+1=Ik+KiTsekI_{k+1} = I_k + K_i T_s e_k (or Tustin: Ik+1=Ik+KiTs2(ek+ek+1)I_{k+1} = I_k + K_i\frac{T_s}{2}(e_k + e_{k+1}))
D (filtered, on −y-y) −Kds1+sTf y\frac{-K_d s}{1 + sT_f}\,y backward Euler Dk=TfTf+TsDk−1−KdTf+Ts(yk−yk−1)D_k = \frac{T_f}{T_f + T_s}D_{k-1} - \frac{K_d}{T_f + T_s}(y_k - y_{k-1})

Backward Euler is used for the derivative filter because it is stable for any TfT_f, even Tf<TsT_f < T_s; forward Euler there would be unstable when Tf<Ts/2T_f < T_s/2. 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 uku_k itself. The velocity (incremental) form computes the change Δuk=uk−uk−1\Delta u_k = u_k - u_{k-1}:

Δuk=Kp (ek−ek−1)+KiTs ek+KdTs (ek−2ek−1+ek−2)(unfiltered D)\Delta u_k = K_p\,(e_k - e_{k-1}) + K_i T_s\,e_k + \frac{K_d}{T_s}\,(e_k - 2e_{k-1} + e_{k-2}) \qquad \text{(unfiltered D)}

It has no explicit integrator: windup protection is simply clamping uku_k, and bumpless transfer is automatic. It is common in PLCs and for actuators that integrate themselves (stepper positions, motorised valves).

The controller code

python
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 u

On 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 (Ra=2 ΩR_a = 2\ \Omega, La=1 mHL_a = 1\ \text{mH}, k=0.02 V⋅s/radk = 0.02\ \text{V} \cdot \text{s/rad}, J=2×10−6 kg⋅m2J = 2 \times 10^{-6}\ \text{kg} \cdot \text{m}^2, b=1×10−6 N⋅m⋅sb = 1 \times 10^{-6}\ \text{N} \cdot \text{m} \cdot \text{s}), supply ±12 V\pm 12\ \text{V} through an H-bridge, the PI of the Bode lesson (Kp=0.0575 V/(rad/s)K_p = 0.0575\ \text{V/(rad/s)}, Ki=6.105 V/radK_i = 6.105\ \text{V/rad}), Ts=1 msT_s = 1\ \text{ms}, the new voltage applied one sample after the measurement.

Find: the response to a speed step from 00 to 300 rad/s300\ \text{rad/s}, with and without anti-windup, and the dip after a load torque of 5 mN⋅m5\ \text{mN} \cdot \text{m} at t=0.15 st = 0.15\ \text{s}.

Solve: the step asks for Kp×300=17 VK_p \times 300 = 17\ \text{V} at the first sample: the bridge saturates at 12 V12\ \text{V} for a few milliseconds. In steady state at 300 rad/s300\ \text{rad/s} the motor needs V=(Rab+k2) ωk=6.03 VV = \frac{(R_a b + k^2)\,\omega}{k} = 6.03\ \text{V}; the load adds Raτ/k=0.5 VR_a\tau/k = 0.5\ \text{V}. 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:

python · try it yourself
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 8 ms8\ \text{ms} but overshoots to 349.8 rad/s349.8\ \text{rad/s} (17 %): during the seven saturated samples the integrator collected error the bridge could not act on. With clamping it takes 29 ms29\ \text{ms} 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 7.2 rad/s7.2\ \text{rad/s}, full recovery, the voltage up by 0.50 V0.50\ \text{V} and the current at 0.265 A0.265\ \text{A}, i.e. τ/k=0.25 A\tau/k = 0.25\ \text{A} for the load plus bω/k=0.015 Ab\omega/k = 0.015\ \text{A} for friction.

Lab: the continuous loop the code approximates

The PID lab is the continuous version of the same structure. Its default PID (Kp=3K_p = 3, Ki=2K_i = 2, Kd=0.1K_d = 0.1) settles in 3.458 s3.458\ \text{s}; a digital version running at Ts=10 msT_s = 10\ \text{ms} would be practically indistinguishable (the 100 Hz100\ \text{Hz} sample rate is about 200 times the closed-loop bandwidth of 0.48 Hz0.48\ \text{Hz}), while at Ts=0.5 sT_s = 0.5\ \text{s} it would not.

r = 1+C(s): Kp 3, Ki 2, Kd 0.1P(s) = 1/((1s+1)(0.5s+1))y-T(s) = (0.100 s^2 + 3.000 s + 2.000) / (0.500 s^3 + 1.600 s^2 + 4.000 s + 2.000)closed-loop poles: -0.63, -1.29+j2.18, -1.29-j2.180.00.51.001 s2 s3 s4 s5 sty(t)t_s 3.46 s+10.0 %y(t)setpoint10-90 % rise

Guided lab: microcontroller speed control (roadmap project)

Hand calculation. Measure RaR_a (ohmmeter on the stalled motor, several shaft positions), kk (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 k≈V/ωk \approx V/\omega minus the RaIR_a I 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 1 kHz1\ \text{kHz}; speed from the encoder count difference (or the period between edges at low speed); PWM at 20 kHz20\ \text{kHz}. Stream (t,r,ω,u)(t, r, \omega, u) over the serial port and plot it. Steps of 100100 and 300 rad/s300\ \text{rad/s}: 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 12 V12\ \text{V} with the current limit at about 1 A1\ \text{A} (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 TsT_s.
  • 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 KiTseK_i T_s e 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

  1. Write the difference equation of a PI in velocity form (no D).
  2. A loop runs at Ts=2 msT_s = 2\ \text{ms} with Ki=50K_i = 50 and the integrator is a 16-bit integer scaled so 1 LSB is 1 mV1\ \text{mV}. What is the smallest error (in the measurement's unit) that still changes the integrator per sample?
  3. Why is backward Euler preferred for the derivative filter?
Answer
  1. uk=uk−1+Kp(ek−ek−1)+KiTseku_k = u_{k-1} + K_p(e_k - e_{k-1}) + K_i T_s e_k.
  2. KiTse≥0.001 VK_i T_s e \ge 0.001\ \text{V}: e≥0.001/(50×0.002)=0.01e \ge 0.001/(50 \times 0.002) = 0.01 units; smaller errors are lost unless the integrator keeps extra fractional bits.
  3. It is stable for every TfT_f, also when Tf<TsT_f < T_s; forward Euler becomes unstable for Tf<Ts/2T_f < T_s/2.

Test yourself

Which discretisation keeps a derivative filter stable for any TfT_f and TsT_s?

  1. forward Euler
  2. backward Euler
  3. no discretisation
  4. a zero-order hold on the derivative

In the velocity (incremental) form of PID, windup protection is

  1. impossible
  2. clamping the output uku_k to the actuator range
  3. an extra integrator
  4. back-calculation with Tt=0T_t = 0

Why initialise y_prev with the first measurement?

  1. to save memory
  2. to avoid a derivative kick at the first sample
  3. to remove the steady-state error
  4. for anti-windup

At 300 rad/s, the course motor needs about how much voltage in steady state?

  1. 0.5 V
  2. 6 V
  3. 12 V
  4. 17 V