Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Digital Control

Digital PID Implementation

Implement a PID controller as a difference equation: rectangular and Tustin integrals, positional versus velocity form, filtered derivative, and the effect of sample time.

A PID controller on a microcontroller is a few lines inside a timer interrupt. Those few lines hide several choices: how to approximate the integral, whether to compute the output or its increment, how to filter the derivative, and how fast to run. The wrong choices produce loops that work on the bench and fail in the field. This lesson turns the continuous PID C(s) = Kp + Ki/s + Kdยทs into code you can trust, building on the practical PID lesson and the discretization methods.

The discrete terms

With sample time T, error e[k] and measurement y[k]:

  • Proportional: P[k] = Kpยทe[k].
  • Integral: I[k] = I[k-1] + KiยทTยทe[k] (backward rectangle). The trapezoid (Tustin) version uses (e[k] + e[k-1])/2; it is slightly more accurate but rarely matters at sensible T. Forward rectangle (e[k-1]) adds a one-sample delay and is slightly worse for stability.
  • Derivative (filtered, on measurement): D[k] = Tf/(Tf+T)ยทD[k-1] - Kd/(Tf+T)ยท(y[k] - y[k-1]) with Tf = Td/N. This is the backward-Euler discretization of Kdยทs/(1 + Tfยทs), stable for any T, and with a bounded high-frequency gain of Kd/(Tf+T) per sample.
  • Output: u[k] = P[k] + I[k] + D[k], then clamp and apply anti-windup.

The skeleton, in pseudo-code:

TEXT
every T seconds (from a timer interrupt, not from a loop with delay()):
    y = read_adc()
    e = r - y
    I += Ki*T*e
    D  = a*D - b*(y - y_prev)            # a = Tf/(Tf+T), b = Kd/(Tf+T)
    u_raw = Kp*e + I + D
    u = clamp(u_raw, u_min, u_max)
    I += Kt*T*(u - u_raw)                # back-calculation anti-windup
    write_dac(u)
    y_prev = y

Positional versus velocity form

The code above is the positional (or absolute) form: it holds the integrator state I and computes the full output. The velocity (incremental) form computes the change in output and adds it to the previous output:

TEXT
ฮ”u[k] = Kpยท(e[k] - e[k-1]) + KiยทTยทe[k] + (Kd/T)ยท(e[k] - 2e[k-1] + e[k-2])
u[k]  = u[k-1] + ฮ”u[k]

Because the integral is implicit in the accumulation u[k-1] + ฮ”u, the velocity form has several practical benefits:

  • No separate integrator to wind up: saturating u[k] automatically limits windup (clamping happens on the accumulated output).
  • Bumpless transfer is easy: initialize u[k-1] to the manual output.
  • Useful when the actuator is an integrator itself (a stepper motor or a valve motor that takes increments).

Both forms are mathematically identical when the same discretization is used; the next experiment proves it on a random error sequence.

Python Positional and velocity forms give the same output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two sequences match exactly because both start from zero initial conditions and use the same rectangular integral and difference-based derivative. In a real implementation the equality holds as long as the controller is not saturated, and the forms differ precisely in how they behave at the limits.

The effect of the sample time

How slow can you sample before the PID falls apart? The experiment below simulates the plant 1/(s+1)ยณ finely (so the plant is effectively continuous) while the controller runs every T seconds with a zero-order hold on its output. It reports the overshoot and how large the oscillation still is during the last 5 seconds.

Python Digital PID on a continuous plant, for several T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The loop behaves almost like the continuous design (overshoot near 22%) for T = 0.01 to 0.1, then overshoot grows as T approaches the plant's time constants. Around T = 1 the loop still settles but with 55% overshoot, and at T = 1.5 the oscillation grows to several times the setpoint (it is unstable). The plant's dominant time constant is 1 s, so the rule of thumb (sample at least 10 times faster than the closed-loop dynamics, so T โ‰ค 0.1) keeps you in the safe zone.

Practical details

  • Fixed period. Use a hardware timer interrupt. Computing dt from a jittery software loop injects noise into the derivative and the integral. If the period must vary, scale the terms with the measured dt.
  • Order of operations. Read the sensor, compute, then write the actuator. The delay between reading and writing is a pure dead time that reduces phase margin, so keep it short and constant.
  • Word length. On fixed-point hardware, the integral accumulator needs more bits than the output: with small KiยทT the increments can round to zero (an "integrator stall"). Use 32 bits for I, or scale gains.
  • Gain scheduling. If the plant gain changes with the operating point, change Kp, Ki, Kd by table lookup, and keep the integrator bumpless when the gains change (adjust I so u does not jump).
  • Setpoint changes. Apply the setpoint through a ramp or a first-order prefilter, or use setpoint weighting, to avoid shocking the actuator.
  • Testing. Simulate with the same code that you flash (code reuse) and unit-test the saturated cases.

Many embedded libraries (Arduino PID, ROS controllers, PLC function blocks) implement exactly the structure shown above. Reading their source is a good way to check that you understand the options: derivative on measurement, back-calculation, output clamp, and "tracking" for bumpless transfer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the velocity (incremental) form of a digital PID, what is computed each sample?

    The velocity form computes Delta u from the last three errors and accumulates it into u.
  2. 2. Why is a hardware timer interrupt preferred over a delay() loop for the control period?

    Jitter in dt corrupts the integral and derivative terms; a timer gives a constant T.
  3. 3. The filtered derivative D[k] = Tf/(Tf+T) D[k-1] - Kd/(Tf+T)(y[k] - y[k-1]) is the discretization of Kd s/(1 + Tf s) by which method?

    Replacing s by (1 - z^-1)/T in Kd s/(1 + Tf s) gives exactly that recursion; it is stable for any T.
  4. 4. What happens as the sample time grows toward the plant's dominant time constant?

    The hold and the delayed reaction erode the phase margin, so overshoot and ringing grow, then the loop goes unstable.

Summary

  • Digital PID: backward-rectangle integral, filtered derivative on measurement, clamp and back-calculate.
  • Positional and velocity forms are equivalent; velocity form is convenient for incremental actuators and bumpless transfer.
  • Use a fixed sample period from a timer; keep input-to-output latency short and constant.
  • Sample at least about 10 times faster than the closed-loop dynamics; slow sampling rings and then diverges.
  • Mind word length, gain scheduling and setpoint handling in real hardware.

Next: Project: Cruise Control