Build Your Line Following Robot
The Story
ESP32 Line Following Robot reads two IR reflectance sensors, compares each sensor with its calibrated line threshold, and drives the left and right motor-driver inputs so the chassis can steer back toward the track.
The important lesson is not only the finished line-following robot. You learn to record raw GPIO34/GPIO35 values, choose separate thresholds for the actual floor and line, then test motor direction with the wheels lifted before a floor run.
Explain Like I'm 12
Think of the ESP32 as the brain. The left and right IR sensors are its eyes looking at the floor. The motor driver is the muscle that turns the wheels. The code reads both eyes, decides where the dark line is, and nudges the robot back onto the track.
Safety Standards
- Unplug USB and the motor supply before changing IR sensor or motor-driver wiring.
- ESP32 GPIO pins provide control signals only; never power DC motors directly from a GPIO pin or the 3.3 V pin.
- Power the motors through the dual H-bridge driver from a suitable low-voltage motor supply.
- Share a ground/reference between the ESP32 and the driver control side when your module requires it.
- Test with the wheels lifted before floor runs because motor startup current can reset the ESP32 if the supply is weak.
What You Will Build
A working ESP32 line following robot that reads two analog IR reflectance sensors, calibrates separate left and right thresholds, drives a dual H-bridge motor driver, and prints raw sensor readings in Serial Monitor.
Learning Objectives
- Wire analog IR sensor outputs to GPIO34 and GPIO35 and print raw ADC readings.
- Calibrate separate left and right thresholds from the actual track surface.
- Map each signal to a named ESP32 GPIO and keep the code constants readable.
- Control a dual H-bridge motor driver on GPIO16-GPIO19 using simple two-sensor steering logic.
- Use Serial Monitor as an engineering tool, not only as a success message.
- Identify sensor, steering, motor direction, and power faults using a repeatable test checklist.
Components List
- ESP32 DevKit boardReads analog sensors and commands the motor driver
- Two analog IR reflectance sensor modulesLeft and right line sensors
- Pololu TB6612FNG dual motor driver carrier (#713)Reference carrier; VCC at 3.3 V, separate motor supply, enable pins wired as shown
- Breadboard and jumper wiresPrototype wiring
- USB data cableProgramming and testing
- Two matched low-power DC gearmotors, chassis and motor supplyUse motors rated for the chosen 4.5-6 V supply, with documented stall current within carrier limits
Bill of Materials
| Part | Qty | Estimated Cost | Notes |
|---|---|---|---|
| ESP32 DevKit | 1 | $6-$10 | USB board |
| Analog IR reflectance sensor modules | 2 | $2-$10 | Use analog AO outputs for this build |
| TB6612FNG carrier (Pololu #713 reference) | 1 | Check vendor | Use this documented interface, not an assumed L298N pin-for-pin replacement |
| Breadboard and wires | 1 set | $3-$5 | Prototype wiring |
| Two DC gearmotors, chassis and switched motor supply | 1 set | Varies | Match motor voltage and stall current to the carrier and supply; original estimate excludes this set |
Wiring
This reference circuit uses a Pololu TB6612FNG carrier (#713) and a classic ESP32-WROOM board with GPIO16/17 free. It is a logical connection map, not a physical header layout or a hardware-tested build. L298N modules need their own enable and supply wiring.
-
1
Disconnect USB and the separate motor supply before wiring. Leave motor power disconnected during sensor calibration.
-
2
Use documented 3.3 V-compatible analog reflectance modules. Connect their supply to 3V3 and grounds to GND; left AO to GPIO34, right AO to GPIO35. Do not use a 5 V AO signal or substitute DO-only modules.
-
3
Connect carrier VCC to ESP32 3V3 and all signal grounds together. VCC is the logic supply; VMOT is the separate motor supply.
-
4
Connect GPIO16 to AIN1, GPIO17 to AIN2, GPIO18 to BIN1 and GPIO19 to BIN2. This WROOM example is not for WROVER boards reserving GPIO16/17.
-
5
Connect PWMA, PWMB and STBY to the 3.3 V logic rail for this full-speed direction-only sketch. They must not float. There is no software PWM speed control or software standby in this example.
-
6
Connect the left motor to AO1/AO2 and the right motor to BO1/BO2. Motor mounting may require swapping that motor pair to make the forward command move forward.
-
7
With power off, connect the switched motor supply positive to VMOT and negative to carrier GND. Use a motor-rated 4.5-6 V supply and compatible small motors. Verify documented stall current against the carrier rating (1 A continuous per channel); do not design around its brief peak-current number. Keep motor current out of ESP32/breadboard signal rails.
-
8
With only USB on, print line/floor readings and set both thresholds and sensor polarity. The loop already issues motor commands; motor supply stays off during calibration.
-
9
Lift the wheels before enabling motor power and keep its switch accessible. Hard-wired STBY does not provide a reset-time motor interlock. Verify start, steering and stop commands before floor testing.
GPIO Mapping
| Signal | ESP32 Pin | Direction | Notes |
|---|---|---|---|
| Left / right sensor AO | GPIO34 / GPIO35 | Analog input | 3.3 V-compatible driven AO; no DO substitution |
| AIN1 / AIN2 (left) | GPIO16 / GPIO17 | Output | Classic WROOM; verify pins are exposed and free |
| BIN1 / BIN2 (right) | GPIO18 / GPIO19 | Output | Direction commands from existing sketch |
| VCC, PWMA, PWMB, STBY | 3V3 logic rail | Power / enable | All four tied to logic supply; enables are not left floating |
| VMOT | Separate switched motor supply + | Motor power | 4.5-6 V, matched motors and current limits; never ESP32 3V3 |
| Carrier / sensors / supply negative | Common GND | Ground | Motor return runs to carrier/supply, not through ESP32 signal wiring |
| AO1/AO2; BO1/BO2 | Left motor; right motor | Driver outputs | Do not connect motor leads to ESP32 GPIO |
Circuit Explanation
The core build assumes two compatible IR reflectance modules using their analog AO outputs. The left sensor AO goes to GPIO34 and the right sensor AO goes to GPIO35. On the classic ESP32, GPIO34 and GPIO35 are input-only ADC1 pins, which makes them suitable for sensor inputs. GPIO34-GPIO39 do not provide internal pull-up or pull-down resistors on the classic ESP32, but this analog sensor build normally does not need internal pulls because the module drives an analog output voltage.
If your module exposes only a digital DO output, use a different sketch that reads HIGH/LOW with digitalRead(). This tutorial is teaching analog calibration with analogRead().
The selected TB6612FNG carrier uses GPIO16/17 for AIN1/AIN2 and GPIO18/19 for BIN1/BIN2. Logic VCC, PWMA, PWMB and STBY connect to 3V3. Motor power enters VMOT separately; left and right motors connect to AO1/AO2 and BO1/BO2. Hard-wired PWM inputs enable full-speed direction control; this sketch does not set motor speed. L298N wiring is not interchangeable.
ESP32 GPIO pins provide control signals only. Do not power DC motors directly from a GPIO. Power motors through the driver from an appropriate low-voltage motor supply, and share a ground/reference between the ESP32 and driver control side when your module requires it. Motor startup current can reset the ESP32 if power is poorly designed.
Engineering Explanation
Calibrate before driving. Upload the sketch with the robot lifted so the wheels cannot run away. Record LEFT and RIGHT raw readings over the dark line, then over the light background, at the actual sensor mounting height. Choose LEFT_THRESHOLD and RIGHT_THRESHOLD roughly between each sensor's dark-line and light-floor readings, then re-test under the room lighting where the robot will run.
The value 1800 is only a starter value. Real readings vary with sensor module, mounting height, surface color, glossy or matte material, ambient light, and individual sensor variation. The two sensors may not match, so separate thresholds are safer than one universal number.
Steering table: left LINE and right LINE means drive forward. Left LINE and right FLOOR means the line is under the left sensor, so stop the left motor and run the right motor to correct left. Left FLOOR and right LINE means stop the right motor and run the left motor to correct right. FLOOR/FLOOR means stop because the line is lost.
Motor orientation varies by chassis. If the robot corrects away from the line, reverse one motor direction or swap the relevant driver outputs after confirming the sensor readings are correct.
Code
Copy into Arduino IDE. Install any libraries noted in the component guides first.
const int LEFT_SENSOR = 34;
const int RIGHT_SENSOR = 35;
const int L_IN1 = 16;
const int L_IN2 = 17;
const int R_IN1 = 18;
const int R_IN2 = 19;
// Calibrate these from your own dark line and light floor readings.
const int LEFT_THRESHOLD = 1800;
const int RIGHT_THRESHOLD = 1800;
// Set false if your sensors produce lower values on the dark line.
const bool LINE_IS_HIGH = true;
bool isOnLine(int value, int threshold) {
return LINE_IS_HIGH ? value > threshold : value < threshold;
}
void leftMotor(bool forward) {
digitalWrite(L_IN1, forward ? HIGH : LOW);
digitalWrite(L_IN2, forward ? LOW : HIGH);
}
void rightMotor(bool forward) {
digitalWrite(R_IN1, forward ? HIGH : LOW);
digitalWrite(R_IN2, forward ? LOW : HIGH);
}
void stopLeftMotor() {
digitalWrite(L_IN1, LOW);
digitalWrite(L_IN2, LOW);
}
void stopRightMotor() {
digitalWrite(R_IN1, LOW);
digitalWrite(R_IN2, LOW);
}
void stopMotors() {
stopLeftMotor();
stopRightMotor();
}
void setup() {
Serial.begin(115200);
analogReadResolution(12);
pinMode(L_IN1, OUTPUT); pinMode(L_IN2, OUTPUT);
pinMode(R_IN1, OUTPUT); pinMode(R_IN2, OUTPUT);
stopMotors();
Serial.println("ESP32 line follower ready");
Serial.println("Record raw values over LINE and FLOOR before running motors.");
}
void loop() {
int leftValue = analogRead(LEFT_SENSOR);
int rightValue = analogRead(RIGHT_SENSOR);
bool leftOnLine = isOnLine(leftValue, LEFT_THRESHOLD);
bool rightOnLine = isOnLine(rightValue, RIGHT_THRESHOLD);
if (leftOnLine && rightOnLine) {
leftMotor(true);
rightMotor(true);
} else if (leftOnLine && !rightOnLine) {
stopLeftMotor();
rightMotor(true);
} else if (!leftOnLine && rightOnLine) {
leftMotor(true);
stopRightMotor();
} else {
stopMotors();
}
Serial.printf("L:%4d %s | R:%4d %s\n",
leftValue, leftOnLine ? "LINE" : "FLOOR",
rightValue, rightOnLine ? "LINE" : "FLOOR");
delay(40);
}
Code Explanation
The sketch reads raw ADC values first: leftValue from GPIO34 and rightValue from GPIO35. It converts those readings into leftOnLine and rightOnLine using LEFT_THRESHOLD, RIGHT_THRESHOLD, and LINE_IS_HIGH.
Do not assume every IR module reports the same polarity. If your dark line gives lower readings than the floor, set LINE_IS_HIGH to false instead of rewriting the steering logic.
Serial Monitor prints both the raw numbers and the interpreted state, for example "L:2350 LINE | R: 900 FLOOR". The motor code then follows the same four-row state table explained above.
Expected Output
Serial Monitor should show raw left and right analog readings plus LINE or FLOOR labels, such as "L:2350 LINE | R: 900 FLOOR".
With both sensors on the line the robot moves forward. With one sensor on the line it corrects toward that side. With both sensors on the floor it stops because the line is lost.
Troubleshooting
- Both sensors always read the same Confirm the left AO wire goes to GPIO34 and the right AO wire goes to GPIO35, then test each sensor over the line and floor separately.
- Sensor readings barely change between black and white Adjust sensor height, improve track contrast, avoid glossy material, and test under the same room lighting used for driving.
- Robot turns the wrong direction If left LINE / right FLOOR makes the robot turn away from the line, swap the left/right sensor wires or reverse the correction actions.
- Robot oscillates left and right Calibrate separate LEFT_THRESHOLD and RIGHT_THRESHOLD values, slow the robot mechanically, or add PWM speed control later.
- Robot loses the line on sharp curves Use wider curves, lower motor speed as an upgrade, and keep the sensors close to the floor but not scraping.
- Readings change when room lighting changes Re-test thresholds under real lighting, shade the sensors from direct sunlight, and avoid shiny track surfaces.
- One motor spins backwards Reverse that motor's two output wires or swap its two motor-driver direction inputs; motor orientation varies by chassis.
- Motors run but ESP32 resets Power motors through the driver from a suitable low-voltage motor supply and use common ground only as required by the module.
- Robot works while lifted but fails on the floor Recheck traction, battery voltage under motor load, sensor height at driving height, and threshold values measured on the actual floor.
Common Mistakes
- Using the digital DO pin from the IR module while the sketch expects analog AO on GPIO34/GPIO35.
- Treating LEFT_THRESHOLD and RIGHT_THRESHOLD starter values as universal instead of calibrating each sensor.
- Expecting an ESP32 GPIO to power a DC motor directly.
- Forgetting the shared ground/reference between ESP32 and the motor driver control side.
- Testing floor movement before raw sensor readings and motor direction are verified.
Testing Checklist
- Keep the switched motor supply OFF while collecting ADC calibration readings; the sketch issues motor commands immediately in loop.
- ESP32 appears on the correct port and accepts a basic blink upload.
- Ground is shared between every module that exchanges signals with the ESP32.
- Each GPIO in the code matches the wire connected on the breadboard.
- Serial Monitor prints startup text at 115200 baud.
- Raw left and right ADC readings are recorded over both dark line and light background before floor testing.
- LEFT_THRESHOLD and RIGHT_THRESHOLD are set between each sensor's measured line and floor values.
- LINE_IS_HIGH matches the actual sensor polarity seen in Serial Monitor.
- The dual H-bridge direction inputs match GPIO16/GPIO17 for the left motor and GPIO18/GPIO19 for the right motor.
- The robot drives forward on LINE/LINE, corrects left or right on single-sensor line detection, and stops on FLOOR/FLOOR.
- The motor supply does not reset the ESP32 when the wheels start.
- The circuit still behaves correctly after power is removed and restored.
- Verify VCC/PWMA/PWMB/STBY at 3.3 V, separate VMOT supply, common GND and all motor terminal connections against the selected carrier labels.
Upgrade Ideas
- Add PWM speed control after the steering logic works.
- Show raw left/right sensor values on an OLED for debugging.
- Add buttons or stored settings for calibration.
- Try PID control later with more sensors, after the two-sensor robot is reliable.
Real-World Applications
- Classroom line-following robot trainer
- STEM lab calibration demonstration
- Robotics steering logic practice
- Motor driver wiring exercise
- Beginner robotics portfolio project
Downloads
- Download the Arduino sketch (.ino)
Same code as the complete sketch on this page. - Wiring steps
On-page connection instructions. - Testing checklist
On-page checks to perform on your build. - Open wiring map full size (SVG)
Enlarge the logical connection map; it is not a physical header layout.
FAQs
Why does my ESP32 line follower threshold not work?
The starter value is not universal. Print raw GPIO34/GPIO35 readings over the dark line and light floor, then choose separate LEFT_THRESHOLD and RIGHT_THRESHOLD values between your measured readings.
Can I use digital DO outputs instead of analog AO outputs?
Only with different code. This project uses analogRead() on GPIO34 and GPIO35 so you can calibrate raw sensor values. DO-only modules require digitalRead() logic.
Why does the robot turn the wrong way?
First confirm the left and right sensor readings in Serial Monitor. Then reverse one motor's direction or swap the relevant motor-driver outputs because chassis wiring and motor orientation vary.
Why does the motor driver not respond?
Confirm shared ground/reference, motor supply, and GPIO16-GPIO19 direction wiring. The ESP32 GPIO pins control the driver; they do not power the motors directly.
Why does the robot reset when motors start?
Motor startup current can pull the supply down. Use a separate motor supply with common ground and test sensor readings before enabling movement.
Review, Testing, and References
Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-11-03. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.
Educational level: Intermediate. Estimated completion time: 90-150 min. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.
Check your result
Before treating this example as working on your hardware, compare the observed behavior with Expected Output and complete the checks on this page. If results differ, use Troubleshooting. Reading this tutorial does not establish successful compilation or hardware operation.
- Wire and test left and right IR line sensors
- Control motor driver from ESP32
- Debug hardware with Serial Monitor
- Improve the project safely

