Try Embedded

PID control

Feedback loops, the three terms, anti-windup and tuning.

Closing the loop

Many embedded products exist to hold something at a target: a motor's speed, an oven's temperature, a drone's attitude, a power supply's voltage, a battery's charge current. They do it with a feedback control loop: measure, compare with the target, adjust the actuator, repeat. The PID controller is the workhorse used in the large majority of industrial loops, and implementing one well (with the details below) is a classic embedded interview topic.

setpoint --> (+) --error--> [ controller ] --output--> [ actuator + plant ] --+--> measurement
              ^ (−)                                                            |
              +-------------------------- sensor <----------------------------+

The three terms

error = setpoint − measurement

TermOutput proportional toEffectToo much
P (proportional)The current errorPushes towards the target; bigger error, bigger pushOscillation; alone, it usually leaves a steady-state error
I (integral)The accumulated error over timeRemoves steady-state error (keeps pushing while any error remains)Overshoot, slow oscillation, windup
D (derivative)The rate of change of the errorDamps: brakes as the target approachesAmplifies sensor noise
output = Kp·e + Ki·∑e·dt + Kd·(de/dt)

A practical discrete PID

A textbook PID needs four refinements to work on real hardware:

  1. Fixed sample time: run it from a timer at a constant rate, and include dt in the I and D terms.
  2. Anti-windup: when the output saturates (the heater is already at 100%), stop accumulating the integral, or it grows huge and causes a long overshoot after the error reverses.
  3. Derivative on measurement, not error: a setpoint step otherwise causes a large output spike ("derivative kick").
  4. Filtered derivative: low-pass the D term, or it amplifies sensor noise.
#include <stdio.h>

typedef struct {
  double kp, ki, kd, dt;
  double out_min, out_max;
  double integral, last_measurement;
} pid_t;

static double pid_update(pid_t *c, double setpoint, double measurement) {
  double error = setpoint - measurement;
  double p = c->kp * error;
  double d = -c->kd * (measurement - c->last_measurement) / c->dt;   /* derivative on measurement */
  c->last_measurement = measurement;

  double candidate = c->integral + c->ki * error * c->dt;
  double out = p + candidate + d;
  /* Anti-windup: clamp the output, and only keep the new integral if it does not push further into saturation. */
  if (out > c->out_max) { out = c->out_max; if (error < 0) c->integral = candidate; }
  else if (out < c->out_min) { out = c->out_min; if (error > 0) c->integral = candidate; }
  else c->integral = candidate;
  return out;
}

int main(void) {
  /* A simple thermal plant: temperature rises with heater power and leaks to ambient (20 C). */
  pid_t c = { 4.0, 0.4, 2.0, 1.0, 0.0, 100.0, 0.0, 20.0 };
  double temp = 20.0;
  for (int t = 0; t <= 60; t++) {
    double power = pid_update(&c, 60.0, temp);
    temp += 0.02 * power - 0.01 * (temp - 20.0);         /* plant model, one second per step */
    if (t % 6 == 0) printf("t=%2ds  heater %5.1f%%  temp %5.1f C\n", t, power, temp);
  }
  return 0;
}

Try setting ki to 0 to see the steady-state error that P alone leaves, or remove the anti-windup lines to see the overshoot grow.

Tuning

  1. Start with I and D at zero. Raise Kp until the response is fast with a little overshoot.
  2. Add Ki until steady-state error disappears in an acceptable time without too much overshoot.
  3. Add Kd if needed to reduce overshoot, keeping it small if the measurement is noisy.

Systematic methods: Ziegler-Nichols (find the gain at which the loop oscillates steadily, and its period, then use formulas; aggressive), step-response (process reaction curve) methods, model-based tuning, and relay auto-tuning built into many industrial controllers.

Implementation details that matter

  • Sample rate: typically 10 to 20 times faster than the loop's desired response (the closed-loop bandwidth). Run it from a timer interrupt or a high-priority RTOS task with low jitter.
  • Measurement delay and filtering add phase lag; heavy filtering makes loops unstable (see the DSP filters lesson).
  • Fixed point: on MCUs without an FPU, scale gains and states as integers (Q formats) and saturate; the fixed-point lesson includes a PI controller with anti-windup in integers.
  • Bumpless transfer: when switching from manual to automatic, initialise the integral so the output does not jump.
  • Cascaded loops: motor drives nest a fast current loop inside a speed loop inside a position loop; each inner loop must be several times faster than the one outside it.
  • Safety: limit output rate of change, detect a sensor failure (out-of-range reading) and go to a safe output rather than letting the controller chase a broken sensor.

Beyond PID

Feed-forward (adding the known required output, such as the torque to hold a load, so PID corrects only the remainder), gain scheduling (different gains at different operating points), state-space control (LQR) and model predictive control (MPC) appear in more demanding systems, but most loops in products are PI or PID.

Pitfall: Running the PID calculation in the main loop "as fast as possible" makes dt vary with everything else the code does, so the I and D terms change with load. Always run control loops at a fixed rate from a timer.

Interview question: Explain what each term of a PID controller does and what goes wrong if it is too large.

Answer: The proportional term responds to the present error, pushing harder the further away the measurement is; too large and the loop oscillates or becomes unstable, and on its own it usually leaves a steady-state error. The integral term accumulates past error so that any persistent error keeps increasing the output until it is removed; too large and the response overshoots and oscillates slowly, and without anti-windup it winds up during saturation. The derivative term responds to the rate of change, damping the approach; too large and it amplifies sensor noise into a jittery output.

Interview question: What details turn a textbook PID into one that works in a product?

Answer: A fixed sample period from a timer with dt in the I and D terms; anti-windup by clamping the integral or stopping integration when the output saturates; derivative computed on the measurement to avoid derivative kick, with a low-pass filter on it; output limits and rate limits; bumpless transfer when switching modes or changing gains; integer scaling and saturation in fixed point; and handling of sensor faults so the controller goes to a safe state rather than chasing a bad reading.

Build it: hold the camera's angle

This is step 3 of the module project, the camera gimbal. Each axis runs a PID loop at 1 kHz: the setpoint is the angle the camera should point at, the measurement comes from the fused sensors (step 5), and the output is the motor command. It runs in integers, as the motor processor has no FPU, and three situations decide whether the footage is usable: a setpoint the motor cannot reach yet, switching the loop on while the motor is already pushing, and a sensor reading that is garbage.

Lab: An integer PID with anti-windup, bumpless start and a sensor check

Angles are in hundredths of a degree, the output is a motor command from -OUT_MAX to OUT_MAX, and the gains are in Q8 (256 is 1.0). Do the sums in 64 bits.

pid_update(c, sp, meas):

  1. If meas is outside ±ANGLE_LIMIT, the sensor has failed: return 0 (motor off) and change nothing.
  2. err = sp − meas; p = kp × err; d = −kd × (meas − last), the derivative of the measurement, so a setpoint change gives no kick; cand = integ + ki × err, clamped to ±OUT_MAX × 256.
  3. out = (p + cand + d) / 256 (C division), clamped to ±OUT_MAX.
  4. Keep cand as the new integ, except when the output was clamped and err pushes the same way (clamped high with err > 0, or low with err < 0): then keep the old integ, so it does not wind up while the motor is already at its limit.
  5. last = meas; return out.

pid_start(c, sp, meas, current_out) prepares the loop to take over a motor that is already driven at current_out: last = meas, and integ set so that the P and I terms together give current_out (current_out × 256 − kp × err, clamped as above). The first output then continues from where the motor was, instead of jumping.

Going deeper

Interview question: How would you control a sous-vide cooker's water temperature without overshoot?

Answer: A PI (or PID) loop on the heater, tuned from the system's measured response, with anti-windup so a long warm-up does not overshoot, the heater driven by slow PWM or burst firing, and a feed-forward estimate of the power needed at the setpoint. Add a separate over-temperature cut-off that does not depend on the control loop.

Interview question: Why must an inner control loop run faster than the outer loop in a cascade?

Answer: The outer loop treats the inner loop as part of its plant and assumes it reaches each new setpoint quickly. If the inner loop is not several times (typically 5 to 10) faster, its dynamics interact with the outer loop's, adding lag that erodes the outer loop's stability margins and causes oscillation. So a motor drive runs current control at tens of kHz, speed at around 1 kHz and position slower still.

Interview question: What is feed-forward and why combine it with PID?

Answer: Feed-forward adds a predicted output computed from the setpoint or a measured disturbance, such as the voltage needed for a given speed or the torque to hold a known load, without waiting for an error to appear. PID feedback then only corrects what the model gets wrong. This gives a faster response to setpoint changes and disturbances with lower feedback gains, which improves stability and noise behaviour.

Explain it: In your own words, explain integral windup and how anti-windup prevents it.

Answer: When the actuator is saturated, for example a heater already at full power, the error remains large for a long time and the integral term keeps accumulating it, growing far beyond what is needed. When the measurement finally reaches the setpoint, that huge integral keeps the output high until an equally large negative error has wound it back down, causing a large overshoot. Anti-windup stops this by not letting the integral grow while the output is saturated in the direction that would make it worse, or by clamping it, so the controller responds promptly once the actuator comes out of saturation.