← How-Tos
electronics Jul 3, 2026 ◯ 2 min read

Line Follower / Obstacle Avoidance Robot

arduinoline followerir sensorroboticsobstacle avoidance

Line Follower: How IR Sensors Work

IR line sensors (commonly sold as 5-sensor arrays like the TCRT5000-based bars) shine infrared light down and measure reflection — white surfaces reflect more IR back than black, so each sensor outputs a digital HIGH/LOW (or analog value on some modules) indicating light/dark under it. A line follower reads an array of these sensors positioned across the robot's front and steers to keep the dark line centered.

Basic Wiring

Simple Bang-Bang Control

int sensors[5] = {2,3,4,5,6}; // left to right void loop() { int s[5]; for (int i = 0; i < 5; i++) s[i] = digitalRead(sensors[i]); if (s[2] == LOW) { // center sensor sees the line forward(); } else if (s[0] == LOW || s[1] == LOW) { turnLeft(); // line drifted left, correct } else if (s[3] == LOW || s[4] == LOW) { turnRight(); } else { stop(); // line lost entirely } }

This works but is jerky. A PID controller (proportional-integral-derivative, calculating steering correction proportional to how far off-center the line is, rather than binary left/right) gives dramatically smoother following — worth implementing once basic bang-bang control is working, using the sensor array's analog outputs if your module has them for finer positional error calculation.

Obstacle Avoidance: Ultrasonic Approach

HC-SR04 ultrasonic sensor mounted front-center, sometimes on a servo for side-to-side scanning:

#include <NewPing.h> NewPing sonar(trigPin, echoPin, 200); // 200cm max distance void loop() { int distance = sonar.ping_cm(); if (distance > 0 && distance < 15) { stop(); reverse(); delay(300); turnRight(); delay(400); } else { forward(); } }

Combining Both Behaviors

A robot that both follows a line AND avoids obstacles needs a priority system — obstacle detection should always override line-following (safety first), which usually means checking the ultrasonic sensor first in loop() and only falling through to line-following logic if the path ahead is clear.

Common Tuning Issues