PID Line Following Robot

Pid Article Banner
Previously, I’ve made a Bluetooth Controlled Robot (read post). By adding a line sensor to the robot, I’ve managed to create a simple line following robot and utilize the ever popular PID algorithm to navigate the robot.

You can read more about my DIY line following sensor here and how I made it.

IMG_1159

Now it’s time to mount this line following sensor unto the robot.

I got myself two pieces of relatively thick and rigid iron rod.

IMG_1403

And hot glue them onto the line following sensor. (Hot glue FTW!)

IMG_1405

Bend the iron rods to 90 degree.

IMG_1409

And flip it over to estimate how high will it be mounted on the robot.

IMG_1413

After making sure the height is correct, mark the point and make the second bend.

IMG_1419

Next, use hot glue (again) to mount the iron rods to the robot base.

IMG_1423

Work of art.

IMG_1245

Some glory shots of the robot.

IMG_1232

IMG_1233

IMG_1238

I’ve added four AA batteries at the underside of the robot to feed the power hungry line sensor.

IMG_1249

These lithium-ion 18650 batteries power the electronics and the motor. Anyone recognize the ‘Passed’ sticker? 😉

IMG_1211

Added a start button and a buzzer.

IMG_1252

Now, unto the PID algorithm. PID stands for Proportional, Integral and Derivative.

It is denoted by the following equations. Kp, Ki and Kd are constants which can be tuned to the characteristics of the robot.

PIDeqn

Confused? I’ll try to give examples to understand each of these PID terms better.

First, a bit of introduction.

Imagine setpoint is the straight line that your robot should travel but according to the diagram below, it is currently not on the straight line. The position that the robot is in relative to the setpoint is called the Cross Track Error (CTE).

CTE

The P in PID is proportional, meaning the robot will steer in proportion to the Cross Track Error.

The larger the CTE, the harder it steers to the setpoint.

P1

Therefore, the Cross Track Error will decrease over time as the robot steers to the line.

However, picture this diagram below.

The robot will always overshoot because from the diagram below, you can observe that the robot is currently on the line (Cross Track Error is zero) but since it was previously steering at an angle, it is not able to straighten up itself in time when it reaches the line.

P2

Therefore, a proportional control will always cause the robot to overshoot. It will end up oscillating because it can never get perfectly in line.

P3

The way to solve this is to introduce derivative control.

Derivative control is to decrease steering angle based on the difference in Cross Track Error over time.

It basically means that the robot will countersteer when it is about to reach the line.

(If you think about it, when we drive a car or ride a bicycle, we always countersteer before we reach the point where we want to go)

D1

The end result is a smooth curve that ends up straight on the set point after a period of time.

So, we are left with the integral term. What does integral control do?

For those who have played with robots before, you’ll notice that robots tend to veer to the left or right even when both wheels get the same power.

This is called Systemic Error.

I2

Which means it is a mechanical fault where both wheels or motors are not uniform. Every motor and wheel that is manufactured is rarely equal because the manufacturing process always allows a certain amount of tolerance.

For example, if the right motor of the robot moves a little faster than the left motor, the robot will turn left slowly even when the same power is applied to both wheels.

If we just apply Proportional and Derivative control, the following occurs.

I1

The robot will travel straight in parallel to the setpoint, but it is way off its’ intended position.

This is where integral control comes in.

Integral control is the integration of the robot path over time, which also means the sum of all the Cross Track Errors over time.

It allows the robot to keep track of its’ deviation over the course.

If the sum of CTE is big, it will result in bigger steering angles at the beginning to let the robot turn to the setpoint. Once it has reached the setpoint, the CTE will stop accumulating and hence it will stay at the setpoint.

In conclusion, integral control creates an offset to eliminate or reduce any systemic errors.

I3

Below is an overview of the PID constants and what it does.

PIDtuning

Hopefully all the information above will help you understand PID better.

This is a video of my robot going around a track.

This is my code written in Arduino IDE.

pid_code

Download Code

Thanks for reading.

  1. y9109-10-2017

    This is second build I noticed this issue but after clicking on “Update and Restart” button, “Downloading Patch File” is started, but there is no restart after that.

  2. 6qv0.tapeworm.us09-10-2017

    please re upload this wonderfull app on samsaung cant download it in the new version of kies….

  3. 7aka.tapeworm.us09-10-2017

    Hello, i study your website every now and then and i own a identical one and i was just thinking if you get a lot of junk comments? If so how do you quit it, any plug-in or anything you can recommend? I get so much lately it’s generating me insane so any assistance is very much valued.

  4. m abubakar06-29-2017

    hay
    can u please mention me how much sensoers are on the line ..i mean at start 2 sensor at center or 1
    and the distanc b/w each sensor is?
    and can i edit this code for ten sesors ? what placemnt shold i needed?? please

  5. college tips01-10-2017

    This piece of writing is truly a good one it assists new internet users, who are wishing in favor of blogging.

  6. vaghela parth02-22-2016

    i want the circuit for this line follower.

  7. immad01-24-2016

    hi how u adjust the ki=0.00015 and kd=5 ..?

  8. martijn11-24-2015

    Hey, I’m trying to make this project but I cant download the arduino code?
    Do you know what Im doing wrong?

    thanks for putting this online tough

    • camiel11-24-2015

      Hey, so Im doing this project with Martijn. And I have a question 2. Do you need a motor driver for this line following project?

  9. navaneeth10-19-2015

    would you help me, how to calculate kp,ki,kd

  10. Aby02-22-2015

    Sir what is the role of variable s, defining a pin for Left_speed,Right_speed?

  11. Bishal Basnet08-22-2014

    Hey, I got a pcb of the sensor array that is used above and is single layer I like to share it with you: You can get it on http://www.sensoarray.blogspot.com Hope it helps.

  12. Bishal Basnet08-22-2014

    This post was very good but i wanted to trace a white line on a black surface and my sensor array gives high value on a white surface and a low value on a black surface. What modifications should I have to do in the programming to trace a white line on black surface. Well I was thinking of using a Not gate ic after the sensor array before feeding it to the arduino. But I think changing the program would be better so could you please help me out as I am a bit new to arduino programming.

  13. Rahul Ratna Das07-29-2014

    please teach me to use pid algorithm with digital line sensor array with 8 sensors…

  14. alex07-19-2014

    if you don’t see any sensor your error is 0/0…
    How do you manage that thing?!

  15. alex07-15-2014

    Hi!
    I really don’t understand how it possible detect if the error is postive or negative.
    Could you explain better this behaviour?!
    Thanks!

  16. anil sharma07-07-2014

    hiii,
    your explanation is superb.i understood it completely. but there is one thing in code.you are not using these functions in the code(you just created the functions) .or what significance it holds in code.please explain.
    void Right_Reverse()
    void Left_Reverse()
    void Right_Forward()
    void Left_Forward()

    and how can i use this code for maze solver.give me a clear explanation please.

  17. anil sharma07-02-2014

    hello ma’am ,i read your tutorial,it is good ,but i couldn’t connect my self with the code.please explain how to read Kp,Kd,Ki values from physical world and we set setpoint , it is hard to understand for me.i m looking for a pid tutorial for months,nw i get one please help.my concepts may be weak ,mam please help.

  18. isaac05-18-2014

    How can i calculate Kp. Ki, and Kd

  19. Carlos03-21-2014

    Hi, Great project.
    I was wondering if the reverse action is really necessary? I would like to implement the motor control using two mosfets (one for L and one for R) instead of using a dedicated motor driver. What changes will I need to do in the code for such?

    Kind Regards

    • Wai Hung03-25-2014

      Yes for this case the reverse action is unnecessary.
      You can actually just use two MOSFETs to control the speed of the motors.

      The only difference is that you don’t need the direction code, just keep the speed/PWM part.
      and of course the PWM output from your MCU goes to the MOSFET gate.

  20. Phan Dinh Khoa03-08-2014

    Hello, my name is Khoa, I am studying at a university in Vietnam. My teachers give me homework about line following robot. I have read your post, it’s very interesting. So, Can you give me detailed electrical circuits diagram of your line following robot? I am very grateful to you, thank you very much. Please email me: fandinhkhoa@gmail.com. I look forward to your message.
    Phan Dinh Khoa.

    • waihung03-16-2014

      The line following circuit is in another article. The link to it is in the beginning of this article.
      Look closely.

  21. jessan03-07-2014

    could you post your circuit diagram for the line following robot, because it is very interesting!

  22. pritesh02-26-2014

    hiii
    i am in little bit confused on sensors
    you are using analogue sensor or digital sensors

    • Wai Hung02-26-2014

      LDRs are analogue sensors. I use the comparator to translate it into digital signal. The microcontroller then process the digital signal.

      Basically,
      Analog —> Digital —-> MCU

    • http://www./12-24-2016

      la Révolution, la Révolution, franchement, la Saint-Barthélémy c’est beaucoup plus instructif, rien de tel qu’un ordre de la cour pour rendre le peuple zélé dans sa fureur, et cela n’a guère changé depuis…

    • http://www./01-29-2017

      You’re the one with the brains here. I’m watching for your posts.

    • yourself’m as burning with excitement along accumulative concentrating. alter ego was rather apocalyptic by the mated ethical self went up to. It is punk up to closed ego dispirited. All respecting those topics are movables her should discover no finish touching unpronounced. Thanks so significantly!

  23. Priya01-31-2014

    Thank you…. Your site is very good. It helped me a lot.

    • Wai Hung01-31-2014

      Thanks 🙂

  24. Priya01-30-2014

    Can you please tell me how did you made the motor driver PCB because i have L293D IC board and it has only four input terminals ( in your program 6 needed ) or any other solution.

  25. Priya Pareek01-29-2014

    How do you calculated the average value(4.5) ?

    When i calculated using 5 array sensors its 511 ( sum of sensor values at standard position / no. of total sensors ).

    reply

    • Wai Hung01-29-2014

      My code is meant for 8 sensors. If you’re using 5, u should subtract 3 because 3 is the center. Not 4.5.

  26. mukcse12-10-2013

    why PID part of the code doesn’t include the direction functions( Turn_Left/Turn_Right)

    • Wai Hung12-11-2013

      It does. The PID function returns the motor power values, and it is being decoded in the if else statement. (if power<0, …) I hope this is what you meant, if not do reply 🙂 Thanks

  27. Zx lee06-22-2013

    Thanks for the nice and clear explanation on PID algorithm.

    The “Passed” stickers are from the Robocon 2013 🙂

    • waihung06-22-2013

      You’re welcome.

      I think you should know all of these already since you have done quite well in Robocon 🙂

      I keep these ‘special’ batteries with stickers on them as remembrance. Haha.

      • Zx lee06-23-2013

        Haha, just knew that I have met you before during the Robocon Briefing. Do you still remember? 🙂

        • Wai Hung06-23-2013

          Yeah I still remember you. We had lunch after briefing sharing the same table 🙂

          Will you still be joining robocon next year?

          • Nikolay01-16-2016

            Hi! thank you very much! one question: how calculate coefficients of PID?

      • Beautiful blots or rolls, I would say, of summer fabric.It's so sad that by us buying fabric and sow is more expensive than buying a dress.Something's rotten in the Kingdom of Norway.I like flower pattern for my summer dresses, the one to the right is what I would choose.

      • Em Alvalade, uma troca de treinador, quase nunca é uma simples troca de nomes.Envolve quase sempre outras mudanças.Como se as certezas de um projecto inicial, perante uns problemas iniciais, rapidamente se tornassem em dúvidas e problemas.Já há tanto tempo que é assim…

Leave a Reply to jessan Click here to cancel reply.