RoboticsIntermediate

Build a Line Following Robot from Scratch

Step-by-step guide to building an IR sensor-based line following robot using Arduino.

1 February 202615 min read

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

SensorArduino Pin
Left IR - OUTA0
Right IR - OUTA1
Both VCC5V
Both GNDGND

L298N → Arduino

L298N PinArduino Pin
IN1Pin 5
IN2Pin 6
IN3Pin 9
IN4Pin 10
ENAPin 3
ENBPin 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

  1. Mount IR sensors at the front, pointing downward, about 1cm above the ground
  2. Space them roughly the width of your line apart (2-3cm)
  3. Keep the center of gravity low for stability
  4. 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".

Tags:RobotLine FollowerIR Sensor