Skip to content
Free Delivery on Orders Above Rs 999/- Pan-India
Cash on Delivery Available for Orders above Rs.500/- and Upto Rs 3000/-
SAVE more when you BUY more. Upto 30% Off on BULK PURCHASE
GST Invoices for Your Business
Dedicated Technical Support Team
Safely Delivering Genuine Products PAN INDIA
Delivering to
Select Location ▾
Delivering to Select Location
▾

PID Controller Explained: Tune Kp, Ki, Kd on a Line Follower

PID Controller Explained: Tune Kp, Ki, Kd on a Line Follower
-
Written By - Robocraze -
๐Ÿ“… Updated on 04 Dec 2026
โœจ Summarize with AI
โœ… Prompt copied

Summary

A PID controller keeps a robot on target by blending three corrections: Proportional, Integral and Derivative. In this guide we explain each term with a car steering analogy, work through the formula with real numbers, wire an Arduino line follower, share upload-ready code and show a step-by-step method for tuning Kp, Ki and Kd

ย 

A PID controller corrects errors using three terms: Proportional (how far off we are now), Integral (how long we have been off), and Derivative (how fast the error changes). On a line follower it turns sensor error into smooth motor speed changes.

If we have already built a basic robot with our line follower build guide or the DIY line follower robot, we know the usual problem: it zig-zags, overshoots curves, or loses the line at speed. PID control fixes that, and this post focuses on how it works.

Block diagram of a PID control loop on a line follower: the sensor array measures position, the error feeds P, I and D blocks, and their sum sets the motor speeds

ย 

PID in plain words (car steering analogy)

Think about how we keep a car in the middle of a lane:


  • Proportional: the further we drift from the centre, the harder we turn the wheel. A small drift gets a small correction.

  • Integral: if a crosswind keeps pushing us left, we slowly learn to hold a little extra right steering. That is the integral remembering past error.

  • Derivative: as the car swings back towards the centre, we start straightening the wheel early so we don't overshoot into the next lane. That is the derivative reacting to how fast the error is changing.


A line follower does the same thing. The "lane centre" is the black line, the "drift" is the sensor error, and the "steering wheel" is the speed difference between the left and right motors.

Components and Supplies

TCRT5000L 5-Channel Infrared Line Tracking Sensor Module -Sensors -Distance/Proximity Sensors -RobocrazeTCRT5000L 5-Channel Infrared Line Tracking Sensor Module -Sensors -Distance/Proximity Sensors -Robocraze

TCRT5000L 5-Channel Infrared Line Tracking Sensor Module

TCRT5000L 5-Channel Infrared Line Tracking Sensor Module The TCRT5000L 5-Channel Infrared Line Tracking Sensor Module is a compact and practical IR tracking module designed for line-following robots, smart cars, and DIY robotics projects. It uses five TCRT5000L infrared reflection sensors to continuously emit infrared...
Rs 209/-
Rs 209/-
Rs 249/-
Save Rs 40/-
Arduino Uno R3 Board compatibleArduino Uno R3 Board compatible

    Arduino Uno R3 Board compatible

    Arduinoย Uno R3 Compatible Boardย  The Arduino Uno R3 ATMEGA328P Development Board is more than just a microcontroller board; it's a gateway to endless possibilities in the world of electronics and programming. For hobbyists, students, and makers, it stands out as the best Arduino Uno...
    Rs 423/-
    Rs 423/-
    Rs 699/-
    Save Rs 276/-
    Dual L298N Motor Driver Module with PWM Control โ€“ Powerful motor driver for robotic applications โ€“ RobocrazeDual L298N Motor Driver Module with PWM Control โ€“ Powerful motor driver for robotic applications โ€“ Robocraze

      2A Dual L298N Motor Driver Module with PWM Control

      2A Dual L298N Motor Driver Module with PWM Control The L298N Motor Driver Module is a great choice for controlling motors! It contains a double H bridge L298N chip, which has a maximum voltage of 46V and a current of 2A. This L298N dual...
      Rs 165/-
      Rs 165/-
      Rs 239/-
      Save Rs 74/-
      RC DIY Coupon Badge
      4WD Smart Robot Car Kit with Acrylic Chassis โ€“ Powerful DIY Kits, STEM Kits, Robot Kits -Robocraze4WD Smart Robot Car Kit with Acrylic Chassis โ€“ Powerful DIY Kits, STEM Kits, Robot Kits -Robocraze

        4WD Smart Robot Car Chassis Kit with Motors for Arduino & Robotics

        4WD Smart Robot Car Kit with Acrylic Chassis The 4WD Smart Robot Car Kit is a complete robot chassis platform designed for Arduino Boards, ESP32 Development Boards, Raspberry Pi Boards, and other development boards used in robotics projects. Featuring a durable double-layer acrylic chassis,...
        Rs 799/-
        Rs 799/-
        Rs 859/-
        Save Rs 60/-

        P, I, and D: what each does

        Term

        Question it answers

        Too low

        Too high

        P (Kp)

        How far off are we right now?

        Slow, lazy turns; misses curves

        Fast wobble from side to side

        I (Ki)

        How long have we been off?

        Small steady offset stays

        Slow, growing swings; overshoot

        D (Kd)

        How fast is the error changing?

        Overshoots after every turn

        Jittery motors; amplifies sensor noise


        The graph below shows a simulated robot pushed off the line. With P alone, it keeps swinging. Adding D calms the swing but leaves a small offset caused by uneven motors. Adding I removes that offset.

        Line graph of robot offset over time after a disturbance: P only keeps oscillating, PD settles with a small offset, PID settles back on the line centre

        PID formula with a worked number example

        The textbook form is u(t) = Kpยทe(t) + Kiยทโˆซe(t)dt + Kdยทde(t)/dt. On an Arduino, we work in loop steps, so it becomes:

        correction = Kp ร— error + Ki ร— (sum of errors) + Kd ร— (error โˆ’ previous error)

        Say our robot uses Kp = 25, Ki = 0.5 and Kd = 15, with a base speed of 150 (out of 255). The line has moved under the right-middle sensor, so the error is 1. On the previous loop it was 0, and the error sum so far is 4.

        Term

        Calculation

        Result

        P

        25 ร— 1

        25

        I

        0.5 ร— 4

        2

        D

        15 ร— (1 โˆ’ 0)

        15

        Correction

        25 + 2 + 15

        42

        Left motor

        150 + 42

        192

        Right motor

        150 โˆ’ 42

        108


        The left wheel speeds up, the right wheel slows down, and the robot turns right towards the line. Notice that D added a large share of the correction because the error had just jumped. On the next loop, if the error stays at 1, D drops to zero.

        PID on an Arduino line follower: wiring and code

        Here is the hardware we use for this build. Each part is a standard choice for a beginner PID robot.


        TCRT5000L 5-Channel Infrared Line Tracking Sensor Module

        TCRT5000L 5-Channel Infrared Line Tracking Sensor Module

        Five IR sensors in a row give us the position of the line, not just "on" or "off". Our TCRT5000 sensor array guide covers pinout and calibration.

        View product

        Arduino Uno R3 Board Compatible

        Arduino Uno R3 Board Compatible

        Runs the PID loop hundreds of times a second and has the PWM pins we need for speed control.

        View product

        L298N Motor Driver Module

        L298N Motor Driver Module

        Takes PWM signals from the Arduino and drives the left and right motor pairs. New to drivers? Read what a motor driver is.

        View product

        4WD Four Wheel Drive Kit: Smart Robot Car with Chassis

        4WD Four Wheel Drive Kit: Smart Robot Car with Chassis

        A double-layer chassis with four geared motors, enough room for the battery, board and driver.

        View product

        ย 

        Wiring

        Wiring diagram: battery to L298N, L298N 5V to Arduino Uno, sensor outputs to A0 to A4, Arduino pins D5 to D10 to the L298N enable and input pins, and the L298N outputs to the left and right motors




        From

        To

        Note

        Sensor OUT1 to OUT5

        Arduino A0 to A4

        OUT1 is the leftmost sensor

        Sensor VCC, GND

        Arduino 5V, GND


        L298N ENA, ENB

        Arduino D5, D6

        Remove the ENA/ENB jumpers

        L298N IN1, IN2, IN3, IN4

        Arduino D7, D8, D9, D10

        Direction pins

        L298N OUT1/OUT2, OUT3/OUT4

        Left motors, right motors

        Wire each side's two motors in parallel

        Battery +, โˆ’

        L298N VS (12V), GND

        All grounds must be shared


        Turning sensor readings into error

        We give each sensor a weight from โˆ’2 (far left) to +2 (far right) and average the weights of the sensors that see black.


        Sensors on the line (L to R)

        Error

        What the robot does

        0 0 1 0 0

        0

        Goes straight

        0 0 1 1 0

        +0.5

        Gentle right turn

        0 0 0 0 1

        +2

        Hard right turn

        1 1 0 0 0

        โˆ’1.5

        Firm left turn

        0 0 0 0 0

        ยฑ3

        Line lost: keep turning the last way


        Arduino PID code

        ย 

        
          // PID line follower: TCRT5000L 5-channel + L298N + Uno
        const int S[5] = {A0, A1, A2, A3, A4};
        const int ENA = 5, IN1 = 7, IN2 = 8, ENB = 6, IN3 = 9, IN4 = 10;
        float Kp = 25, Ki = 0, Kd = 15;   // tune these
        int baseSpeed = 120;
        float lastError = 0, integral = 0;
        
        void setup() {
          for (int i = 0; i < 5; i++) pinMode(S[i], INPUT);
          int outs[] = {ENA, IN1, IN2, ENB, IN3, IN4};
          for (int p : outs) pinMode(p, OUTPUT);
          digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);  // left forward
          digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);  // right forward
        }
        
        float readError() {
          const int w[5] = {-2, -1, 0, 1, 2};
          int sum = 0, count = 0;
          for (int i = 0; i < 5; i++) {
            if (digitalRead(S[i]) == HIGH) { sum += w[i]; count++; } // use LOW if your module reads LOW on black
          }
          if (count == 0) return lastError > 0 ? 3 : -3;  // line lost
          return (float)sum / count;
        }
        
        void loop() {
          float error = readError();
          integral = constrain(integral + error, -50, 50);  // anti-windup
          float derivative = error - lastError;
          float correction = Kp * error + Ki * integral + Kd * derivative;
          lastError = error;
        
          analogWrite(ENA, constrain(baseSpeed + correction, 0, 255));  // left
          analogWrite(ENB, constrain(baseSpeed - correction, 0, 255));  // right
          delay(5);
        }
        
        

        If the robot turns away from the line, swap the signs on the two analogWrite lines or swap the motor wires on one side.

        How to tune Kp, Ki, Kd step by step


        Flowchart for PID tuning: start with Ki and Kd at zero, raise Kp until the robot wobbles, raise Kd until the wobble stops, add a small Ki only if it drifts, then raise base speed and repeat



        1. Start slow and simple. Set Ki = 0, Kd = 0 and base speed around 120. A slow robot is easier to read.

        2. Raise Kp. Start at 5 and increase in steps of 5. Stop when the robot follows curves but wobbles steadily on straights.

        3. Raise Kd. Start at about half of Kp and increase until the wobble dies out within one or two swings. If the motors start to buzz or jitter, back off.

        4. Add Ki only if needed. If the robot rides consistently to one side of the line, add Ki in small steps (0.01 to 0.1). Many line followers run well with Ki at 0.

        5. Speed up and repeat. Raise base speed by 10 to 20, then fine-tune Kp and Kd again. Higher speed usually needs more Kd.


        We find it helps to change one value at a time and note each result. A potentiometer on a spare analog pin, mapped to Kp or Kd, saves many re-uploads.

        Starting values for a 5-sensor line follower

        These are the gains we start from on a 4WD line follower running the code above, where the error runs from โˆ’2 to +2 and motor speed from 0 to 255. Every chassis, motor and battery behaves a little differently, so we treat these as a first guess and fine-tune with the steps above.

        Speed

        Base speed (PWM)

        Kp

        Ki

        Kd

        Slow

        100 to 120

        20 to 25

        0

        10 to 15

        Medium

        150 to 170

        30 to 35

        0 to 0.05

        20 to 30

        Fast

        200 to 230

        40 to 50

        0 to 0.05

        35 to 50


        Notice that Kd rises faster than Kp as the robot speeds up. A faster robot reaches the edge of the line sooner, so it needs more damping to stop each swing. If our sensor code uses a wider error range, such as โˆ’2000 to +2000 from an analog sensor array, we divide these gains by the same factor (1,000 in that case).

        PID for motor speed (encoders)

        The same controller can hold a motor at a set speed instead of holding a robot on a line. Here the sensor is a wheel encoder, which sends a fixed number of pulses per revolution. Every 50 to 100 ms we count the pulses, convert them to RPM and subtract that from the target RPM; the PID output then sets the PWM value. Unlike a line follower, speed control usually needs the I term: a motor under load always runs slightly slow, and only the integral builds up enough extra PWM to close that gap. We tune Kp first, add Ki until the speed holds under load, and keep Kd at zero or very small because encoder counts are noisy. Many robots run both loops together: a speed PID on each wheel, with the line PID on top setting their target speeds.

        Common PID mistakes

        Mistake

        Symptom

        Fix

        Starting with all three gains at once

        Hard to tell which term causes the problem

        Tune P, then D, then I

        Integral with no limit

        Robot swings wider after leaving a curve

        Clamp the integral (anti-windup)

        Using delay() of 50 ms or more

        Late, jerky corrections

        Keep the loop under about 10 ms

        Sensor array too high or uncalibrated

        Noisy error, jittery D term

        Mount 5 to 10 mm above the track; check each sensor LED

        Weak or sagging battery

        Gains that worked yesterday fail today

        Charge fully before tuning; use a steady supply

        Wrong error sign

        Robot turns away from the line

        Swap the correction signs or motor wires


        Conclusion

        PID looks like maths, but on a line follower it comes down to three questions: how far off we are, how long we have been off and how fast that is changing. With a 5-channel sensor, an Arduino, an L298N and the tuning steps above, we can turn a wobbly robot into one that takes curves smoothly.

        Get the line follower parts

        
        

        Excerpt

        Learn how a PID controller works and how to tune Kp, Ki and Kd on an Arduino line follower, with wiring, code and starting values for every speed.

        Frequently Asked Questions

        What does PID stand for?

        PID stands for Proportional, Integral, Derivative: the three terms the controller adds together to calculate its correction.

        What is a PID controller used for?

        It holds a system at a target value. We see it in line followers, self-balancing robots, drone flight controllers, 3D printer heaters, motor speed control and cruise control.

        How do we tune PID values?

        Start with Ki and Kd at zero. Raise Kp until the robot wobbles, raise Kd until the wobble settles, then add a small Ki only if a steady offset remains.

        Do we need all three terms?

        No. Many line followers work well as PD controllers with Ki at zero. We add I only when the robot keeps drifting to one side.

        Can an Arduino run PID?

        Yes. An Arduino Uno can run a simple PID loop hundreds of times per second, which is more than fast enough for a line follower. There is also a ready-made PID library for Arduino.

        What is the difference between PID and bang-bang control?

        Bang-bang control only turns fully left or right, so the robot zig-zags. PID scales the correction to the size and trend of the error, so turns are smoother and faster.

        Why does our line follower still wobble after tuning?

        Usually Kp is too high for the current speed, or Kd is too low. Check that the battery is charged and the loop has no long delays, then re-tune Kd.

        What are good starting PID values for a line follower?

        With a 5-sensor array, an error range of โˆ’2 to +2 and PWM up to 255, we start at Kp 20 to 25, Ki 0 and Kd 10 to 15 at slow speed. At higher speeds both Kp and Kd rise, with Kd rising faster; the starting values table above lists medium and fast settings.

        Prev Post
        Next Post

        Leave a comment

        Please note, comments need to be approved before they are published.

        Thanks for subscribing!

        This email has been registered!

        Shop the look

        Choose Options

        Edit Option
        Back In Stock Notification

        Choose Options

        this is just a warning
        Login
        Shopping Cart
        0 items
        FREE SHIPPING!
        โ‚น100 OFF
        โ‚น200 OFF
        โ‚น999
        โ‚น2500
        โ‚น4900
        WhatsApp Chat Chat