Home · Academy · Robotics & Coding · Robotic Systems · Line Following

Line Following

Learn the control logic for following a line with two line sensors.

LESSON COMPASS

What will you use this page for?

Core idea

Line following is when a robot uses two infrared sensors to see a dark line on the floor and adjusts its left and right motor speeds to travel along that line.

Evidence to produce

Complete the page task with your own input, test conditions and reasoning.

Control trap

Assuming the sensor logic backwards Not every module gives the same 1 and 0 values. Some report 1 on the line, others 0 . Before writing code, test the sensor over the line and over white, and note which value it gives. Mixing up left and right turns Turning left when the left sensor sees the line feels wrong at…

Next connection

Robot Arm Logic: We look at how each joint of a jointed robot arm is controlled and the steps for gripping and releasing an object.

Module sources: Python Tutorial · Arduino Learn

LevelBeginner
Age10–16
Duration35–50 min
PrerequisiteObstacle Detection
ContentIn-depth guide · 2,125 words
Last updated

One-sentence summary

Line following is when a robot uses two infrared sensors to see a dark line on the floor and adjusts its left and right motor speeds to travel along that line.

Why it matters

In the previous lessons we taught the robot to detect an obstacle in front of it with a distance sensor. Now we take the robot one step further: instead of just stopping, it will follow a path that has been drawn for it.

Line following is the most classic task in robotics competitions. But it is not only for contests; robots that carry boxes in factories and vehicles that move between shelves in warehouses also follow marks on the floor with a similar idea.

This lesson brings together the heart of the whole module: the sense – decide – act loop. The sensor detects the line, the program makes a decision, and the motors turn that decision into movement.

How does an infrared line sensor work?

Surfaces that reflect or absorb light

An infrared (IR) line sensor sends invisible infrared light down to the floor and measures how much light bounces back. The trick is in the colour of the surface:

So the sensor does not really measure colour; it measures how much light is reflected. It is like a flashlight looking bright on white paper but dim on black velvet.

Most line sensors give the result as a simple digital signal: 1 when over the line, 0 when over the white floor (on some modules it is the other way around, so always test your own module).

Using two sensors to know "where we are"

A single sensor can tell you whether it sees the line, but not which way to turn. That is why we place two sensors under the front of the robot, one on each side of the line: one left, one right.

The two sensors have four possible situations:

Using two sensors to know "where we are" table
Left sensorRight sensorMeaningWhat to do
No lineNo lineRobot is centred on the line, both on whiteGo straight
LineNo lineRobot drifted right, line is on the leftTurn left
No lineLineRobot drifted left, line is on the rightTurn right
LineLineJunction or thick lineSpecial case

This logic can feel backwards at first: if the left sensor sees the line, we turn left. That is because if the left sensor is touching the line, the robot has drifted to the right of it; to re-centre we need to pull back to the left.

How do we turn? Adjusting motor speeds

Imagine a robot with two wheels, each driven by its own motor. There is no separate steering wheel; instead, we spin the two wheels at different speeds.

Think of a rowing boat: if you pull the right oar harder, the boat turns left. The robot works the same way:

This method is called differential drive. In sharp turns we almost stop one wheel, or even spin it backwards; for gentle corrections a small speed difference is enough.

Pseudocode: basic line following

First let us write the logic in pseudocode, close to everyday language:

Repeat forever
  left  = read left sensor
  right = read right sensor

  If left is white and right is white
    drive both motors forward at medium speed   (go straight)
  Else if left is line and right is white
    turn left (slow the left motor)
  Else if left is white and right is line
    turn right (slow the right motor)
  Else
    handle junction or lost situation

This pseudocode stays the same no matter which programming language we move to. Now let us translate it into Arduino.

Arduino example

The example below uses two line sensors and a motor driver (for example an L298N). We set the motor speed with PWM through analogWrite:

const int LEFT_SENSOR  = 2;   // left IR sensor
const int RIGHT_SENSOR = 3;   // right IR sensor
const int LEFT_MOTOR   = 5;   // left motor speed (PWM)
const int RIGHT_MOTOR  = 6;   // right motor speed (PWM)

const int FAST = 160;         // 0-255 range
const int SLOW = 60;

void loop() {
  int left  = digitalRead(LEFT_SENSOR);   // 1 = line seen
  int right = digitalRead(RIGHT_SENSOR);

  if (left == 0 && right == 0) {           // both white
    analogWrite(LEFT_MOTOR, FAST);
    analogWrite(RIGHT_MOTOR, FAST);        // go straight
  } else if (left == 1 && right == 0) {    // line on the left
    analogWrite(LEFT_MOTOR, SLOW);
    analogWrite(RIGHT_MOTOR, FAST);        // turn left
  } else if (left == 0 && right == 1) {    // line on the right
    analogWrite(LEFT_MOTOR, FAST);
    analogWrite(RIGHT_MOTOR, SLOW);        // turn right
  }
}

Note: this example only shows the speed pins. On a real robot you also need to set the pins that decide the motor direction (forward/back) inside setup(). Do not trust these 1/0 values until you have measured what your own module reports.

Hard cases: junctions and getting lost

On real tracks two special situations confuse the robot.

Both sensors see the line

This is usually a junction or a thick marker line. On a simple robot the decision is easy: keep going straight. On more advanced robots we might apply a turn decision that was planned in advance.

No sensor sees the line (getting lost)

If the robot leaves the line completely, both sensors see white. In the simple code above, this situation gets confused with "go straight," and the robot gets lost. A well-known way to fix this is to remember the last direction the line was seen:

If both sensors are white
  If I last saw the line on the left
    turn left in place to search for the line
  Else
    turn right in place to search for the line

So when the robot loses the line it does not move randomly; it remembers which way it last drifted and turns that way to find the line again. If it still cannot find it after a while, stopping the motors for safety is a good idea.

Why not connect the motor straight to the Arduino?

This is one of the most common questions with a line-following robot.

Arduino pins can only supply a very small current (a few milliamps per pin). A DC motor draws hundreds of milliamps when starting. If you connect the motor straight to a pin, you will damage the Arduino.

That is why we put a motor driver (for example an L298N) in between. The Arduino sends the driver a weak signal that says "go forward at this speed"; the driver then delivers the real power to the motors from a separate battery pack.

Two important rules:

Mini practice

An exercise you can do with parts or entirely on paper.

  1. Draw a gently curving path with black tape on white cardboard. Use arcs instead of sharp corners; simple robots miss sharp turns.
  2. Fill in the table below: what should the robot do in each case? For each row, write the left motor and right motor speed as "fast / slow / stop."
Mini practice table
Left sensorRight sensorLeft motorRight motor
whitewhite??
linewhite??
whiteline??
lineline??
  1. Imagine the robot has left the line for a moment. Write the "remember the last direction" logic as a three-step pseudocode in your own words.
  2. Suppose you observe the robot moving forward while constantly wobbling left and right (zigzagging). Which value could you change to reduce this wobble? (Hint: look at the gap between FAST and SLOW.)

Common mistakes

Assuming the sensor logic backwards

Not every module gives the same 1 and 0 values. Some report 1 on the line, others 0. Before writing code, test the sensor over the line and over white, and note which value it gives.

Mixing up left and right turns

Turning left when the left sensor sees the line feels wrong at first. Think about which way is correct until the robot physically turns; if needed, push the robot by hand to test.

Forgetting the lost case

Coding only three situations (straight, right, left) and treating "both sensors white" as "go straight" makes the robot get lost when it leaves the line. Handle the lost case separately.

Setting the speed too high

Running the robot at full speed looks exciting, but a fast robot misses the turn and shoots off the line. Try a low speed first, then raise it little by little once it works.

Not powering the motors separately

Trying to power the motors from the Arduino's 5V pin is the most common electronics mistake. Motors must be powered from a separate battery pack, with a common ground.

Safety note

Lesson summary

Check questions

  1. Why does an infrared line sensor measure "little light" over a black line?
  2. If the left sensor sees the line and the right sensor sees white, which way should the robot turn and why?
  3. How does a robot turn without a steering wheel using "differential drive"?
  4. When both sensors see white, what information does the robot need to remember so it does not lose the line?
  5. Why do we use a motor driver and a separate battery instead of connecting a DC motor straight to an Arduino pin?

Answers

  1. Because dark surfaces absorb most of the infrared light, so little light bounces back to the sensor, and the sensor reads this as "I am over the line."
  2. It should turn left. If the left sensor is touching the line, the robot has drifted to the right of it; turning left re-centres it on the line.
  3. By spinning the two wheels at different speeds. When one side slows down and the other stays fast, the robot curves toward the slower wheel; no separate steering is needed.
  4. Which side (left or right) it last saw the line on. It remembers that direction and turns that way to search for the line again.
  5. Arduino pins cannot supply the current a motor draws and would be damaged. The motor driver takes the weak control signal and delivers power from a separate battery pack; thanks to the common ground, both circuits agree on the same zero point.

Source and verification note

For “Line Following”, verification focuses on whether the relationship between How does an infrared line sensor work? and Using two sensors to know "where we are" remains consistent across examples. Robot behaviour cannot be explained by code alone; mechanical structure, power system, sensor placement and surface conditions must be evaluated together. Test results should be recorded over several runs on the same course.

Next lesson

Robot Arm Logic: We look at how each joint of a jointed robot arm is controlled and the steps for gripping and releasing an object.

Start QuizBack to Robotic Systems
QUESTION POOL

Reinforce this lesson with 10 questions

This lesson has a pool of 20 questions. Each attempt selects 10 and reshuffles the choices.