Feedback control and PID
What you’ll learn
- Why on/off (“bang-bang”) control wobbles
- P, I and D in plain words
- How to tune a controller step by step
Bang-bang control
The two-sensor line follower only knows “left”, “right” or “centre”, so it jerks between full turns: bang-bang control. It works, but it zig-zags and can’t go fast.
Error
Proportional control needs a number: the error, how far you are from where you want to be. In the simulator, linePosition() gives the line’s position under a 5-sensor bar, from −1 (far left) to 1 (far right), so the error is just that value (target = 0).
P: proportional
correction = Kp × error
Small error → small correction; big error → big correction. Too little Kp and the robot drifts off on curves; too much and it oscillates.
D: derivative
+ Kd × (error − lastError)
Reacts to how fast the error is changing, which damps the wobble, like a shock absorber.
I: integral
+ Ki × (sum of all errors)
Fixes a small error that stays for a long time (one motor slightly weaker). Line followers often don’t need it; balancing robots and heaters do.
Tuning recipe
- Set Ki = Kd = 0. Increase Kp until it follows well but starts to wobble.
- Add Kd until the wobble calms down.
- Only if it settles slightly off-target, add a little Ki.
- Change one number at a time and note what happens.
Example: P line follower (simulator)
const BASE = 50, KP = 40;
function loop() { const error = linePosition(); if (error === null) { motors(30, -30); return; } // lost: search const turn = KP * error; motors(BASE + turn, BASE - turn);}Line to the right (error > 0) → left wheel faster → robot turns right towards it.
Example: adding D
let last = 0;function loop() { const error = linePosition(); if (error === null) { motors(30, -30); return; } const turn = 40 * error + 120 * (error - last); last = error; motors(60 + turn, 60 - turn);}Example: P control with encoders (Arduino)
long error = leftCount - rightCount; // target: equal countsint correction = 3 * error; // Kp = 3setMotors(150 - correction, 150 + correction);Try it
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Too little, too muchEasy
Try KP = 10 and KP = 150. Describe what happens in each case. KP 10: turns too gently and runs off on the curves. KP 150: over-corrects and wobbles from side to side.
Go fasterMedium
Raise BASE to 80. Re-tune KP until it completes laps. Is it faster than the bang-bang follower?
Add DHard
Add a derivative term and find a Kd that lets it run at BASE = 90 without wobbling off. Start Kd around 2–4 times Kp and adjust.
Quick check
Finished this lesson?