DEV Community

I Want To Learn Programming
I Want To Learn Programming

Posted on • Originally published at iwtlp.com

PID control explained with a line-following robot

PID control runs an enormous share of the physical world: thermostats, cruise control, drones, 3D printers, and the steering of self-driving cars. It sounds technical, but a line-following robot makes every part of it intuitive. The robot's job is simple: stay on the line. PID is how it decides how hard to turn.

The setup

A line follower has a sensor that tells it how far off the line it is. Call that the error: zero means dead center, positive means it has drifted right, negative means left. PID turns that error into a steering command, using three terms.

P, the proportional term

The simplest idea: steer in proportion to how far off you are. Drifted far right, turn hard left; barely off, turn gently.

double correction = Kp * error;
Enter fullscreen mode Exit fullscreen mode

P alone often works, but it tends to overshoot and weave across the line, because it only reacts to the current error, not where things are heading.

D, the derivative term

The derivative looks at how fast the error is changing and damps the motion. If the robot is racing back toward the line, D eases off so it does not overshoot. It is the term that smooths the weaving.

double d = Kd * (error - prev_error);
prev_error = error;
Enter fullscreen mode Exit fullscreen mode

P says "how far off am I"; D says "how fast am I correcting," and together they give a smooth approach.

I, the integral term

The integral accumulates error over time, to fix a small, persistent offset that P never quite closes (for example, if the robot consistently rides slightly to one side). It builds up until the bias is corrected.

integral += error;
double i = Ki * integral;
Enter fullscreen mode Exit fullscreen mode

I is powerful but needs care, because the accumulator can grow too large (a problem called integral windup).

Putting it together

double steer = Kp * error
             + Ki * integral
             + Kd * (error - prev_error);
Enter fullscreen mode Exit fullscreen mode

That single line is PID. Tuning the three gains (Kp, Ki, Kd) is the art: too much P weaves, too little is sluggish, D smooths, I removes drift. A line-following robot lets you feel each gain's effect immediately, which is why it is the classic teaching example.

Build it and tune it

The robotics track builds a line-following robot with PID control in C++ and simulation, so you can watch each term change the behavior and tune the gains yourself, graded in your browser. The first project is free.

Understand PID on a line follower, and you understand the algorithm steering drones and cars.

Top comments (0)