A line-follower robot drives along a black line on a white surface on its own. It is the classic first robot and the entry event at most college tech fests, because it teaches the three things every robot needs: sensing, deciding and moving. This guide builds a two-sensor version you can later upgrade to five sensors and PID control.
Parts
- 2WD robot chassis with two geared DC motors and a caster wheel
- L298N dual motor driver
- Two IR sensor modules (or a 5-channel IR array)
- Arduino Uno or Nano
- Battery holder with 2 × 18650 cells (about 7.4 V)
- Jumper wires
How it works
Mount the two IR sensors at the front, just either side of the line. On white, both sensors see a reflection; over the black line, the reflection drops. If the left sensor sees the line, the robot has drifted right, so it turns left — and vice versa. Most IR modules output LOW over a black line; if yours does the opposite, flip the comparison in the code.
Wiring
- L298N OUT1/OUT2 → left motor, OUT3/OUT4 → right motor
- L298N ENA, IN1, IN2 → Arduino pins 5, 7, 8; ENB, IN3, IN4 → pins 6, 9, 10 (remove the ENA/ENB jumpers)
- Battery + → L298N 12V input, battery − → L298N GND and Arduino GND (common ground)
- Left IR OUT → pin 2, right IR OUT → pin 3, sensor VCC/GND → 5V/GND
The code
const int L_SENSOR = 2, R_SENSOR = 3;
const int ENA = 5, IN1 = 7, IN2 = 8, ENB = 6, IN3 = 9, IN4 = 10;
const int SPEED = 150; // 0-255: start slow, raise once it tracks well
void drive(int left, int right) {
digitalWrite(IN1, left > 0); digitalWrite(IN2, left < 0);
digitalWrite(IN3, right > 0); digitalWrite(IN4, right < 0);
analogWrite(ENA, abs(left)); analogWrite(ENB, abs(right));
}
void setup() {
const int outputs[] = {ENA, IN1, IN2, ENB, IN3, IN4};
for (int pin : outputs) pinMode(pin, OUTPUT);
pinMode(L_SENSOR, INPUT);
pinMode(R_SENSOR, INPUT);
}
void loop() {
bool leftOnLine = digitalRead(L_SENSOR) == LOW;
bool rightOnLine = digitalRead(R_SENSOR) == LOW;
if (leftOnLine && !rightOnLine) drive(0, SPEED); // drifted right: turn left
else if (rightOnLine && !leftOnLine) drive(SPEED, 0); // drifted left: turn right
else drive(SPEED, SPEED); // centred: go straight
}Tuning tips
- Set each IR module's potentiometer so its LED switches cleanly between the line and the white surface.
- If the robot overshoots curves, lower SPEED or move the sensors closer together.
- If one motor runs backwards, swap its two wires on the L298N.
- A 25 mm wide black electrical-tape line on white chart paper makes a good practice track.
Upgrade: five sensors and PID
Competition robots use a five-sensor array to estimate how far the robot is from the centre of the line, then a PID controller to steer smoothly instead of zig-zagging. Once the two-sensor version works, swapping in an array and adding PID is the natural next step.
Questions or improvements? Join the discussion →