Line Following Robot with Arduino
Build an autonomous line-following robot using Arduino and IR sensor array.
Parts List
- Arduino Uno
- IR Sensor Array (5 sensors)
- L298N Motor Driver
- DC Motors (x2)
- Robot Chassis
- Battery Pack
Step-by-Step Instructions
Build Chassis
Attach the two DC motors to the robot chassis using the provided mounting brackets, positioning them symmetrically on the left and right sides. Press the wheels onto the motor shafts and add a caster wheel or ball bearing at the front for balance. Secure the battery pack underneath the chassis and route the power wires up to where the motor driver will be mounted.
Wire IR Sensors
Mount the 5-sensor IR array on the underside of the chassis at the front, approximately 5mm above the ground surface for optimal detection. Connect the sensor output pins to Arduino analog pins A0 through A4, and wire VCC to 5V and GND to ground. Connect the L298N motor driver inputs IN1-IN4 to digital pins 5, 6, 7, and 8, and the ENA/ENB enable pins to PWM pins 9 and 10.
Program PID Control
Write an Arduino sketch that reads all five IR sensor values and calculates a weighted average to determine the robot's position relative to the line. Implement a PID controller with proportional, integral, and derivative terms that adjust the differential motor speeds to steer the robot back toward the center of the line. Start with conservative PID gains (Kp=2, Ki=0, Kd=1) and tune incrementally while testing on your track.
int pins[] = {A0, A1, A2, A3, A4};
float Kp = 2, Ki = 0, Kd = 1;
float error = 0, lastError = 0, integral = 0;
float readLine() {
float sum = 0, weighted = 0;
for (int i = 0; i < 5; i++) {
float val = analogRead(pins[i]);
weighted += val * i;
sum += val;
}
return sum > 0 ? weighted / sum - 2.0 : 0;
}
void loop() {
error = readLine();
integral += error;
integral = constrain(integral, -50, 50);
float derivative = error - lastError;
float correction = Kp * error + Ki * integral + Kd * derivative;
lastError = error;
int baseSpeed = 150;
int leftSpeed = baseSpeed + correction;
int rightSpeed = baseSpeed - correction;
// Set motor speeds via L298N
}Calibrate Sensors
Place the robot over the line and record the sensor readings for both the line and the background surface to establish detection thresholds. Write a calibration routine that automatically sets the midpoint between line and background values for each sensor. Test the robot on straight sections first, then curves, adjusting the PID parameters until it follows the line smoothly without oscillating or losing the track.