Advertisement
Beginner Time: 1–2 weeks Robotics

Line Following Robot

Build an autonomous robot that follows a black line using IR sensors and PID control algorithm.

IR SensorArduinoPIDMotor DriverRoboticsAutonomous
DifficultyBeginner
Duration1–2 weeks
Components10 items
Steps7 steps

Introduction

Build an autonomous robot that follows a black line using IR sensors and PID control algorithm. This comprehensive guide covers everything from design through implementation, testing, and deployment.

Theory & Background

TCRT5000 sensors emit infrared light and measure reflected intensity. White surface reflects IR strongly (low ADC value), black line absorbs IR (high ADC value or digital LOW). Mount five sensors in a row below the chassis front, spaced 15mm apart. Sensor 3 (center) detects line when robot is correctly positioned. Sensors 1-2 (left) and 4-5 (right) detect deviations. Calibrate in your operating environment — ambient light affects readings significantly.

Advertisement

Components & Requirements

10 components required for this project.

#ComponentPurposeQty
1Arduino Uno R3Main microcontrollerx1
2IR Sensor Module (TCRT5000)Line detection arrayx5
3L298N H-Bridge Motor DriverDual DC motor controlx1
4DC Gear Motors with Wheels (12V, 100RPM)Drive wheelsx2
5Ball Caster WheelFront support wheelx1
67.4V 2S LiPo Battery (2200mAh)Power supplyx1
7Robot Chassis (acrylic)Mechanical platformx1
810kΩ PotentiometersSensor sensitivity adjustmentx2
9220Ω ResistorsIR LED current limitingx5
10Power SwitchMain power cutoffx1

Step-by-Step Implementation

Follow these 7 steps carefully.

1
IR Sensor Working Principle

TCRT5000 sensors emit infrared light and measure reflected intensity. White surface reflects IR strongly (low ADC value), black line absorbs IR (high ADC value or digital LOW). Mount five sensors in a row below the chassis front, spaced 15mm apart. Sensor 3 (center) detects line when robot is correctly positioned. Sensors 1-2 (left) and 4-5 (right) detect deviations. Calibrate in your operating environment — ambient light affects readings significantly.

2
Hardware Assembly

Mount motors on chassis rear with wheels. Install ball caster at front center. Solder motor wires securely — vibration causes poor connections to fail. Mount IR sensor array on a front-bottom bracket 5–8mm above the floor. Battery should be center-mounted for balanced weight distribution. Run all wiring through cable ties to prevent entanglement in wheels.

3
Basic ON/OFF Control

Start with simple bang-bang control: read 5 sensors. If center sensor sees line → go straight. If left sensors see line → turn right. If right sensors see line → turn left. If no sensor sees line → stop (line lost). This works but causes jerky, oscillatory motion especially at speed. Test on a white surface with 20–25mm wide black tape track.

4
Weighted Error Calculation for PID

Assign weights to sensors: positions [-2, -1, 0, 1, 2] for sensors [S1, S2, S3, S4, S5]. Error = sum(sensor_value × weight) / sum(sensor_values). This gives a continuous error value (-2 to +2) rather than discrete states. Negative error = line is left → steer left. Positive error = line is right → steer right. This smooth error signal is ideal input for PID controller.

5
PID Implementation

Proportional: correction = Kp × error. Integral: correction += Ki × error × dt (eliminates steady-state offset). Derivative: correction += Kd × (error - prev_error)/dt (reduces overshoot). Motor speeds: LEFT = base_speed + correction, RIGHT = base_speed - correction (clamped 0–255). Start tuning: Kp=30, Ki=0, Kd=10. Increase Kp until oscillation, add Kd to dampen, add small Ki if needed.

6
Speed Optimization

With good PID tuning, the robot can navigate at higher speeds. Implement adaptive speed: when error is large (sharp curve), slow down (reduce base_speed). When error is near zero (straight), increase speed. This variable speed approach improves lap times on complex tracks by 30–40%. Set maximum speed limit to prevent motor stall on sharp turns where one wheel needs to reverse.

7
Track Testing and Debugging

Test on various track features: straight sections (verify no drift), 90° corners, 180° U-turns, crossings (T and + intersections), and curved sections. Log sensor readings, error, and PID output to Serial Monitor at low speed. Common issues: sensor crosstalk (sensors too close), wheel slip (check floor surface/wheel rubber), PID windup on lost-line recovery, and insufficient torque at low PWM from motor startup friction.

Code & Implementation

Core code for line_follower_pid.ino:

line_follower_pid.ino C/C++
#define S1 A0  // Leftmost
#define S2 A1
#define S3 A2  // Center
#define S4 A3
#define S5 A4  // Rightmost
#define IN1 7  #define IN2 8  #define ENA 9
#define IN3 10 #define IN4 11 #define ENB 5

float Kp=35, Ki=0.05, Kd=25;
float error=0, prev_error=0, integral=0;
int BASE = 150;

float readError() {
  int s[5];
  for(int i=0;i<5;i++) s[i] = 1023 - analogRead(A0+i); // Invert: black=high
  float sum=0, wSum=0;
  int weights[] = {-2,-1,0,1,2};
  for(int i=0;i<5;i++) { sum += s[i]; wSum += s[i] * weights[i]; }
  return (sum > 50) ? wSum/sum : prev_error; // Hold last error if line lost
}

void setMotors(int L, int R) {
  L = constrain(L, -255, 255); R = constrain(R, -255, 255);
  digitalWrite(IN1, L>0); digitalWrite(IN2, L<0); analogWrite(ENA, abs(L));
  digitalWrite(IN3, R>0); digitalWrite(IN4, R<0); analogWrite(ENB, abs(R));
}

void loop() {
  error = readError();
  integral = constrain(integral + error, -100, 100);
  float correction = Kp*error + Ki*integral + Kd*(error-prev_error);
  prev_error = error;
  setMotors(BASE + correction, BASE - correction);
  delay(5);
}

Testing & Troubleshooting

Test Line Following Robot by verifying each subsystem individually before full integration.

!
Troubleshooting Tips

Verify power voltages, check ground connections, use serial monitor for debug.

Real-World Applications

*Automated guided vehicles (AGV) in warehouses
*Factory floor material transport
*Hospital specimen delivery robots
*Competitive robotics events
*Educational robotics demonstrations
*Airport baggage handling systems
*Museum tour guide robots
*Pharmaceutical distribution automation

Extensions & Next Steps

  • Add encoder feedback for precise speed control
  • Implement intersection detection and map-based navigation
  • Add ultrasonic sensor for obstacle avoidance while following
  • Build a track editor app to program routes remotely via Bluetooth
  • Add computer vision with OpenCV for marker recognition at intersections

Interactive Playground

Coming Soon

An interactive simulator will be available here — simulate circuits and run code in-browser without hardware.

Frequently Asked Questions

What width should the black line be for optimal performance?
Standard line-following competition specifications use 18–25mm wide black tape on white background. Too narrow (<10mm): sensors may detect line edge rather than center, causing inaccurate error calculation. Too wide (>35mm): multiple sensors see the line simultaneously, making edge detection unreliable. For beginners, use 20–22mm black electrical tape on white A3 paper for easy setup and modification.
How do I handle intersections where the robot must choose a direction?
At T or + intersections, all sensors will read black simultaneously. Program a decision rule: always turn left, always go straight, or use a pre-programmed route map. Advanced robots use a map array: store [LEFT, STRAIGHT, RIGHT, RIGHT] and execute decisions sequentially as intersections are encountered. Even more advanced approaches use computer vision with a camera to recognize intersection markings.
Why does my robot oscillate even with PID tuning?
Oscillation causes: excessive Kp (too aggressive correction), insufficient Kd (insufficient damping), sensor noise causing rapid error fluctuation (add a moving average filter: error = 0.7×error_new + 0.3×error_old), motor backlash (loose wheel/axle connections), or unequal motor characteristics (one motor faster than the other — calibrate by measuring actual RPM and adjusting motor PWM bias).
Can this robot navigate in reverse?
Yes — by reading sensors and applying reverse logic. However, reversing requires careful logic to avoid infinite loops when the line is lost. Best practice: implement a recovery behavior — when line is lost, rotate in place (last known direction) for up to 2 seconds to search for the line. If not found, stop and wait. Never reverse indefinitely as this can lead to the robot going off track permanently.
How does sensor height affect performance?
Optimal sensor height is 5–8mm from the floor. Too close (<3mm): sensors see only a tiny spot, sensitive to floor imperfections and dust. Too far (>15mm): sensor beam widens, reducing resolution — adjacent sensors' fields of view overlap, making it impossible to distinguish which sensor sees the line edge. Test with a few heights and measure the signal contrast (difference between white and black readings) — choose height with maximum contrast.
Advertisement