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).

Block diagram: the setpoint 1000 rpm minus the encoder speed gives the error e; pid_task, run every 10 ms, adds P, I and D and limits the sum to 0 to 100 percent; the PWM duty u drives the motor driver and the motor; the encoder reads the speed and feeds it back.
The loop: error in, duty out, every 10 ms. The motor's speed comes back through the encoder and closes the loop.

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 speedsteady-state errorpeak on the way
0.04545.5 rpm454.5 rpm581.6 rpm
0.08705.9 rpm294.1 rpm837.5 rpm
0.16827.6 rpm172.4 rpm1083.9 rpm
0.24878.0 rpm122.0 rpm1176.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).

Three speed responses to a step to 1000 rpm over 1 second: P only levels off at 705.9 rpm; PI peaks at 1189.0 rpm and settles at 1000; PID peaks at 1101.6 rpm and settles sooner.
P alone stops short; I removes the error but overshoots; D brakes the approach and settles sooner.
tuning (Kp, Ki, Kd)final errorovershootrise 10→90 %settling ±2 %
P: 0.08, 0, 0294.1 rpmnonenever reaches 90 %never
PI: 0.08, 0.6, 0018.9 %60 ms360 ms
PID: 0.08, 0.6, 0.001010.2 %70 ms240 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).

Two runs where the shaft is held for 0.3 s: without anti-windup the integral climbs to 180 percent and the speed peaks at 2287 rpm after release; with clamping the integral stays at 18 percent and the speed peaks at 1286 rpm.
Without anti-windup the integral stores 180 % while the shaft is held and the motor overshoots to 2287 rpm; clamping keeps it at 18 %.

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.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlI removes error; clamp stops windupOpen the Computer Architecture mind mapComputer Architecturesmall fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlI removes error; clamp stops windup
This page on the Computer Architecture mind map · 79 pages in 7 branches · open it to see the whole map and test yourself in recall mode.