Two more terms fix P control's weaknesses: one remembers the past, one looks at the trend.
Key idea
PID: $u = K_p e + K_i \sum e\,\Delta t + K_d \dfrac{e - e_{\text{prev}}}{\Delta t}$. The integral term adds up error over time and removes steady-state error. The derivative term reacts to how fast the error changes and damps overshoot.
- Each pass: measure, compute $e$.
- Integral: $I \leftarrow I + e\,\Delta t$.
- Derivative: $D = (e - e_{\text{prev}})/\Delta t$.
- Command: $u = K_p e + K_i I + K_d D$; clip it; send it.
- Save $e$ as $e_{\text{prev}}$.
Worked example: One step
$K_p = 2$, $K_i = 1$, $K_d = 0.1$, $\Delta t = 0.05$. Previous error 10, integral 3. Now $e = 8$.
- $I = 3 + 8 \times 0.05 = 3.4$.
- $D = (8 - 10)/0.05 = -40$.
- $u = 16 + 3.4 - 4 = 15.4$.
Answer: 15.4.
Why it works
The derivative term is negative here because the error is shrinking: it eases off before the cart overshoots. The integral term keeps pushing a little as long as any error is left.
Common mistake
Forgetting $\Delta t$, or letting the integral grow without bound while the motor is saturated (called windup). Real code limits the integral.