Skip to content

Line following

Line following is a classic exercise for small autonomous vehicles and has a number of practical uses. Line following has been used for many years to control the movement of robots around automated factories, for example.

There are many ways to implement this behaviour, but for the purposes of this exercise we will be using a specially-designed sensor which consists of three pairs of infra-red emitter/receiver pairs. Information about the sensor can be found by following the links in the resources box. In order to get your line-follower working well you will need to go through several stages of development:

  • Install the appropriate libraries
  • Learn how to calibrate the sensor
  • Learn how to read values from the sensor
  • Develop a strategy for using the sensor reading to control the vehicle
  • Develop an integrated Arduino sketch which handles the calibration and control functions

Line following vehicle Line following vehicle. The line is detected by the absence of a reflection of IR light.

Controlling the vehicle

The pseudocode below provides the framework for writing your line follower control sketch. You will need to make use of your existing experience of other examples to complete it, and you will find that there are a number of significant challenges along the way.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    // Declare PID controller(s)

    setup()
    //    Set initial values of variables
    //    Start serial output
    //    Perform calibration

    loop()
    //    Take sensor readings
    //    Map raw readings onto a common range
    //    Compute control corrections for left and right motors
    //    Send signals to motors

While you are developing the sketch, please keep in mind the following good practice principles of software design:

  • Separation of concerns: Place the code for doing a particular task into its own function. This will make the high-level code such as the loop function easier to read, and it will make the whole sketch easier to maintain.

  • Use descriptive names for functions and variables: In the past, it was important to abbreviate names to save on memory space. This is no longer necessary, and using longer, descriptive names makes it easier to understand what the code is doing.

  • DRY: Don't Repeat Yourself - if you find you are writing more or less the same code more than once, try to parameterise it and put it into its own function.

Further reading

Pololu