An advanced line following robot with PID control

Overview


Photobucket

 

This tutorial details the process of building a line following robot. The robot can follow both black and white lines. It uses a sensor array to sense the line and a PID control to follow the line. With the help of a PID control the robot does not follow the line by oscillating to the left and to the right like conventional line followers but follows the line smoothly without wavering too much the left and right, conserving battery power while at the same time following the line much more faster.

Here is a video of the robot

 

Specifications and features

 

 

Note: This robot is aimed at intermediate robot builders who have built a robot or two and played quite a bit with microcontrollers. Building this robot will be quite a tough for a beginner, so if you have not built a robot before, try building the $40 robot, the $50 robot or any of the simple robots in the members tutorials section before trying to build this robot. I write this note because I have been getting a lot of mails from people who are trying to build this robot, without prior experience in robotics and have got stuck somewhere and have no clue about what is wrong or how to proceed.

 

Advanced Line Following Robot - Step 1: What it takes to build a fast line follower? Part: A

In this page I will be telling you what it takes to build a fast line follower. I will be talking about the design, steering mechanisms, sensors, algorithms, etc, which can be implemented.

Robot Design
The design of the robot plays an important role in deciding its speed and efficiency. The first thing you will want to decide in the design of your robot is the steering mechanism. The various steering mechanisms available are two wheel differential drive, four wheel differential drive, car-type steering mechanism, etc. From my experience, I can tell that two wheel differential drive is the best – it is easier to build, control and is cheap (requires only two motors).

Irrespective of the steering mechanism you use, the most important thing to keep in mind is to place the line sensors as far as possible from the steering wheel. This will give the robot, more time to react. Keeping the distance between the sensors and the steering wheel big, will largely reduce the number of over-shootings by the robot.

Photobucket
In my robot I kept the motor and the sensors at a distance of 12 cm

 

Another important thing is to keep the centre of mass as close to the ground as possible. This can be done by, placing all the heavy parts (batteries, motors) of the robot as close to the ground as possible. Keeping the centre of mass low will decrease the robot's moment of inertia enabling it to slow down quickly and then accelerate faster in curves. A robot with a high centre of mass will take a lot of time to slow down and a lot more time to accelerate afterwards owing to its high moment of inertia.

Sensors
Sensors are the first requirement in the process of line following. There are many sensors one can use for line following – IR LED and a Photodiode, LED and LDR (photoresistor), etc. When selecting the type of sensor there are three things you need to keep in mind – response time, sensitivity and ambient light protection.

LDRs (photoresistors) are excellent in terms of sensitivity, they can sense not only between two contrasting colours(one dark and one light) but also between two primary colours. Some competitions make the line following tougher by having a white line on a coloured surface (blue, red, grey). In such cases LDRs are the sensors to be used. But there is one big disadvantage in using LDRs - their slow responce time. A LDRs reaction time is around 0.1s. This may not seem much, but if you have a robot using LDRs following a line with a speed of 1 m/s then it will be getting data from the sensor every (0.1 * 1 = 0.1m) 10 cm !

IR LED and photodiodes give good response time. But they have two drawbacks, both of which can be dealt with – they can sense only between two contrasting colours and they are easily affected by ambient light.

Sensitivity can be improved in two ways. One by using LED which emits light of any other color other than the surface color and using a suitable photodiode to sense the light. Basically, if there is a white line on a red surface, you can use any other color LED, say green, to emit light and photodiodes which react to green colour. What happens is the surface, being red, absorbs all the green light emitted by the LED and no light reaches the photodiode. The line on the other hand, being white, reflects all the green light falling on it back to the photodiode. Using this method significantly increases the sensitivity of the sensors. Another way of improving sensitivity is by making modifications to the sensor circuit. Just by varying the resistance of some of the resistors in the sensor circuit, you can tune it to sense between two particular colors. Take a look at www.societyofrobots.com/schematics_infraredemitdet.shtm .

The second draw back, that is, interference from ambient light, is much more difficult to deal with. IR photodiodes detect light of a particular wavelength, which usually between 700 - 850 nanometers. Unluckily, the wavelength of most of the IR radiations around us fall in this range. To the photodiode these radiations are same as the IR radiations emitted by the IR LED, and hence they get falsely triggered by them. Even red light (which comes just beyond the IR radiations in the electromagnetic spectrum) can affect these sensors. There are many methods you can employ to protect IR sensors from interference from ambient light. One of the easiest method is to physically shield the sensors from ambient light. You can also use sensors that provide ambient light protection like the TSOP 17** sensors.

 

Photobucket
To protect the sensors from ambient light, my robots chassis is completely closed and the sensors are placed inside where they are shielded from any ambient light interference.

 

Algorithm
The algorithm is the one thing that determines the performance of your robot more than anything else. The most basic algorithm I know is the one which uses only one sensor. The sensor is placed in a position that is a little off centered to one of the sides, say right. When the sensor is detects no line the robot moves to the left and when the sensor detects the line the robot moves to the right. A robot with this algorithm would follow the line like shown in the picture below

Photobucket

The drawback of this method is that the line following is not smooth. The robot keeps wavering left and right on the track, wasting battery power and time. A modification to this method is to add sensors on both sides of the robot and place them such that they just sense the line on either side. And the algorithm would be to move forward if both the sensors sense the line or to move left if only the left sensor senses the line and move right if only the right sensor senses the line. A robot with this algorithm would follow the line like shown in the picture below

Photobucket


This algorithm is faster than the previous algorithm but the robot will still wobble about the line and may not be fast enough.

A much better algorithm is to use the PID to follow the line. This will make line following process much more smoother, faster and efficient.

Explaining the PID control will take a lot of time and space hence I will be explaining about it in the next page.

Advanced Line Following Robot - Step 1: What it takes to build a fast line follower? Part: B

In this page I will be explaining about the PID control

PID stands for Proportional Integral and Derivative. It is a popular control loop feedback control extensively used in industrial controls systems. But why would one need a PID controller for a line following robot, when there are many simpler algorithms already available for line following. Lets us see...

A conventional robot would follow a line as shown below(red line shows the path taken by the robot)

 

Photobucket

As you can see clearly in the picture the robot oscillates a lot about the line, wasting valuable time and battery power. By now you must have realized that there is a maximum speed beyond which you cannot use this algorithm, other wise the robot will overshoot the line.


A robot with PID control will follow the line as shown below

Photobucket

As you can see clearly the robot will follow the line smoothly keeping its centre always above the line. In straight lines, the robot will gradually stabiles go straight unlike a robot with the left-right algorithm. This enables the robot to follow the line faster and more efficiently.

Before I tell you how to implement a PID algorithm for a line following robot, let me tell you the terms associated with it –


Target – It is the position you want the line follower to always be(or try to be),that is, the center of the robot.

Current Position – It is the current position of the robot with respect to the line.

Error - It is the difference between the current position and the target. It can be negative, positive or zero.

Proportional – It tells us how far the robot is from the line like – to the right , to the extreme right, to the left or a little to the left. Proportional is the fundamental term used to calculate the other two.

Integral – It gives the accumulated error over time. It tells us if the robot has been on the line in the last few moments or not.

Derivative – It is the rate at which the robot oscillates to the left and right about the line.

Kp, Ki and Kd are the constants used to vary the effect of Proportional, Integral and Derivative terms respectively.

What the controller does is first calculate the current position. Then calculate the error based on the current position. It will then command the motors to take a hard turn, if the error is high or a small turn if the error is low. Basically, the magnitude of the turn taken will be proportional to the error. This is a result of the Proportional control. Even after this, if the error does not decrease or decreases slowly, the controller will then increase the magnitude of the turn further and further over time till the robot centers over the line. This is a result of the Integral control. In the process of centering over the line the robot may overshoot the target position and move to the other side of the line where the above process is followed again. Thus the robot may keep oscillating about the line in order to center over the line. To reduce the oscillating effect over time the Derivative control is used.

 

Implementing PID control for a line following robot

 

The first requirement in implementing PID for a line follower is calculating the error of the robot. To calculate the error we will need to know the current position of the robot with respect to the line. There are a number of ways of knowing this.

A simple approach would be to place two IR sensors on either side of the line. The IR sensors should be tuned to give an output voltage that is promotional to the distance between the line and the sensor. The output can then be connected to the ADC pin of a microcontroller and the error can be calculated.

Though this method may seem simple and easy to implement it has a few drawbacks. Firstly, a robot using this method will have problems following a line whose width is varying. Secondly, the output of these sensors will be highly susceptible to interference from external light. And lastly, for this method to work, you have to ensure that the track is completely flat. Any change in the distance between the sensor and the surface will affect the sensor readings.

A better approach would be to use the traditional sensor array. Using an array of sensors, you can easily calculate the error by knowing which sensor is on the line. Consider you have an array of 10 sensors each placed 1cm apart. When the 7th sensor from the left detects the line you can be sure that the centre of the robot is 2 cm to the right of the line. Using a sensor array the processor can calculate the error faster as there is no ADC required to be done and thus you can increase the sampling rate. You can also use the robot as a grid solver.

When building a sensor array, there are a few things to keep in mind. Firstly, the more sensors you have in an array, the better will be the performance of the robot, because more sensors translates to more range of error. For line following anything between 6 to 10 sensors (depending on your robot) will be sufficient. The distance between each adjacent sensor determines the resolution of the readings. It is always best to place the sensors as close to each other as possible because your resolution will increase as you place the sensors closer (a resolution of +/- 1cm is always better than a resolution of +/- 3 cm).

The next important thing in implementing PID after the sensors is the writing the code itself. The algorithm for a PID control for line followers would be something like this –

 

Error = target_pos – current_pos               //calculate error

P = Error * Kp                       //error times proportional constant gives P

I = I + Error                         //integral stores the accumulated error

I = I * Ki                             //calculates the integral value

D = Error – Previos_error       //stores change in error to derivate

Correction = P + I + D

 

The next step is to add this correction term to the left and right motor speed.

While calculating the derivative, the change in error can be divided by the time taken to get the rate of change of error, but I have skipped this step in my robot, because each loop takes almost the same time to execute.

Advanced Line Following Robot - Step 2: The Parts List



The following are the parts used in building the robot -


Item

Qty

Price

Vendor, Part No.

Atmega16

1

$5.9

www.futurlec.com

L293D

1

$2.9

www.futurlec.com

16x2 LCD with backlight

1

$9.9

www.futurlec.com

LM7805 - 5V Positive Regulator

1

$0.3

www.futurlec.com

2 Pin .1" Straight Male and Female Polarized Headers

6

$0.22

www.futurlec.com

3 Pin .100" Straight Male Polarized Headers

1

$0.23

www.futurlec.com

4 Pin .100" Straight Male Polarized Headers

1

$0.27

www.futurlec.com

6 Pin .100" Straight Male Polarized Headers

1

$0.35

www.futurlec.com

8 Pin .100" Straight Male Polarized Headers

2

$0.45

www.futurlec.com

IR LED pairs

8

$0.47

www.robokitsworld.com

16 Pin IC Socket

1

$0.07

www.futurlec.com

40 Pin IC Socket

1

$0.15

www.futurlec.com

Miniature Pushbuttons

3

$0.45

www.futurlec.com

330 ohm resistor

17

$0.1

www.futurlec.com

10K resistor

12

$0.1

www.futurlec.com

0.22 uf ceramic disc capacitor

2

$0.99

www.hobbyengineering.com

100 uF electrolytic capacitor

1

$0.08

www.futurlec.com

100 uF electrolytic capacitor

1

$0.08

www.futurlec.com

200 rpm dc motors

2

$4.69

www.robokitsworld.com

Wheels (dimeter of 8—10cm)

2

$5

www.triindia.co.in

Plywood

One big piece

$5

Local hardware shop

Screws, Nuts and bolts

20—30

$8

Local hardware shop

Small L—bracket

11

$10

Local hardware shop

Micelleneous

$10

Total

$85


Note: If you are building the robot, I would suggest you to go through and understand the whole tutorial before ordering the parts.

Apart from these parts you will also need the following tools and materials, if you don’t have them you may consider buying or borrowing them-
• Soldering Iron
• Desoldering Pump(optional)
• Crimper
• Drilling machine
• A 8 - 12 V battery source
• Wires

Advanced Line Following Robot - Step 3: The Mechanics

The Mechanics

 

Nothing too complicated here. The robot uses differential drive as its steering mechanism. From my experience differential drive is one of the best steering mechanisms for line following robots. Almost all of the fast line followers I have seen use differential drive or a variation of it. It is easy to understand and implement and at the same time quite cheap (only needs two motors). And above all writing a PID control for the differential drive is both simple and easy. When the robot’s left or right sensor senses the line, the corresponding motor is slowed down and the robot stays on line.

The chassis is quite intriguing. The chassis is completely closed. All the parts – motors, circuit board, sensors – are placed inside the chassis. This is done so because by keeping the sensors enclosed in the chassis, you will be shielding them from any ambient light thus avoiding any interference from the surrounding light sources. With this setup, I can calibrate the sensors once at home and use the robot in outdoors, indoors and in the competition

Photobucket
The sensor board is mounted inside the closed chassis and is completely shielded by external light


Designing
I used Google SketchUp for designing the robot. Google sketchup was used because it is easy to learn and it is available as a free download.

Construction
The robot is built in plywood. Plywood was used because it is easy to work with – cutting and drilling holes in plywood is easy and requires no special tools. Moreover it is quite light(keeping the robot light has many advantages). I used plywood of 3 mm thickness.

Photobucket
This picture shows the plywood cut into pieces.

Then I drilled four holes to mount the L-Brackets to attach the sides.

Photobucket
The robot's base


Photobucket
The L-Brackets attached to the base.

Photobucket

Photobucket
The sides attached to the base.

The top piece is then attached to the chassis. A hinge is attached in its front end.
Photobucket


The front piece is attached to the top through the hinge. The front piece is attached to the hinge so that, the front piece may be opened for calibrating sensors, changing batteries, etc.

 

Photobucket

I added a similar hinge to the back and attached the back piece as shown. Such an arrangement is made so that the back piece can be opened and the main circuit board can be accessed easily.

Photobucket

Photobucket



Then I drilled two holes for the motors on the sides. Make sure that the holes are correctly aligned or the robot's wheel will not be aligned and the robot will not go straight even on straight tracks.

Photobucket



Then I mounted the motors and the wheels. The motors I used had a nut around the shaft, which enable me to drill a hole in the side of the chassis (as seen in the above picture) just enough for the shaft to go through it and tightened the nut from the other side (as seen in the picture below).

Photobucket


Mounting the wheels was even easier. The wheels I used had a set screw which I used to mount it to the motor's shaft.

Photobucket

 

Then I drilled three holes of diameter 3mm at the back of the top peice and cut a 3cm by 8 cm peice for the LCD as shown in the next picture.

 

Note: As you can see in the picture, I have used polarized connectors for the DC motors. It is always a good idea to use polarized connectors for DC motors because if you connect them the other way around, then that motor will be turning back instead of turing forward and it will take a lot of time to figure out whats happening(this happened to me and it took me more than an hour to figure out what had happened. For more than an hour I thought there was some problem in the algorithm !)

Advanced Line Following Robot - Step 4: The Electronics

Electronics

 

In this parts I will be explaining the constuction of the sensor array and the main controll board.

 

The Sensor Array

The sensor board consists of 8 IR sensors. The sensors are placed 1.2 cm apart from each other.Two on oboard LM324 onboard convert the anaglog signals from the IR photodiode and convert them to digital signals. There is a onboard preset to calibrate the sensors. The sensor board PCB is shown below. I used EaglePCB for the designing because it is quite easy to learn and comes free. The sensor board is single sided so it should be possible to etch at home. Just print the board to size and etch it.

 

The solder side (the board is 10cm x 4.5 cm)

 

The silkscreen side

 

R1 - 120 ohms

R2 to R9 - 10K

L1 to L8 are IR LEDs

PD1 to PD8 are photodiodes

 

The final sensor board is shown below

 

 

I attached two l brackets on both sides of the sensor board to mount it to the robot chassis.

 

The Main Board

The main board consists of the microcontroller and the motor driver. The microcontroller I used is the Atmega16. The motor driver I used is the L293D. I used the L293d because it is quite cheap and also you can control the motor speed with its enable feature. 

The main board's PCB is shown below. It is also single sided. It is 10 cm x 4.5 cm.

The solder side

The silkscreen side

 

Photobucket Photobucket

The final board

 

Note: The motor driver I have used, the L293D, can drive motors which consume upto 600 ma of current. If your motor requires more current, you can use the L239NE which can drive motors upto 1 A. It is pin compatible with the L293D so you can use the same circuit.

 

Visit http://i305.photobucket.com/albums/nn236/pratheekn/Lotl.png to view the schematic. You can also download the Eagle schematic files below.

 

Advanced Line Following Robot - Step 5: The Programming

Programming

 

In this page I will explain the final process of building the robot - Programming.

 

The program for the robot is written in WinAVR and the programmer used to transfer the program to the microcontroller is PonyProg. I used a serial programmer to program the robot. I won't be explaining how to program the robot as this step varies a lot from the software and the hardware programmer you  use. For programming the microcontroller, you can follow the instructions in this page - http://www.societyofrobots.com/step_by_step_robot_step4.shtml

 

The program consists of the following files - 

Lotl.c - This is the most important file. It contains the main function.

Lotl.h - This file contains all the function and variable definitions used by the program.

lcd.c and lcd.h - these files are used to control the LCD. I downloadeed them from http://extremeelectronics.co.in/ .

 

Note: You will have to disable the JTAG fuse of the microcontroller. The Atmega16 comes shipped with the JTAG feature enabled and this renders some pins of PORTC unusable which are required to control the LCD in this project. Once JTAG is disabled these pins can be used as standard IO pins.

 

Here is an explanation of the functions used in the program - 

 

InitPorts() - Initializes all the pins as inputs or outputs. I ususally keep a separate function for initialization as the program becomes more clear and since all the initialization has been done in one place, additions and modifications become simpler.

 

InitInterrupts() - This function sets the interrupt registers. It has to be called just one at the start of the program.

 

InitPWM() - Initializes the timer registers for Pulse Width Modulation for controlling the motor speeds. 

 

PowerLEDOn() and PowerLEDOff() - switch on and off the power LED.

 

 

BacklightOn() and BacklightOff() - switch on and off the LCD backlight.

 

 

CalcError() - This method reads the sensor values and calculates the current error.

 

LeftMF() - Drives the left motor forward.

 

LeftMB() - Drives the left motor backward.

 

LeftMS() - Stops the left motor.

 

RightMF() - Drives the right motor forward.

 

RightMB() - Drives the right motor backward.

 

RightMS() - Stops the right motor.

 

 

Tuning the PID control

This is the most interesting part in building a PID control. In this step one should tune the Kp, Ki and Kd values to get the best results. I cannot give you the values because what works for me will not work for you. The optimum Kp, Ki and Kd values vary a lot from robot to robot. And the best way to determine the optimum values is by trial and error.

First, set all values to 0 and start with tuning the Kp value. First time I just gave an approximate value. Seeing the robot perform will determine what you should do next. If the robot wobbles a lot reduce the Kp value, if the doesn't follow the line (goes straight in curves) increase the Kp value. Tune the Kp value till the robot smoothly follows the line. By now you will have observed that the robot goes with no acceleration on straight lines. Now, tune the Kd term. After tuning the Kd term move to the Ki term. After which, you will see the robot first center over a straight line and then accelerate also.

Note: The optimum Kp, Ki and Kd values vary a lot even from track to track. You can only know these optimum values by testing. 

 

Time taken for building the robot

 

Research: 10 -  11 hrs

Designing: 3 - 4 hrs

Mechanics and Electronics: 5 - 6 hrs

Programming: 4 - 5 hrs

Testing: 15 - 20 hrs

 

Total time taken: 35 - 40 hrs

 

Possible Upgrades

 

1. Store the Kp, Ki and Kd values in the microcontroller's EEPROM so that you don't have to set them every time you need to use the robot(I really wanted to do this but did not due to lack of time).

 

2. Use encoders for wheels this will give you input like your speed, acceleration and even position if possible.

 

3. Add another two sensors in the front to detect the surface color and implement a algorithm that will detect changes in surface color(eg. black to white) on the go.

 

4. Use Li - ion or Li - poly batteries. These will improve performance quite a lot owing to their low weight and the power they can provide. Implementing an onboard charger will be really useful.

 

5. I myself haven't figured out how to do it but implementing an algorithm that will enable the robot map the line it is following will be a great project in itself.