ENع
←Digital PID loop
Lesson 50 · State space and digital control

Writing a digital PID loop

15 min10 steps5 questionsAdvanced
About this lesson

Take the PID controller from "The PID controller" and run it on a computer. A timer starts a pass every T seconds: read the cart position through an ADC, turn the integral into a running sum and the derivative into a difference, write the force through a DAC that holds it until the next tick. Then watch the same code at 10, 50 and 80 ms ticks.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 50 · Interactive
01 / 10

PID on a timer

In "The PID controller" a cart was pushed by u = Kp·e + Ki·∫e dt − Kd·dy/dt. A computer cannot do calculus all the time. It runs a loop: every T seconds read the sensor, work out u, write it, wait.

the cart     y'' + 10 y' + 20 y = u
command      r = 1 m (a step)
gains        Kp = 300, Ki = 200, Kd = 20

the loop, once every T seconds:
  read  y      (sensor → ADC → number)
  compute u    (a few lines of Python)
  write u      (number → DAC → force)
  wait         for the next tick

We take T = 10 ms: 100 passes a second.
Loading figure…
or ← →
Read the lesson step by step
  1. PID on a timer

    In "The PID controller" a cart was pushed by u = Kp·e + Ki·∫e dt − Kd·dy/dt. A computer cannot do calculus all the time. It runs a loop: every T seconds read the sensor, work out u, write it, wait.

    the cart     y'' + 10 y' + 20 y = u
    command      r = 1 m (a step)
    gains        Kp = 300, Ki = 200, Kd = 20
    
    the loop, once every T seconds:
      read  y      (sensor → ADC → number)
      compute u    (a few lines of Python)
      write u      (number → DAC → force)
      wait         for the next tick
    
    We take T = 10 ms: 100 passes a second.
  2. Read: one sample per tick

    The ADC (analog-to-digital converter) turns the cart position into a number, but only at the ticks t = kT. That number is the sample y[k]. At tick k = 5, t = 50 ms, it reads y[5] = 0.2733 m.

    tick k    0    1    2    3    4    5
    t (ms)    0   10   20   30   40   50
    
    y[k] = y(k·T), the position at tick k
    y[5] = 0.2733 m
    
    Between two ticks the computer sees
    nothing. Whatever the cart does in
    those 10 ms, the code only learns at
    the next tick.
  3. P: same as before

    The error and the proportional part need no change: use the sample in place of y(t). e[5] = 1 − 0.2733 = 0.7267 m, so P = 300 × 0.7267 = 218.0 N.

    e[k] = r - y[k]
         = 1 - 0.2733
         = 0.7267 m
    
    P[k] = Kp * e[k]
         = 300 * 0.7267
         = 218.0 N
    
    No calculus here, so nothing to
    approximate.
  4. I: the integral becomes a sum

    ∫e dt is the area under the error. Each tick adds one thin rectangle, height e[k], width T: the Euler rule from "Discretising a controller: Euler versus Tustin". I goes from 9.2 to 10.7 N.

    I[k] = I[k-1] + Ki * T * e[k]
         = 9.2 + 200 * 0.01 * 0.7267
         = 9.2 + 1.5
         = 10.7 N
    
    One rectangle per tick:
      height  e[k]
      width   T = 0.01 s
    
    I is remembered from one pass to the
    next: it is the loop's memory.
  5. D: the slope becomes a difference

    dy/dt becomes (y[k] − y[k−1]) / T, so the code keeps the last sample. A light low-pass filter tames sensor noise, giving D = a·D − b·(y − y_old). Here D = −149.1 N: it brakes the moving cart.

    a = Tf/(Tf+T) = 0.400    b = Kd/(Tf+T) = 1200.0
       (Tf = Kd/Kp/10 = 1/150 s)
    
    D[k] = a*D[k-1] - b*(y[k] - y[k-1])
         = 0.400*(-128.2) - 1200.0*(0.2733 - 0.1918)
         = (-51.3) - 97.8
         = -149.1 N
    
    Derivative on the measurement, not the
    error, as in "The PID controller": a
    jump in r gives no kick.
  6. Write u, then hold it

    u = P + I + D = 79.6 N goes to the DAC (digital-to-analog converter). It holds that force steady until the next tick: a zero-order hold. So the force is a staircase, one stair per tick.

    u[5] = P + I + D
         = 218.0 + 10.7 + (-149.1)
         = 79.6 N
    
    zero-order hold:
      u(t) = u[k]  for  kT <= t < (k+1)T
    
    A value made at kT acts over the whole
    tick, so on average it is half a tick
    (T/2) late.
  7. Wait for the next tick

    Every formula assumed the ticks are exactly T apart. So wait for a fixed deadline, not for sleep(T) after the work: then the time the code itself takes does not stretch the period.

    import time
    T = 0.010
    deadline = time.monotonic()
    for k in range(5):
        # read y, compute u, write u ...
        deadline += T          # fixed grid
        time.sleep(max(0.0, deadline - time.monotonic()))
    
    # sleep(T) after the work would make
    # each pass T + (time spent working).
  8. Fast ticks: as good as analog

    With T = 10 ms the sampled loop follows the analog controller closely. On a 1 m move the two positions never differ by more than 5.4 cm, and neither overshoots (0.0 % and 0.0 %).

    Kp, Ki, Kd, T = 300, 200, 20, 0.010
    Tf = Kd / Kp / 10
    a, b = Tf / (Tf + T), Kd / (Tf + T)
    y = v = I = D = y_old = peak = 0.0
    h = 1e-5
    for k in range(round(2 / T)):
        e = 1.0 - y
        I = I + Ki * T * e
        D = a * D - b * (y - y_old)
        u = Kp * e + I + D; y_old = y
        for _ in range(round(T / h)):   # u held
            v += h * (u - 10 * v - 20 * y)
            y += h * v; peak = max(peak, y)
    print(round(max(0.0, peak - 1) * 100, 1))   # 0.0
  9. Slower ticks cost damping

    Same gains, T = 50 ms. Each force is held five times longer, so on average it acts later. The loop loses damping and the cart overshoots 12.9 %. Look at the coarse stairs.

    Kp, Ki, Kd, T = 300, 200, 20, 0.050
    Tf = Kd / Kp / 10
    a, b = Tf / (Tf + T), Kd / (Tf + T)
    y = v = I = D = y_old = peak = 0.0
    h = 1e-5
    for k in range(round(2 / T)):
        e = 1.0 - y
        I = I + Ki * T * e
        D = a * D - b * (y - y_old)
        u = Kp * e + I + D; y_old = y
        for _ in range(round(T / h)):   # u held
            v += h * (u - 10 * v - 20 * y)
            y += h * v; peak = max(peak, y)
    print(round(max(0.0, peak - 1) * 100, 1))   # 12.9
  10. Too slow: it shakes apart

    At T = 80 ms the same code makes the swing grow: about 2.0 m off target in the second second, 37 m by the sixth. Sampling too slowly can make a stable design unstable. Pick T small against the loop's speed.

    T        overshoot
    10 ms    0.0 %
    50 ms    12.9 %
    80 ms    grows without limit
    analog   0.0 %
    
    largest |y - 1|
      1 s to 2 s   2.0 m
      5 s to 6 s   37 m
    
    Same gains and same code in every row:
    only T changed.

Quiz Unlocks after the last step.