The idea: a loop that corrects itself every 10 ms
A motor driven by a fixed PWM duty does not keep a fixed speed: the load, the supply voltage and the temperature all change it. A feedback loop fixes this. Every sample time T = 10 ms a small task reads the speed from the encoder, compares it with the wanted speed, the setpoint, and writes a new duty to the PWM. The difference is the error, e = setpoint − speed. A PID controller turns the error into a duty u with three terms: one for the error now (P), one for the error added up over time (I), and one for how fast the error changes (D).
On the canvas the speed and the duty are drawn one point per sample. The bars show the three terms of the current sample, and the C code on the right is what runs. Step Sample runs it once, line by line.
The motor on this page
The thing being controlled is called the plant. Here it is a small DC motor and its driver, written as two lags that move part of the way toward their target each sample:
x[k+1] = 0.8·x[k] + 0.2·u[k] // driver and current, τ ≈ 45 ms
ω[k+1] = 0.9·ω[k] + 0.1·30·x[k] // speed in rpm, τ ≈ 95 ms
In steady state ω = 30·u: each percent of duty gives 30 rpm, so 100 % gives 3000 rpm and 1000 rpm needs 33.3 %. A change in u reaches the speed only after a few samples, and that delay is what makes the loop able to overshoot.
P only: a steady-state error
The simplest controller is u = Kp·e. The bigger the error, the harder it pushes. But to hold any speed the motor needs some duty, and P only gives duty when there is an error. So the motor settles where the two agree: ω = 30·Kp·(1000 − ω), which gives ω = 1000 · 30·Kp / (1 + 30·Kp). With Kp = 0.08 %/rpm the motor stops at 705.9 rpm, 294.1 rpm short (Demo 1). This leftover is the steady-state error.
| Kp (%/rpm) | final speed | steady-state error | peak on the way |
|---|---|---|---|
| 0.04 | 545.5 rpm | 454.5 rpm | 581.6 rpm |
| 0.08 | 705.9 rpm | 294.1 rpm | 837.5 rpm |
| 0.16 | 827.6 rpm | 172.4 rpm | 1083.9 rpm |
| 0.24 | 878.0 rpm | 122.0 rpm | 1176.9 rpm |
A bigger Kp shrinks the error but never removes it, and the motor swings more on the way: at Kp = 0.24 it passes 1000 rpm and rings before it settles below it.
The I term removes the error
The integral term adds a little of the error every sample: integ += Ki·e·T. As long as any error is left, the integral keeps growing, so it can only stop when e = 0. Then the integral alone holds the 33.3 % the motor needs, and P is 0. With Ki = 0.6 the motor reaches exactly 1000 rpm (Demo 2). The price is overshoot: the integral is still large when the speed reaches the setpoint, so the speed goes past it, to 1189.0 rpm (18.9 %), and only comes back when the negative error has drained the integral.
The D term damps the swing
The derivative term looks at how fast the error changes: d = Kd·(e − prev_e)/T. While the speed rises quickly, the error falls quickly, so D is negative and brakes the motor before it gets there. With Kd = 0.001 the overshoot drops to 10.2 % and the speed settles within ±2 % after 240 ms instead of 360 ms (Demo 3).
| tuning (Kp, Ki, Kd) | final error | overshoot | rise 10→90 % | settling ±2 % |
|---|---|---|---|---|
| P: 0.08, 0, 0 | 294.1 rpm | none | never reaches 90 % | never |
| PI: 0.08, 0.6, 0 | 0 | 18.9 % | 60 ms | 360 ms |
| PID: 0.08, 0.6, 0.001 | 0 | 10.2 % | 70 ms | 240 ms |
More D is not always better. With Kd = 0.002 the overshoot falls to 6.7 %, but the approach is slower and settling takes 360 ms again; with Kd = 0.004 it takes 540 ms. Real encoders are noisy, and D turns noise into big duty jumps, so the D term is usually passed through a small low-pass filter first (see FIR and IIR filters).
The code, and why the period must be fixed
The controller is a few lines of C. DT is the sample time in seconds, and the integral and the D term both use it, so the task must really run every 10 ms. It is usually started by a timer interrupt or as a periodic task in a scheduler, as on Time-Triggered Scheduling. Jitter in the period makes the I and D terms wrong.
void pid_task(void) { // every 10 ms
float meas = encoder_rpm();
float e = sp - meas;
float p = KP * e;
float i = integ + KI * e * DT;
float d = KD * (e - prev_e) / DT;
float raw = p + i + d;
float u = clamp(raw, 0, 100);
int wind = (raw>100&&e>0)||(raw<0&&e<0);
if (!(CLAMP && wind)) integ = i;
prev_e = e; prev_m = meas;
pwm_set_duty(u);
}
The duty goes to a timer's compare register, as on ADC and PWM. The units of the gains follow from the code: Kp in % per rpm, Ki in % per rpm·s, Kd in %·s per rpm.
Integral wind-up and clamping
The PWM cannot give more than 100 %. When the output is stuck at that limit, the loop is open: more push changes nothing, but the integral does not know that and keeps growing. This is integral wind-up. On the page the shaft is held for 0.3 s while the loop runs (Demo 4). The error stays 1000 rpm, u is stuck at 100 %, and the integral climbs by 6 % every sample, to 180 % at the release. Then it must be drained by a negative error before the duty can drop, so the motor shoots to 2287 rpm, 128.7 % over, and settles only after 760 ms.
The fix is anti-windup. The simplest kind is clamping (conditional integration): on a sample where the output is past a limit and the error pushes further that way (wind = 1), keep the old integral. With clamping the integral stops at 18 % during the hold, and the peak after the release is only 1286 rpm, about what a normal start gives (Demo 5).
Derivative kick
D on the error has a side effect. When the setpoint jumps, the error jumps too, and (e − prev_e)/T is huge for one sample. In Demo 6 the setpoint steps from 1000 to 1200 rpm with Kd = 0.002: D = 0.002 × 200 / 0.01 = +40 % for one sample, and the duty jumps from 33.3 % to 90.5 %. That spike is the derivative kick. It is a current spike in the motor and a jolt in the gears, and it tells the loop nothing it did not already know.
The usual fix is to take D on the measurement: d = −Kd·(meas − prev_m)/T. While the setpoint is constant this is exactly the same, because e changes only when meas does. At a setpoint step it stays 0, so the duty goes only to 50.5 % (Demo 7). The setpoint is then followed by P and I alone, a little slower: overshoot 7.2 %, settling 370 ms.
Tuning by hand, and other views
A common hand-tuning order: raise Kp until the response is quick but rings, add Ki until the error goes away in an acceptable time, then add a little Kd to calm the overshoot, and check it again with the actuator at its limits. Rules like Ziegler–Nichols give a starting point from a measured step response. The same loop can be analysed in the z-domain, where the closed-loop poles must lie inside the unit circle (see Z-transform, poles and zeros). A PID reacts to a measured error; a Kalman filter is the tool for estimating the speed when the sensor is noisy, and the second-order ringing above is the same kind as in RLC circuits.
See also driving loads from an MCU pin for the transistor and flyback diode that let a PWM pin like this one run a motor or relay.
What the page leaves out
The encoder reading is exact; a real one counts pulses, so the speed comes in steps (for example 10 rpm per count in 10 ms) and D sees that as noise. There is no load torque, friction, supply change or noise, and the motor model is linear apart from the 0 … 100 % duty limit (no reverse drive, no current limit). The page uses floating point; many microcontrollers use fixed-point PID with scaled integers. Other anti-windup methods (back-calculation, the velocity form of PID), setpoint ramps and weighting, D-term filtering, bumpless transfer when gains change, cascaded current and speed loops, and auto-tuning are not shown.