Arduino line-following robot: sensor schematic, code, and project variations
Introduction: why build it
A line-following robot is one of the most fun and educational projects in the world of electronics and embedded programming. It lets you learn how to read sensors, control motors with PWM, work with decision logic, and, if you wish, move toward more refined controls like PID. In this guide you’ll find the sensor schematic, main connections, a ready-to-use code example, and several variants to grow the project in difficulty and performance.
How a line follower works
The basic operation is simple: a set of infrared reflective sensors detects the presence of the line (typically black on a white background) by measuring how much light is reflected from the surface. White plastic reflects more, black less; by translating these signals into digital logic or analog values, the microcontroller determines whether to go straight, correct left, or correct right.
With 3 sensors (left, center, right) you already get reliable behavior for simple tracks. With 5 or more sensors and a PID algorithm you can achieve significantly higher speed and precision.
Required components
Here’s a typical list for a 3-sensor setup:
- Arduino Uno or Nano
- L298N or L293D motor driver
- 2 DC gear motors with wheels + 1 pivot/caster
- 3 reflective IR modules TCRT5000 (digital version) or a compatible sensor bar
- Battery power (e.g., 7.4 V LiPo or 2S) and switch
- Jumper wires, breadboard or PCB, 3D-printed/laser-cut chassis
Sensor wiring and connections
In the following textual schematic we connect three digital IR sensors to three Arduino digital pins, and an L298N module to drive the motors with PWM speed control. Make sure to have common grounds between Arduino, driver, and sensors.
Power: - Battery (7–12 V) -> L298N VIN and GND - L298N GND -> Arduino GND - Arduino 5V -> IR sensors VCC (or the L298N 5V if explicitly allowed and stable) - Note: Avoid powering Arduino from the L298N 5V if the battery exceeds 12 V or the regulator is unstable. Better use a dedicated DC-DC step-down to Arduino 5V. Motors: - Left motor -> L298N OUT1/OUT2 - Right motor -> L298N OUT3/OUT4 L298N control (Arduino -> L298N): - ENA (left) -> D5 (PWM) - IN1 -> D7 - IN2 -> D8 - ENB (right) -> D6 (PWM) - IN3 -> D9 - IN4 -> D10 IR sensors (digital): - Left sensor (OUT) -> D2 - Center sensor (OUT) -> D3 - Right sensor (OUT) -> D4 - All sensors: VCC -> Arduino 5V, GND -> common GND Orientation: [ L ] [ C ] [ R ] - distance from the ground: ~2–4 mm - adjust the trimmers on the modules to get clean signals on white/black
Many digital IR modules output LOW when they detect black and HIGH on white (because of the integrated comparator). If not, just invert the logic in the code.
Basic code for 3 sensors
Below is a simple and robust program: it sets the base speed, corrects with differential turns, and implements a “search” strategy when the line is lost.
// 3-sensor line follower robot (Arduino UNO/Nano)
// Assumption: sensor = LOW on black, HIGH on white. Invert if needed.
// Sensor pins
const int PIN_SX = 2;
const int PIN_C = 3;
const int PIN_DX = 4;
// L298N
const int ENA = 5; // left PWM
const int IN1 = 7;
const int IN2 = 8;
const int ENB = 6; // right PWM
const int IN3 = 9;
const int IN4 = 10;
// Parameters
int baseSpeed = 140; // 0-255
int turnBoost = 60; // extra during correction
int searchSpeed = 110; // speed during search
int backNudge = 80; // slight reverse on inner wheel
int lastTurn = 0; // -1 = left, 1 = right, 0 = straight
void setup() {
pinMode(PIN_SX, INPUT); // If needed: INPUT_PULLUP
pinMode(PIN_C, INPUT);
pinMode(PIN_DX, INPUT);
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
stopMotors();
delay(500);
}
void loop() {
// Read sensors (LOW = black)
bool sx = (digitalRead(PIN_SX) == LOW);
bool c = (digitalRead(PIN_C) == LOW);
bool dx = (digitalRead(PIN_DX) == LOW);
if (c && !sx && !dx) {
// We are centered on the line
drive(baseSpeed, baseSpeed);
lastTurn = 0;
}
else if (sx && !dx) {
// Too far right: correct left
int left = max(baseSpeed - turnBoost, 0) - backNudge;
int right = min(baseSpeed + turnBoost, 255);
drive(left, right);
lastTurn = -1;
}
else if (dx && !sx) {
// Too far left: correct right
int left = min(baseSpeed + turnBoost, 255);
int right = max(baseSpeed - turnBoost, 0) - backNudge;
drive(left, right);
lastTurn = 1;
}
else if (sx && c && dx) {
// Intersection or large black area: keep straight
drive(baseSpeed, baseSpeed);
}
else {
// Line lost: search in the direction of the last correction
if (lastTurn = 0);
digitalWrite(inA, forward ? HIGH : LOW);
digitalWrite(inB, forward ? LOW : HIGH);
analogWrite(en, pwm);
}
void stopMotors() {
drive(0, 0);
}
How to adapt the code to your hardware
If the sensors return HIGH on black, replace the comparisons with the inverse (HIGH instead of LOW). Alternatively, just change the read line so the variables evaluate to true when they “see” the line. Also, tune baseSpeed and turnBoost based on weight, friction, motor quality, and power supply.
Tuning and debugging
Before testing on the track, lift the wheels off the ground and verify direction and speed differential. Then adjust the sensor trimmers so that on white the output stays HIGH and on black goes LOW (or vice versa), with a good margin. If the floor is very glossy, increase the sensor height or reduce sensitivity to avoid false positives.
Tip: add Serial prints to read sensor states and motor commands during the first tests. Remember that DC motors generate noise: heat-shrink tubing on the wires, capacitors on the armatures, and a good common ground improve stability.
Advanced variant: PID control with 5 sensors
With five analog sensors (A0–A4) you can compute a continuous position error and apply a PID. This makes corrections smooth and allows higher speeds without zig-zagging.
// Conceptual PID scheme with 5 analog sensors (A0..A4)
const int sPins[5] = {A0, A1, A2, A3, A4};
int weights[5] = {-2, -1, 0, 1, 2};
float Kp = 28.0, Ki = 0.0, Kd = 14.0;
int baseSpeed = 150;
float integral = 0, lastError = 0;
void loop() {
long sumWeighted = 0;
long sumValues = 0;
for (int i = 0; i 0) {
position = (float)sumWeighted / (float)sumValues; // about -2..+2
}
float error = 0 - position;
integral += error;
float derivative = error - lastError;
lastError = error;
float correction = Kp*error + Ki*integral + Kd*derivative;
int left = constrain((int)(baseSpeed + correction), 0, 255);
int right = constrain((int)(baseSpeed - correction), 0, 255);
drive(left, right);
}
To tune the PID, start with Ki at zero, increase Kp until the robot oscillates, then increase Kd to dampen it. Add Ki only if you observe long-term errors (steady drift). Remember that good mechanics and stable sensors matter as much as the controller constants.
Other variants and upgrades
More sensors and dedicated arrays
An array like the Pololu QTR-8A/RC offers up to eight elements, uniform readings, and calibration functions. More sampling points improve the estimate of the line’s position.
Intersection handling and path logic
You can detect intersections by reading specific patterns (for example all sensors dark) and applying a policy: always left, always right, or follow a programmed sequence of turns.
Speed modes and pit stop
Add a selector or a button to choose between “slow,” “normal,” and “turbo” modes. In “turbo,” increase baseSpeed and lighten the correction for wide tracks; in “slow,” do the opposite for narrow tracks.
Communication and telemetry
With a BLE or serial Bluetooth module you can log sensor values in a phone app, vary PID parameters in real time, and receive diagnostics during tests.
Power and mechanics
Use a 2S LiPo with a 5 V step-down regulator for Arduino and sensors. Keep the sensors 2–4 mm from the ground and aligned; good base geometry and balanced wheels reduce oscillations.
Quick troubleshooting
“Drunk” robot that weaves: decrease turnBoost or increase Kd in the PID. Robot that doesn’t see the line: adjust sensor trimmers and revisit the height. Weak motors: check the battery and driver wiring, ensure ENA/ENB receive PWM. Unstable readings: shield the sensor cables and separate power and signal grounds (star to common GND).
Conclusion
Building a line follower is the ideal training ground for those who want to move from theory to practice. With three sensors and a simple algorithm you can already achieve satisfying results; with five sensors and a well-tuned PID, the project becomes surprisingly capable. The key is to proceed iteratively: solid mechanics, tidy wiring, precise tuning, and tests on progressively more complex tracks.
Get your project rolling
Try the proposed wiring, upload the code, and start experimenting right away. Then tell us in the comments how it went, what changes you made, and what tracks you tackled. Need help with tuning or want to share your PID variant? Write to us: it will be a pleasure to dive deeper together and improve the project step by step.

Comments