Build a mini robotMiddleLesson 2706 min read

Smooth steering with PID

A PID controller steers by how far off the line you are, how long you have been off, and how fast the error is changing. Tune P, I and D on the virtual robot until it tracks the line smoothly.

Lesson in motion

In 60 seconds

Smooth steering with PID

A PID controller steers by how far off the line you are, how long you have been off, and how fast the error is changing. Tune P, I and D on the virtual robot until it tracks the…

1/4
In simple words
When you carry a full glass of water, you do not jerk your hand when it tips a little. You make a small correction if it tips a little and a bigger one if it tips a lot. If it keeps tipping the same way, you correct a bit more. If it is tipping fast, you act quickly before it spills. That is PID.
Your two-sensor line follower from lesson 3 only knows "left", "right" or "centred". So it wiggles. A line-position sensor (in real robots, a row of several IR sensors) tells you how far the line is from the centre. In the simulator this is s["offset"]: centimetres to the left (+) or right (−) of the tape. Now we can steer smoothly.

The three terms

TermIt looks atWhat it doesToo much of it
P (proportional)The error nowTurn more when you are further offFast wiggles (oscillation)
I (integral)The error added up over timeRemoves a small steady error, for example when one motor is weakerSlow, big swings and overshoot
D (derivative)How fast the error is changingBrakes the turn as you approach the line, calming wigglesNervous, jerky steering that reacts to noise
Each step, the controller adds the three parts to get a turn: turn = KP × error + KI × sum_of_errors + KD × change_in_error. Then the left wheel gets base + turn and the right wheel base − turn. The numbers KP, KI and KD are the gains. Tuning means choosing them.
Python: one PID step, by handpython
KP, KI, KD = 0.1, 0.0, 0.2
base = 0.6
total, previous = 0.0, None

for error in [8.0, 6.5, 4.0, 2.0, 0.5, -0.3]:      # cm, the robot is closing in on the line
    total += error
    change = 0.0 if previous is None else error - previous
    previous = error
    turn = KP * error + KI * total + KD * change
    print(f"error {error:5.1f}  change {change:5.1f}  turn {turn:6.2f}  "
          f"wheels ({base + turn:.2f}, {base - turn:.2f})")
Look at the output: as the error shrinks quickly, the D part (change is negative) reduces the turn early, so the robot does not swing past the line.

A simple way to tune

  1. 1

    Start with all gains at 0

    The robot drives straight and leaves the line: that is expected.
  2. 2

    Raise KP slowly

    Increase until the robot follows the line. If it starts to wiggle, go back a little.
  3. 3

    Add a little KD

    It should calm the wiggles and let you use a higher KP.
  4. 4

    Add a tiny KI only if needed

    If the robot always stays a bit to one side, a small KI fixes it. Too much makes it swing.
  5. 5

    Change one thing at a time and write it down

    Keep a table of gains and results.
Note
In our simple simulator, the sensor sits 6 cm ahead of the wheels and the motors are perfect, so a well-chosen P alone can already do well. Real robots have motor delays, one motor stronger than the other, and bumpy floors. There, D and a small I often help much more. Tuning on the real robot is always the final step.

Two safety habits for PID on real robots

  • Limit the turn. Clip the turn so the wheels never go past their safe range. The lab code clips the turn to the base speed.
  • Limit the integral. If the robot is stuck or lifted, the error keeps adding up (this is called integral windup). When it is put back down, it can swing hard. Cap the sum, or reset it when the robot stops.
Real example
Imagine a college team in Coimbatore. They tuned their line follower at night in a quiet lab and it was perfect. At the daytime competition it wiggled off the track. The floor was the same; the light from the windows changed their sensor readings, so the errors were bigger and noisier. They lowered KD, which had been amplifying the noise, re-calibrated the sensors, and it was steady again.
Try this. In the code above, set KD to 0 and run it again. Compare the wheel speeds in the last few lines. Which setting would swing past the line?

Watch and read more

Lab

Tuned P, I and D gains that bring the virtual robot back to the line and keep it within 2 cm, from two different starts.

~30 min

The problem

This runs in your browser. The robot starts 10 cm off the line, pointing away from it. The PID code is already written; your job is to tune KP, KI and KD.

  1. Run the starter with all gains at 0. The robot drives off.
  2. Raise KP step by step (try 0.01, 0.05, 0.1, 0.3, 1.0). Watch the picture and the numbers.
  3. Then try adding KD (0.1, 0.3, 1.0) and a tiny KI (0.01, 0.05).
  4. Goal: from step 40 on, the robot's middle stays within 2 cm of the tape, it reaches at least x = 140 cm, and it does not crash. The check also tries a second start on the other side.
  5. Make a table of at least five gain settings you tried and what happened. Which term helped most here? Which made things worse?

Practice lab

Edit the code and run it. Python runs in your browser — nothing is sent to our server.

Output

No output. Add print(...) to see values.

You are done when

Hard questions

Try to answer before you reveal. If you can answer these, you understood the lesson.

Q1Why does the lab clip the turn to the base speed?Reveal

Without the clip, a large error gives a huge turn, so one wheel runs full forward and the other full backward. The robot then spins on the spot, and because it barely moves forward it can get stuck spinning. Clipping keeps both wheels at or above zero, so the robot always makes progress while it turns. On real robots, limits like this also protect motors and keep motion predictable.

Q2Your gains work perfectly in the simulator. On the real robot, the same gains cause wild wiggles. Give two reasons and what you would change.Reveal

Real motors take time to speed up and slow down, and real sensors are noisier and may read less often, so the controller reacts to old or jumpy information. That makes the same gains too strong. Start with lower KP and KD on the real robot, smooth the sensor reading, and tune again step by step. This is the sim-to-real gap in action.

Please sign in to continue.

Questions people ask

Is PID only for line followers?

No. PID is used very widely: keeping a drone level, holding a motor at a set speed, keeping an oven or water heater at a set temperature, and many factory machines. Anywhere you want a measurement to stay at a target, PID is a common first choice.

Do I always need all three terms?

No. Many robots use just P, or PD. Use I only when there is a steady error that P and D leave behind. Simpler is easier to tune and to understand.

Why does D react badly to noise?

D looks at how fast the error changes. A noisy sensor makes the error jump up and down from one reading to the next, which looks like a fast change. D then makes sharp, jerky turns. Smoothing the sensor reading, or using a smaller KD, helps.

Are there better methods than PID?

For some jobs, yes. Engineers also use model-based controllers and, in research, learned controllers. But PID is simple, well understood and often good enough, which is why it is a classic first controller to learn.

Lesson test

5 questions. Get 3 right (60%) to pass and complete this lesson.

Sign in to take the test and save your progress