Introduction
A line following robot is one of the most fundamental robotics projects. It uses IR sensors to detect a dark line on a light surface and follows it autonomously. This is a great project to learn about sensor interfacing, motor control, and basic control logic.
Components Required
- Arduino Uno
- L298N Motor Driver Module
- 2× IR Sensor Modules (TCRT5000 or similar)
- 2× DC Gear Motors (with wheels)
- 1× Caster wheel
- Robot chassis (acrylic or PVC)
- 9V battery or 7.4V Li-Po
- Jumper wires
Wiring
IR Sensors → Arduino
| Sensor | Arduino Pin |
|---|---|
| Left IR - OUT | A0 |
| Right IR - OUT | A1 |
| Both VCC | 5V |
| Both GND | GND |
L298N → Arduino
| L298N Pin | Arduino Pin |
|---|---|
| IN1 | Pin 5 |
| IN2 | Pin 6 |
| IN3 | Pin 9 |
| IN4 | Pin 10 |
| ENA | Pin 3 |
| ENB | Pin 11 |
The Code
// Motor pins
const int ENA = 3, IN1 = 5, IN2 = 6;
const int ENB = 11, IN3 = 9, IN4 = 10;
// Sensor pins
const int leftSensor = A0;
const int rightSensor = A1;
int speed = 150; // 0-255
void setup() {
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
Serial.begin(9600);
}
void moveForward() {
analogWrite(ENA, speed); analogWrite(ENB, speed);
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);
}
void turnLeft() {
analogWrite(ENA, 0); analogWrite(ENB, speed);
digitalWrite(IN1, LOW); digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);
}
void turnRight() {
analogWrite(ENA, speed); analogWrite(ENB, 0);
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW); digitalWrite(IN4, LOW);
}
void stopMotors() {
analogWrite(ENA, 0); analogWrite(ENB, 0);
}
void loop() {
int left = analogRead(leftSensor);
int right = analogRead(rightSensor);
// Threshold depends on your sensors — calibrate!
bool leftOnLine = left > 500;
bool rightOnLine = right > 500;
if (leftOnLine && rightOnLine) {
moveForward();
} else if (leftOnLine && !rightOnLine) {
turnLeft();
} else if (!leftOnLine && rightOnLine) {
turnRight();
} else {
moveForward(); // both off line — keep going
}
delay(10);
}Assembly Tips
- Mount IR sensors at the front, pointing downward, about 1cm above the ground
- Space them roughly the width of your line apart (2-3cm)
- Keep the center of gravity low for stability
- Use a white surface with black electrical tape for the line
Calibration
Before running, check sensor readings using Serial Monitor. Adjust the threshold (500 in the code) based on your actual readings for "on line" vs "off line".