PID Controller Robotics: Stop Your Line Follower Wobbling
Learn how a PID controller works in robotics, with Arduino code, simulation data and tuning steps. Simple English guide for Indian students and makers.
A PID controller stops a robot from wobbling by deciding how much to correct, not just which way. It looks at the error (the gap between where the robot should be and where it is) and combines three things: how big the error is now (P), how long it has been there (I), and how fast it is changing (D). The result is a smooth correction value that you add to and subtract from your motor speeds.
Most first robots use on-off control. If you have finished building a line follower robot, you have probably seen it: the robot drifts left, turns hard right, goes too far, turns hard left, and keeps swinging until the end of the track. That happens because one motor simply switches off when the robot needs to turn. There is no “turn a little” option. The same problem shows up in self-balancing robots that try to stay upright and drones that try to hold a height.
This tutorial builds a PID line follower step by step on an Arduino Uno. Every code output shown below was produced by running the same PID code, and the tuning section includes results from a simulation so you can see what P, PD and PID actually do before you touch your robot.
Prerequisites and Versions Used
You need a working two-wheel robot first. If you are starting from zero, our simple line follower build covers the chassis and wiring basics.
- Board: Arduino Uno (or any ATmega328P board such as a Nano).
- Sensors: 5 digital IR line sensors in a row, spaced roughly 2 cm apart.
- Motor driver: an L298N or L293D-style dual H-bridge with separate enable (PWM) pins for each motor.
- Robot: two DC gear motors, a caster wheel and a battery pack suited to your motors.
- Software: Arduino IDE 2.x. The current release at the time of writing is Arduino IDE 2.3.10 (June 2026).
- How the code was checked: the sketch was compiled with g++ 13.3 against a small desktop stand-in for the Arduino functions, and the PID function was run inside a line follower simulation. It was not uploaded to a physical robot for this article, so expect your gain values to differ.
If H-bridges are new to you, read how motor drivers work before wiring anything.
PID Formula: What Do Kp, Ki and Kd Actually Do?
Every PID system has a value you want and a value you are getting. Take a self-balancing robot. You want it at 90 degrees (upright). That target is called the setpoint. The angle the sensor actually reads is the process variable. The difference between them is the error.
error = setpoint - process variableerror = 90 - 97 = -7 degrees
The PID controller’s only job is to look at this error and decide how hard to push so the error goes to zero. It does that with one formula:
output = (Kp * error) + (Ki * total of past errors) + (Kd * how fast error is changing)
Kp, Ki and Kd are numbers you choose. Tuning a robot means finding good values for these three. In a line follower, the output is used as a correction: one wheel runs at base speed plus the correction, and the other at base speed minus the correction.
| Term | Looks at | Simple meaning | Main side effect if too high |
|---|---|---|---|
| P (Proportional) | The error right now | The more wrong you are, the harder you turn | Fast wobbling across the line |
| I (Integral) | The total of past errors | A memory that fixes small errors that never go away | Slow swings and integral windup |
| D (Derivative) | How fast the error is changing | Brakes the correction before you overshoot | Jerky, twitchy motors, especially with noisy sensors |
Step 1: Wire the IR Sensors and Motor Driver
Wire the five sensors to the analog pins (used here as digital inputs) and the motor driver to the pins below. The enable pins go to pins 9 and 10 on purpose. The official Arduino reference notes that PWM on pins 5 and 6 of the Uno gives higher-than-expected duty cycles, and a value of 0 may not fully stop the output there, because those pins share a timer with millis().
| Part | Driver or sensor pin | Arduino Uno pin |
|---|---|---|
| IR sensors (left to right) | OUT | A0, A1, A2, A3, A4 |
| Left motor speed | ENA | 9 (PWM) |
| Left motor direction | IN1, IN2 | 7, 8 |
| Right motor speed | ENB | 10 (PWM) |
| Right motor direction | IN3, IN4 | 11, 12 |
| Ground | GND | GND (shared with motor battery) |
Remove the jumper caps on ENA and ENB if your driver board has them. Otherwise the motors always run at full speed and the PID correction does nothing. The PWM idea is the same one used for PWM motor speed control on other robots: a value from 0 to 255 sets the motor speed.
📌 Official Resource: PWM pins, frequencies and the pin 5 and 6 note for every Arduino board are listed in the analogWrite() reference. Visit Official Website
Step 2: Upload the PID Line Follower Sketch
Here is the complete sketch. It starts with only Kp switched on (Ki and Kd are zero). The next steps explain each part and when to switch the others on.
// PID line follower - Arduino Uno + L298N/L293D-style driver + 5 digital IR sensors// Start with Kp only. Add Kd, then a small Ki. See the tuning step.// ---------- Pins ----------const int sensorPins[5] = {A0, A1, A2, A3, A4}; // left to rightconst int weights[5] = {-4, -2, 0, 2, 4}; // position of each sensorconst int LINE_DETECTED = HIGH; // check your module: some give LOW on blackconst int ENA = 9; // left motor speed (PWM)const int IN1 = 7;const int IN2 = 8;const int ENB = 10; // right motor speed (PWM)const int IN3 = 11;const int IN4 = 12;// ---------- PID settings ----------const float DT = 0.01; // loop time in seconds (10 ms = 100 loops per second)const unsigned long LOOP_MS = 10;float Kp = 20.0, Ki = 0.0, Kd = 0.0;float integral = 0, lastError = 0;const float INTEGRAL_LIMIT = 2.0; // anti-windup clampfloat pTerm, iTerm, dTerm;const int BASE_SPEED = 150; // 0-255unsigned long lastLoop = 0;float readError() { int sum = 0, count = 0; for (int i = 0; i < 5; i++) { if (digitalRead(sensorPins[i]) == LINE_DETECTED) { sum += weights[i]; count++; } } if (count == 0) { // Line lost: keep turning towards the side we last saw it return (lastError > 0) ? 5.0 : -5.0; } return (float)sum / count; // positive = line is to the right of centre}float computePID(float error) { pTerm = Kp * error; // P: error now integral += error * DT; // I: running total of past error if (integral > INTEGRAL_LIMIT) integral = INTEGRAL_LIMIT; if (integral < -INTEGRAL_LIMIT) integral = -INTEGRAL_LIMIT; iTerm = Ki * integral; dTerm = Kd * (error - lastError) / DT; // D: how fast error is changing lastError = error; return pTerm + iTerm + dTerm;}void setMotors(int leftSpeed, int rightSpeed) { leftSpeed = constrain(leftSpeed, 0, 255); rightSpeed = constrain(rightSpeed, 0, 255); digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); // both motors forward digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); analogWrite(ENA, leftSpeed); analogWrite(ENB, rightSpeed);}void setup() { Serial.begin(115200); for (int i = 0; i < 5; i++) pinMode(sensorPins[i], INPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);}void loop() { if (millis() - lastLoop < LOOP_MS) return; // run exactly every 10 ms lastLoop = millis(); float error = readError(); float correction = computePID(error); int leftSpeed = BASE_SPEED + correction; int rightSpeed = BASE_SPEED - correction; setMotors(leftSpeed, rightSpeed); Serial.print("err="); Serial.print(error, 2); Serial.print(" P="); Serial.print(pTerm, 1); Serial.print(" I="); Serial.print(iTerm, 1); Serial.print(" D="); Serial.print(dTerm, 1); Serial.print(" corr="); Serial.print(correction, 1); Serial.print(" L="); Serial.print(constrain(leftSpeed, 0, 255)); Serial.print(" R="); Serial.println(constrain(rightSpeed, 0, 255));}
How the error is calculated: each sensor has a weight from -4 (far left) to +4 (far right). The code averages the weights of the sensors that see the line. Zero means the line is in the centre. A positive number means the line is to the right, so the robot must turn right. If no sensor sees the line, the error is set to +5 or -5 based on the side where the line was last seen, so the robot keeps searching in the right direction.
Open the Serial Monitor at 115200 baud and move the robot over the line by hand with the wheels lifted. Expected output for four positions (centred, line under the right-middle sensor, line between centre and right-middle, line lost on the right):
err=0.00 P=0.0 I=0.0 D=0.0 corr=0.0 L=150 R=150err=2.00 P=40.0 I=0.0 D=0.0 corr=40.0 L=190 R=110err=1.00 P=20.0 I=0.0 D=0.0 corr=20.0 L=170 R=130err=5.00 P=100.0 I=0.0 D=0.0 corr=100.0 L=250 R=50
If the signs are the wrong way round (the left wheel slows down when the line is on the right), swap the weights or change LINE_DETECTED to LOW. Fix this before going further. A PID loop with the wrong sign pushes the robot away from the line.
Step 3: Add the Proportional (P) Term
Proportional means “matching in size”. The correction grows with the error: the more wrong you are, the harder you turn. The P line in computePID() is simply:
pTerm = Kp * error;
Set Kp to 10 and look at two cases: the robot slightly off the line (error 1) and the line completely lost (error 5). Expected output:
err=1.00 P=10.0 I=0.0 D=0.0 corr=10.0 L=160 R=140err=5.00 P=50.0 I=0.0 D=0.0 corr=50.0 L=200 R=100
A small error changes the wheel speeds by only 10, so the robot turns gently. A large error changes them by 50, so it turns much harder. That alone is a big step up from on-off control, and for many beginner robots, P is enough to follow a simple track.
P has two weak points. If Kp is too high, the robot overshoots and wobbles. And if one motor is slightly weaker than the other, P leaves the robot sitting a little to one side of the line forever, because a small error only produces a small correction that cannot beat the weak motor.
Step 4: Add the Integral (I) Term with Anti-Windup
The integral term fixes that leftover error. It keeps a running total of past errors. If the error does not go away, the total keeps growing until the correction becomes strong enough to fix the problem. Think of it as the controller’s memory.
integral += error * DT;if (integral > INTEGRAL_LIMIT) integral = INTEGRAL_LIMIT;if (integral < -INTEGRAL_LIMIT) integral = -INTEGRAL_LIMIT;iTerm = Ki * integral;
The code multiplies each error by DT (0.01 seconds). This keeps your Ki value meaningful even if you later change the loop speed. With Kp = 20, Ki = 5 and the robot stuck at error 1 because of a weak motor, the output over 300 loops (3 seconds) looks like this:
loop 1: err=1.00 P=20.0 I=0.0 D=0.0 corr=20.0 L=170 R=129loop 10: err=1.00 P=20.0 I=0.5 D=0.0 corr=20.5 L=170 R=129loop 100: err=1.00 P=20.0 I=5.0 D=0.0 corr=25.0 L=175 R=125loop 200: err=1.00 P=20.0 I=10.0 D=0.0 corr=30.0 L=180 R=120loop 300: err=1.00 P=20.0 I=10.0 D=0.0 corr=30.0 L=180 R=120
The P part stays at 20, but the I part keeps building and pushes the correction up until the weak motor is beaten. Notice that I stops at 10.0 after loop 200. That is the anti-windup clamp at work: the integral is not allowed past 2.0, so Ki x 2.0 = 10 is the most the I term can add. The R value of 129 instead of 130 is not a bug; converting the correction to a whole number drops the decimal part.
Integral Windup Problem: Why the Clamp Matters
Imagine the robot leaves the track completely, or you pick it up for a few seconds while the code keeps running. The error stays large the whole time, so the integral keeps growing. When the robot gets back to the line, that huge stored total is still there. The robot overshoots badly and can even start spinning. This is called integral windup. Brett Beauregard, who wrote the Arduino PID Library, describes it in his post on reset windup in the beginner’s PID as the trap that catches more beginners than any other. Limiting the integral, as this sketch does, is one of the common fixes. The tuning step below shows how much difference it makes.
Step 5: Add the Derivative (D) Term
The derivative term does not care how big the error is or how long it has been there. It checks how fast the error is changing and uses that to predict what happens next. If the robot is rushing back to the line, D sees it coming and eases off the correction early, so the robot does not shoot past to the other side.
dTerm = Kd * (error - lastError) / DT;lastError = error;
With Kp = 20, Kd = 0.2 and the robot coming back quickly from error 4 to the centre, the expected output is:
err=4.00 P=80.0 I=0.0 D=0.0 corr=80.0 L=230 R=70err=2.00 P=40.0 I=0.0 D=-40.0 corr=0.0 L=150 R=150err=1.00 P=20.0 I=0.0 D=-20.0 corr=0.0 L=150 R=150err=0.00 P=0.0 I=0.0 D=-20.0 corr=-20.0 L=130 R=170err=0.00 P=0.0 I=0.0 D=0.0 corr=0.0 L=150 R=150
Look at the second and third lines. P still wants to turn (40, then 20), but the error is dropping fast, so D pushes the other way and cancels it. As the robot reaches the centre, D even adds a small opposite correction to stop the swing. Once the error stops changing, D goes back to zero.
One warning for digital sensors: the error jumps in steps (0, 1, 2) instead of changing smoothly, so the D term arrives in sudden kicks. That is why the Kd used here is small. With a large Kd and digital sensors, the motors will twitch.
Step 6: Tune Kp, Ki and Kd
There is no magic set of values that works on every robot. Gains depend on your motors, battery voltage, weight, wheel size and sensor spacing. Use this order:
- Set Ki and Kd to 0. Start with a low Kp and raise it until the robot follows the line but starts to wobble.
- Add Kd in small steps until the wobble dies down. Stop before the motors start twitching.
- Only if the robot still sits slightly to one side on straight lines, add a small Ki.
- Change one value at a time, and test with a fully charged battery each time.
To show why this order works, we ran the exact computePID() function from the sketch in a simple line follower simulation. The simulated robot starts 2 cm off the line, one motor is weaker than the other, the loop runs 100 times per second, the motors take a short time to respond, and each run lasts 15 seconds. The sensor reading is smooth here (like an analog sensor array), so these gain numbers are for the simulation only. Use the pattern, not the numbers.
| Controller | Gains | Overshoot to the other side | Time to settle within 0.3 cm | Final distance from line |
|---|---|---|---|---|
| P only | Kp=10 | 10.6 cm | Never – swing kept growing | Lost the line |
| P only | Kp=20 | 23.6 cm | Never – swing kept growing | Lost the line |
| PD | Kp=20, Kd=10 | 0.49 cm | 2.2 s | 0.25 cm (stuck to one side) |
| PID | Kp=20, Ki=5, Kd=10 | 0.74 cm | 2.6 s | 0.009 cm |
Three things stand out. First, P alone never settled in this model; raising Kp made the swing worse, not better. Second, adding D removed almost all the overshoot, but the robot stayed 0.25 cm to one side because of the weak motor. That number is exactly the weak motor’s push divided by Kp, which is the leftover error P cannot remove on its own. Third, adding a small Ki pulled the robot back onto the line, at the cost of a slightly slower settle.
We also tested windup. In this run, the simulated robot was held off the line for 3 seconds while the code kept running, and then released 5 cm from the line with Kp=20, Ki=5, Kd=10:
| Integral limit | Overshoot after release | Time to settle within 0.3 cm |
|---|---|---|
| No real limit | 4.80 cm | 10.2 s |
| INTEGRAL_LIMIT = 2.0 | 0.81 cm | 2.1 s |
Without the clamp, the stored integral threw the robot almost 5 cm past the line and it took about five times longer to recover. Two lines of code fixed that.
📌 Official Resource: Brett Beauregard’s Arduino PID Library (version 1.2.1, MIT licence) handles sample time, output limits and windup for you once you understand the basics. Visit Official Website
Common Errors and Their Fixes
Most PID problems come down to a handful of causes. Match what your robot does to the table below.
| What you see | Likely cause | Fix |
|---|---|---|
| Robot turns away from the line | Correction sign is reversed | Swap the weights, or swap + and – in the leftSpeed and rightSpeed lines |
| Fast wobble across the line | Kp too high, or Kd too low | Lower Kp by a third, then add Kd slowly |
| Slow, wide swings that build up | Ki too high | Halve Ki, or set it to 0 and start again |
| Motors twitch and buzz | Kd too high for digital sensors | Reduce Kd, or use an analog sensor array |
| Robot spins after leaving the track | Integral windup | Lower INTEGRAL_LIMIT, or reset integral to 0 when the line is lost |
| Behaviour changes when you add code | Loop time is not steady | Keep the millis() timing check and avoid delay() inside loop() |
| Motors never stop fully or behave oddly at low speed | Enable pins on 5 or 6 | Move ENA and ENB to pins 9 and 10 |
| Tuning stops working after a few runs | Battery voltage dropping | Tune and test on a fully charged battery |
One more mistake worth calling out: printing too much to Serial at a low baud rate slows the loop. The sketch uses 115200 baud for that reason. If you lower it, check that your loop still runs every 10 ms, or remove the prints once tuning is done.
Frequently Asked Questions
Should I use the Arduino PID library instead of writing my own PID code?
For your first robot, writing these few lines yourself helps you see what each term does, which makes tuning much easier. Once you understand it, the Arduino PID Library by Brett Beauregard is a good choice because it already handles sample time, output limits and windup for you.
Can I use the same PID code for a self-balancing robot or a drone?
The computePID() function stays the same, but the error comes from a different sensor. A self-balancing robot uses the tilt angle from an IMU as the process variable, while a drone usually runs separate PID loops for height and for each axis, and each loop is tuned on its own.
Why are my Kp, Ki and Kd values so different from other tutorials?
Gains depend on your error units, loop speed, motors, battery voltage and the weight of your robot, so they rarely transfer between robots. Our code also multiplies by the loop time DT, so its Ki and Kd numbers are not comparable to code that adds and subtracts raw errors without DT.
Next Steps
- Switch to an analog sensor array: analog readings give a smooth error instead of steps of 1 or 2, so the D term works properly and you can run faster.
- Add live tuning: read three potentiometers with analogRead() and map them to Kp, Ki and Kd, so you can tune on the track without re-uploading code.
- Try PID on a balancing robot: the same controller keeps a robot upright using an IMU angle. Our self-balancing robot example shows what that kind of robot looks like.
- Plan what to learn after this: PID sits in the middle of most robotics skills. Our robotics learning roadmap shows where it fits, and our basic line follower without a microcontroller is a good contrast to see how far control has come.
Found this helpful? Share it with someone navigating the Indian IT job market. Subscribe to our RootSaid IT YouTube channel for honest, hands-on IT career and tech videos – and check out our RootSaid Robotics Malayalam channel if you are into hardware and making.
