Skip to main content

Algorithm/pseudo-code for software PID

Short answer

The PID algorithm samples error at fixed period T, computes proportional, integral, and derivative terms discretely: P=Kp·e, I=I+Ki·T·e (clamped for anti-windup), D=Kd·(e-prev_e)/T. Output u=P+I+D is clamped to actuator limits and written to DAC/PWM. T must be much smaller than plant time constant for stability.

Write an algorithm (pseudo-code) to implement the PID controller in software.

A software PID samples the output at a fixed period T, computes the error, and updates the integral and derivative terms in discrete form. The routine is called from a timer interrupt every T seconds.

Discrete equations

e[k] = r - y[k]

I[k] = I[k-1] + Ki·T·e[k]

D[k] = Kd·(e[k] - e[k-1]) / T

u[k] = Kp·e[k] + I[k] + D[k]

Algorithm

  1. Initialise Kp, Ki, Kd, sampling period T, I = 0, prev_error = 0, output limits u_min, u_max.
  2. Wait for the timer tick (every T).
  3. Read the sensor (ADC) and get y.
  4. Compute error e = r - y.
  5. Compute P = Kp·e.
  6. Update I = I + Ki·T·e; clamp I between limits (anti-wind-up).
  7. Compute D = Kd·(e - prev_error)/T.
  8. Compute u = P + I + D; clamp u to [u_min, u_max].
  9. Write u to the actuator (DAC / PWM).
  10. Save prev_error = e and go to step 2.

Pseudo-code

init: I = 0; prev_e = 0
every T seconds (timer ISR):
    y = ReadSensor()
    e = r - y
    P = Kp * e
    I = I + Ki * T * e
    if I > Imax then I = Imax
    if I < Imin then I = Imin
    D = Kd * (e - prev_e) / T
    u = P + I + D
    if u > Umax then u = Umax
    if u < Umin then u = Umin
    WriteActuator(u)
    prev_e = e

The choice of T matters: it should be much shorter than the plant's time constant; otherwise control is poor and the loop may become unstable.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 7 questions →