You’ve closed the loop: you measure the error (target − current) and turn it into a command. The question is how. PID is a three-part answer that has run most of the world’s thermostats, cruise controls and drone stabilisers for decades.
command = Kp·error + Ki·∫error dt + Kd·d(error)/dt
└ now └ the past └ the future (trend)
Play first (widget at the top of this page)
The live widget above the lesson simulates a 1 kg cart on a track with a little friction. The target is 1 m. Drag the sliders and watch the response. Then read what each term did.
What each term is for
- P (proportional) — push harder the further you are. Too low: sluggish. Too high: it overshoots and oscillates, because by the time it arrives it’s moving too fast to stop.
- D (derivative) — push against the speed of approach. It’s the brake that damps the overshoot P caused. Too much D amplifies sensor noise (not modelled here, but it’s the reason real controllers filter it).
- I (integral) — accumulate error over time. Switch on Push at t = 3 s and set I to 0: the cart is shoved and never quite returns — P alone settles with a steady offset when something pushes back. A little I removes that offset by refusing to be satisfied while any error remains. Too much I causes slow, rolling oscillation (“integral windup”).
A tuning recipe that actually works
- Set I and D to 0. Raise P until the response is quick but starts to overshoot.
- Add D until the overshoot is tamed.
- Add the smallest I that clears the steady offset.
Real tuners (Ziegler–Nichols, auto-tune) are fancier versions of the same recipe.
Try it on a robot
In the simulator, open </> Code and write a heading controller: error = angle to goal − current yaw, command = Kp * error, applied as a difference between left and right wheel speeds. Notice the tuning story is identical.
Takeaways
- P reacts to now, D to the trend, I to accumulated history.
- Tune in order P → D → I, and change one thing at a time.
- Saturation matters: real motors max out, so the widget clamps the command to ±10 N.