Robotics/electronics

Line-Following Robot

Use two reflectance sensors and differential motor control to follow a high-contrast tabletop track.

The robot never knows the whole route. It repeatedly measures the line under two sensors and makes small steering corrections, turning feedback into smooth motion.

Difficulty
Advanced
Build time
140-220 min
Estimated cost
$0-$45
Age range
13-18
Workspace
A clear table about 90 cm wide

The finish line

What you will build

The robot completes a 3-metre high-contrast loop twice without leaving the line for more than one second.

Learning goals

  • Identify how left and right reflectance measurements produces differential wheel-speed corrections.
  • Construct and explain a sensor feedback-to-steered vehicle motion system.
  • Measure how proportional gain changes performance.
  • Diagnose losses caused by wheel slip and sensor noise.

Before you build

Materials, tools, and safety

Reuse-material cost: Usually under $5 with an existing kit. Supervision: Adult guidance recommended for wiring and cutting.

Tools

  • Small screwdriver
  • Wire stripper
  • Multimeter
  • Low-temperature glue gun or tape

Low-cost swaps

  • Use alligator-clip leads for a no-solder version.
  • Build and test the mechanism manually before adding electronics.
  • Use a classroom line-follower kit while calibrating and writing the control logic yourself.

Wiring table

FromToPurpose
Battery +H-bridge motor supplyPower motors within rated voltage
All groundsController, driver, sensors, battery negativeCreate common reference
Sensors outputsAnalog A0 and A1Measure left and right reflectance
Controller PWM 5 and 6H-bridge speed inputsSet left and right wheel speed
Controller direction pinsH-bridge direction inputsCommand forward motor polarity

Project-specific safety

  • Use only the listed low-voltage battery supply; never use mains electricity.
  • Disconnect power before changing wires and stop if a motor, wire, or battery becomes warm.
  • Use low voltage, support the robot during first motor tests, protect sensors from short circuits, and stop if any motor, driver, or battery warms.

Orient the build

Place the build so left and right reflectance measurements is on your left and differential wheel-speed corrections is on your right. Call the side facing you the front, the far side the back, the tabletop the bottom, and the opposite face the top.

Build it

Step-by-step instructions

  1. Step 1

    Build a straight rover

    Align both axle centers and match wheel diameters.

    Roll unpowered through a 1-metre lane.

  2. Step 2

    Mount the sensor bar

    Place sensors 15-25 mm apart and 5-10 mm above the floor.

    Keep them ahead of the wheel axle.

  3. Step 3

    Wire the motor stage

    Connect motors through the H-bridge and use common ground.

    Do not power motors from controller pins.

    Builder checkpoint: After wire the motor stage, the first subassembly should stay aligned when handled gently.

  4. Step 4

    Wire and inspect sensors

    Connect each sensor at its rated voltage and route outputs to A0 and A1.

    Add strain relief.

    Watch for: If this stage binds or drifts, inspect control delay before adding more parts.

  5. Step 5

    Calibrate surfaces

    Read 100 samples over line and background for each sensor.

    Choose midpoint thresholds or normalized ranges.

  6. Step 6

    Test motor matching

    Command equal low PWM with wheels raised, then on a straight lane.

    Record drift and apply a small trim.

    Builder checkpoint: After test motor matching, operate the build slowly and confirm that differential wheel-speed corrections begins without binding.

  7. Step 7

    Tune proportional steering

    Start with low base speed and correction gain.

    Increase gain until turns work without rapid oscillation.

  8. Step 8

    Run full-loop trials

    Complete two loops and log line-loss locations.

    Change only speed or gain between tests.

    Builder checkpoint: At the final checkpoint, The robot completes a 3-metre high-contrast loop twice without leaving the line for more than one second.

See the engineering

Why it works

Input
left and right reflectance measurements
Output
differential wheel-speed corrections
Motion
sensor feedback-to-steered vehicle motion
Energy losses
wheel slip, sensor noise, motor mismatch, control delay
Line-Following Robot concept diagram with labeled input, output, and motion arrows.
The sensor feedback-to-steered vehicle motion motion path, with the main efficiency losses called out.

Why this works

Closed-loop line control

The controller compares left and right reflectance. Their difference becomes a steering error, and proportional correction speeds one wheel while slowing the other.

Look for: Print or display raw sensor values over white and black surfaces before choosing a threshold or gain.

Where the energy goes

Efficiency and losses

The ideal model leaves out wheel slip, sensor noise, motor mismatch, control delay. These effects turn some input energy into heat, sound, vibration, or unwanted motion, so measured performance will be lower than an ideal calculation.

Look for: Run the build slowly and locate the first place where wheel slip becomes visible or audible.

Math bite

Normalize a sensor reading

Formula: normalized = (reading - white) / (black - white)

  • Reading = 600
  • White = 200
  • Black = 800

Substitute: normalized = (600 - 200) / (800 - 200) = 0.67

Result: The reading is about two-thirds of the calibrated dark range.

Normalization lets mismatched sensors use a comparable scale.

Lighting and sensor height can shift endpoints.

line_follower.ino

A complete two-sensor proportional controller. Set calibration values from your own readings before running.

const int leftSensor=A0, rightSensor=A1;
const int leftPwm=5, rightPwm=6, leftDir=7, rightDir=8;
const int whiteL=220, blackL=810, whiteR=205, blackR=790;
const int baseSpeed=105; const float gain=85.0;
float normalized(int value,int whiteValue,int blackValue){
  return constrain((float)(value-whiteValue)/(blackValue-whiteValue),0.0,1.0);
}
void setup(){
  pinMode(leftPwm,OUTPUT); pinMode(rightPwm,OUTPUT);
  pinMode(leftDir,OUTPUT); pinMode(rightDir,OUTPUT);
  digitalWrite(leftDir,HIGH); digitalWrite(rightDir,HIGH);
}
void loop(){
  float left=normalized(analogRead(leftSensor),whiteL,blackL);
  float right=normalized(analogRead(rightSensor),whiteR,blackR);
  int correction=(int)(gain*(left-right));
  analogWrite(leftPwm,constrain(baseSpeed-correction,0,200));
  analogWrite(rightPwm,constrain(baseSpeed+correction,0,200));
  delay(8);
}
Brick-building meme reading: Chuck Norris does not build LEGO; he roundhouses the bricks into sculptures.
The robot followed the line perfectly until the tape corner offered a philosophical question.Image supplied by the site owner.

Make it behave

Test, troubleshoot, and tune

Controlled test

Start here: Calibrate sensor values with motors disconnected.

Success looks like: The robot completes two 3-metre loops without a line loss longer than one second.

Measure: Lap time, line losses, steering oscillation, and sensor ranges.

Change: proportional gain

Keep constant: track, lighting, sensor height, base speed, battery, and tires

  1. low gain
  2. medium gain
  3. higher stable gain
Troubleshooting guide
SymptomLikely causeConfirm itFix
It drives off on curvesGain is low, speed high, or sensors too closeReview readings at curve entryLower speed, raise gain, or widen sensor spacing
It wiggles rapidlyGain is too high or delay too longRun on a straight lineReduce gain and loop delay
One side always winsMotors or sensors are mismatchedSwap sensor positions and retestNormalize sensors and add motor trim
Values change with room lightSensor shielding or height is poorCover with a paper hoodAdd shielding and recalibrate

Choose your tradeoff

Calibrate at the actual sensor height and lighting before changing control gain. Faster base speed shortens reaction time and requires cleaner sensing and stronger correction.

Keep experimenting

Try another version

Easier

Bang-bang control

Use three states: left, right, and forward.

Performance

Fastest clean lap

Penalize every line loss.

Advanced

PID control

Add derivative damping and compare oscillation.

Build together

Classroom and access options

Classroom version

Teams can compare proportional gain while keeping track, lighting, sensor height, base speed, battery, and tires. Assign builder, tester, recorder, and explainer roles; have each team predict the result before collecting three trials.

Access adaptations

  • Color-code and label every wire at both ends.
  • Use clip leads, larger controls, and pre-crimped connectors when fine motor work is difficult.
  • Use a wide 4 cm line, color-and-tactile wire labels, and serial calibration output with large text.

Reflect on the design

  1. How did proportional gain change the measured result?
  2. Where did wheel slip affect the build most strongly?
  3. What evidence shows that closed-loop line control explains the motion?
  4. Which change would improve differential wheel-speed corrections without creating a new problem?
Glossary
Closed-loop line control
The controller compares left and right reflectance.
Input
The action or energy supplied to a system; here it is left and right reflectance measurements.
Output
The useful response produced by a system; here it is differential wheel-speed corrections.
Efficiency
The fraction of input energy that becomes useful output instead of friction, sound, heat, or unwanted motion.

Build your dreams

One build can start the next.

Share what you learned, change one variable, and help another builder understand what worked.

Explore more guides

Sources and build notes

A platform-agnostic low-voltage robotics or electronics project with original assembly guidance.

  • Low-voltage design review: Battery voltage, polarity, component roles, current paths, and motor or LED protection were editorially checked.

Written and edited by BrickLabClips. Published 2026-07-22; updated 2026-07-22.

Next builds

Related guides