The Line Follower


The line follower has 2 sensors which can detect a white surface (within the range of 1-2cm). It works by emitting IR (InfraRed) light and recording how much is reflected back. If a lot is reflected back, it can be deduced it is close to a white surface. If a little is reflected back, it can be deduced that the surface is black, or the sensor is not near a surface.

A light surface reflects a lot of infrared light back to the receiver:


A dark surface only reflects a little light back to the receiver:


In mBlock there are 2 blocks associated with the line follower:


The first block will return a number between 0 and 3 based on the following values:


The second block will return either true or false.

Using the “Line Follower” block to program:

If we want to have our robot follow a black line, we have the following pseudocode:

If( line follower = 0)
---- Go forward
Else if (line follower = 1)
---- Turn Left
Else if(line follower = 2)
---- Turn Right
Else if(line follower = 3)
---- Aaargh!! Help!! Where is the line?

So let’s now put that into mBlock code:


And it doesn’t work – the robot often goes off the track. This is because this program is run from the mBlock IDE. Remember it takes time for the signals and commands to be sent from the robot to the computer and back again. In this case, that delay interferes with how the robot performs the line following. We need to upload this program onto the board to reduce this delay. Then the program will work. For the mBot, we use the “mBot program” block, go into Arduino mode and “Upload to Arduino”:


Now the robot successfully follows the line.

Using the “Line Follower (port)(side)Is(Black/White)” block to program:

Using this block:

If((Right is black) AND (Left is black))
---- Go forward
Else if((Right is white) AND (Left is black))
---- Turn Left
Else ((Right is black) AND (Left is white))
---- Turn Right
Else ((Right is white) AND (Left is white))
---- Aaargh!! I’m lost AGAIN?!?

So for this we need an “and” block to combine the 2 conditional statements:


So the final code looks like this:



  1. The robot moves does not turn smoothly. Why is that? Can you fix it?
  2. Can you write a program so the robot moves around a (white) table in a random fashion without falling off? (Remember the line follower sensor detects if light is reflected – or not reflected)
  3. Can you write a program that follows a line AND avoids objects – if an obstacle is detected, the robot should stop the motors and wait for the object to be removed.

Construct Your Dreams!