Build a fast Raspberry Pi Pico line follower robot with PID steering, a 5-channel IR sensor array, a TB6612FNG motor driver, an ultrasonic obstacle stop and a live OLED status screen.
Need it ready-made? Buy Ready Project
This Raspberry Pi Pico line follower robot tracks a black tape line on a white floor using a 5-channel IR sensor array and smooth PID steering. A TB6612FNG driver runs the two gear motors, an HC-SR04 ultrasonic sensor stops the robot before it hits anything placed on the track, and a small OLED shows what each sensor sees, the obstacle distance, the battery voltage and the run time.
It is a complete robotics combination project: sensors, motor control, a control loop, power regulation and a user interface, all written in MicroPython. It is ideal for college mini projects, robotics competitions and anyone who wants to understand how PID control really works on a moving robot.

How It Works
- Reading the line: each of the five IR sensors shines infrared light at the floor. White reflects it and black absorbs it, so each digital output tells the Pico whether that sensor is over the line. Most modules output LOW over black; set
LINE_IS_LOWto match yours. - Position error: the sensors get weights of -2, -1, 0, +1 and +2 from left to right. The average weight of the sensors that see the line is the error: 0 means the line is centred, a negative value means it is to the left, a positive value means it is to the right.
- PID steering: the correction is
KP × error + KI × integral + KD × change in error. The correction is added to the left wheel speed and taken away from the right wheel speed, so the robot turns back towards the line smoothly instead of zig-zagging. - Motor driver: the TB6612FNG is a MOSFET driver, so it wastes far less voltage than an L298N. The Pico drives its PWM pins at 20 kHz (silent) and uses the IN pins for direction. Setting both IN pins high gives a short brake for quick stops.
- Lost line and crossings: if no sensor sees the line, the robot spins towards the side where it last saw it until it finds it again. If all five see black (a cross or a finish mark), it keeps going straight.
- Obstacle stop: the HC-SR04 is read every 60 ms. If something is closer than 15 cm the robot brakes and the buzzer sounds; it moves on as soon as the path is clear.
- Power: two 18650 cells (7.4V) feed the motors directly through the TB6612 VM pin, and a buck converter makes a clean 5V for the Pico VSYS pin and the ultrasonic sensor. A 10 kΩ and 4.7 kΩ divider lets the Pico ADC measure the battery and warn when it is low.
Components Required
- Raspberry Pi Pico or Pico W (with headers) – 1
- 5-channel IR line sensor array (TCRT5000 type, digital outputs) – 1
- TB6612FNG dual motor driver module – 1
- N20 or TT gear motors (6V, 200 to 300 RPM) with wheels – 2
- Caster ball wheel – 1
- HC-SR04 ultrasonic sensor – 1
- 0.96 inch SSD1306 I2C OLED (128×64) – 1
- 2S 18650 battery holder with switch and two 18650 cells (7.4V) – 1
- Mini buck converter (MP1584 or LM2596) set to 5V – 1
- Active buzzer module (3.3V) – 1
- Tactile push button – 1
- Resistors: 1 kΩ and 2 kΩ (echo divider), 10 kΩ and 4.7 kΩ (battery monitor) – 1 each
- Robot chassis plate (acrylic or 3 mm MDF), jumper wires, screws and 19 mm black electrical tape for the track
Wiring Table
| Part / pin | Pico pin | Notes |
|---|---|---|
| IR array S1, S2, S3, S4, S5 | GP2, GP3, GP4, GP5, GP6 | S1 is the far-left sensor; power the array from 3V3 |
| IR array VCC / GND | 3V3 (pin 36) / GND | 3.3V supply keeps outputs safe for the Pico |
| TB6612 PWMA / AIN1 / AIN2 | GP16 / GP17 / GP18 | Left motor on A01 and A02 |
| TB6612 PWMB / BIN1 / BIN2 | GP22 / GP20 / GP21 | Right motor on B01 and B02 |
| TB6612 STBY | GP19 | Set HIGH by the code to enable the driver |
| TB6612 VCC / VM / GND | 3V3 / battery + (7.4V) / GND | VM takes the motor supply |
| HC-SR04 VCC / GND | Buck 5V / GND | Sensor needs 5V |
| HC-SR04 TRIG | GP14 | 3.3V trigger is enough |
| HC-SR04 ECHO | GP15 through 1 kΩ, 2 kΩ to GND | Never connect the 5V ECHO pin directly |
| OLED SDA / SCL | GP0 / GP1 | I2C0, address 0x3C |
| Push button | GP10 to GND | Start and stop |
| Active buzzer + | GP11 | Negative pin to GND |
| Battery monitor | GP26 (ADC0) | Battery + to 10 kΩ to GP26, 4.7 kΩ GP26 to GND |
| Buck converter OUT 5V | VSYS (pin 39) | Set to 5.0V with a meter before connecting the Pico |
Connection Diagram
The illustration near the top shows how the parts sit on the chassis. It is a layout guide only. Follow the pin-accurate drawing below, which matches the wiring table exactly.
Mechanical Setup
- Mount the IR array at the front, 5 to 10 mm above the floor and centred between the wheels. Too high and it cannot tell black from white; too low and it scrapes.
- Place the motors at the back and the caster ball at the front, or the other way round, so the robot sits level. The sensor array should be about 6 to 10 cm ahead of the wheel axle for stable steering.
- Fix the HC-SR04 at the front facing forward, a little above the floor so it does not see the track itself.
- Keep the battery low and near the wheels so the robot does not tip on sharp turns.
- Make the track with 19 mm black electrical tape on a white chart sheet or a light floor, with curves no tighter than about 10 cm radius at first.
Code
Flash the latest MicroPython UF2 for your board (Pico or Pico W) and open Thonny. Install the ssd1306 package from Tools > Manage packages (the robot still runs without the OLED if it is missing). Save the code below on the Pico as main.py so it starts on power-up. On a Pico W change the on-board LED line to Pin("LED", Pin.OUT).
# Raspberry Pi Pico PID Line Follower Robot
# 5-channel IR array + TB6612FNG + HC-SR04 obstacle stop + SSD1306 OLED
# MicroPython for Raspberry Pi Pico / Pico W
# Arduino Project Hub - ardiunoprojecthub.online
from machine import Pin, PWM, I2C, ADC, time_pulse_us
import time
try:
import ssd1306 # install "ssd1306" from Thonny > Tools > Manage packages
HAVE_OLED = True
except ImportError:
HAVE_OLED = False
# ---------------- Tuning (change these for your robot) ----------------
BASE_SPEED = 45 # % duty on a straight line (35-60 is typical)
MAX_SPEED = 85 # % duty limit for any wheel
KP = 14.0 # proportional gain
KI = 0.0 # integral gain (keep 0 at first)
KD = 55.0 # derivative gain
STOP_CM = 15 # stop if an obstacle is closer than this
LINE_IS_LOW = True # True if the sensor output goes LOW over the black line
LOW_BATT_V = 6.6 # warn below this battery voltage (2S Li-ion)
DIVIDER = (10000 + 4700) / 4700 # battery divider ratio (10k top, 4.7k bottom)
# ---------------- Pins ----------------
ir = [Pin(p, Pin.IN) for p in (2, 3, 4, 5, 6)] # S1 (far left) .. S5 (far right)
WEIGHTS = (-2, -1, 0, 1, 2)
pwma = PWM(Pin(16)); ain1 = Pin(17, Pin.OUT); ain2 = Pin(18, Pin.OUT) # left motor
stby = Pin(19, Pin.OUT)
bin1 = Pin(20, Pin.OUT); bin2 = Pin(21, Pin.OUT); pwmb = PWM(Pin(22)) # right motor
pwma.freq(20000); pwmb.freq(20000)
trig = Pin(14, Pin.OUT, value=0)
echo = Pin(15, Pin.IN) # through 1k / 2k divider (5V -> 3.3V)
button = Pin(10, Pin.IN, Pin.PULL_UP)
buzzer = Pin(11, Pin.OUT, value=0)
led = Pin(25, Pin.OUT) # on-board LED (Pico). On Pico W use Pin("LED")
batt = ADC(26)
oled = None
if HAVE_OLED:
try:
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
except Exception:
oled = None
# ---------------- Helpers ----------------
def motor(pwm, in1, in2, speed):
"""speed -100..100 (%)."""
speed = max(-100, min(100, speed))
if speed >= 0:
in1.value(1); in2.value(0)
else:
in1.value(0); in2.value(1)
pwm.duty_u16(int(abs(speed) * 655.35))
def drive(left, right):
motor(pwma, ain1, ain2, left)
motor(pwmb, bin1, bin2, right)
def brake():
ain1.value(1); ain2.value(1); bin1.value(1); bin2.value(1)
pwma.duty_u16(65535); pwmb.duty_u16(65535)
def read_line():
"""Returns list of 1 (on line) / 0 (off line) for S1..S5."""
return [(0 if p.value() else 1) if LINE_IS_LOW else p.value() for p in ir]
def distance_cm():
trig.value(0); time.sleep_us(2)
trig.value(1); time.sleep_us(10); trig.value(0)
t = time_pulse_us(echo, 1, 25000) # 25 ms timeout (~4 m)
if t < 0:
return 999
return t / 58.0
def battery_v():
return batt.read_u16() * 3.3 / 65535 * DIVIDER
def beep(ms=80, times=1):
for _ in range(times):
buzzer.value(1); time.sleep_ms(ms)
buzzer.value(0); time.sleep_ms(ms)
def show(l1, l2="", l3="", l4=""):
if not oled:
return
oled.fill(0)
for i, t in enumerate((l1, l2, l3, l4)):
oled.text(t, 0, i * 16)
oled.show()
# ---------------- Main ----------------
stby.value(1)
brake()
running = False
last_error = 0.0
integral = 0.0
last_seen = 0 # -1 line was on the left, +1 on the right
lap_start = time.ticks_ms()
last_ui = 0
last_sonar = 0
dist = 999
beep(60, 2)
while True:
now = time.ticks_ms()
# Start / stop button (active LOW) with simple debounce
if button.value() == 0:
time.sleep_ms(30)
if button.value() == 0:
running = not running
brake()
integral = 0; last_error = 0
lap_start = now
beep(120 if running else 40)
while button.value() == 0:
time.sleep_ms(10)
# Ultrasonic every 60 ms (keeps the PID loop fast)
if time.ticks_diff(now, last_sonar) > 60:
dist = distance_cm()
last_sonar = now
s = read_line()
count = sum(s)
if not running:
brake()
state = "READY - press btn"
elif dist < STOP_CM:
brake()
state = "OBSTACLE!"
buzzer.value(1)
else:
buzzer.value(0)
if count == 0:
# Line lost: spin toward the side where it was last seen
state = "SEARCH"
if last_seen < 0:
drive(-35, 45)
else:
drive(45, -35)
elif count == 5:
# All black: finish mark or cross line - go straight
state = "CROSS"
drive(BASE_SPEED, BASE_SPEED)
else:
error = sum(w * v for w, v in zip(WEIGHTS, s)) / count
if error < 0: last_seen = -1
elif error > 0: last_seen = 1
integral = max(-50, min(50, integral + error))
derivative = error - last_error
last_error = error
corr = KP * error + KI * integral + KD * derivative
left = max(-MAX_SPEED, min(MAX_SPEED, BASE_SPEED + corr))
right = max(-MAX_SPEED, min(MAX_SPEED, BASE_SPEED - corr))
drive(left, right)
state = "RUN e=%+.1f" % error
# Screen and LED update 4 times a second
if time.ticks_diff(now, last_ui) > 250:
last_ui = now
v = battery_v()
led.toggle()
secs = time.ticks_diff(now, lap_start) // 1000 if running else 0
show(state,
"IR " + "".join("#" if x else "." for x in s),
"Dist %3d cm" % min(dist, 999),
"Bat %.1fV %ds%s" % (v, secs, " LOW" if v < LOW_BATT_V else ""))
time.sleep_ms(5)
Tuning the PID
- Set
KIandKDto 0 andBASE_SPEEDto about 35. - Raise
KPuntil the robot follows gentle curves but wobbles slightly on straights. - Raise
KDstep by step (20, 40, 60) until the wobble goes away and turns become smooth. - Only add a small
KI(0.2 to 1) if the robot always drifts to one side of the line. - Increase
BASE_SPEEDslowly and re-tune KP and KD at each step.
Testing
- Lift the robot off the floor, switch it on and check the OLED shows READY and the five sensor marks.
- Move a strip of black tape under each sensor and confirm the matching # appears on the OLED. Adjust the blue trimmer on each sensor if needed.
- Press the button: both wheels should spin forward. If one spins backwards, swap that motor’s two wires on the TB6612.
- Put your hand 10 cm in front of the ultrasonic sensor: the wheels should stop and the buzzer should sound.
- Place the robot on the track, press the button and tune the PID values.
Troubleshooting
| Problem | Fix |
|---|---|
| Robot turns away from the line | The sensor order or the motors are swapped. Check S1 is on the left, or swap the left and right motor connections on the driver. |
| Sensors always read black or always white | Adjust each sensor’s trimmer, change LINE_IS_LOW, and keep the array 5 to 10 mm above the floor. Strong sunlight can blind IR sensors. |
| Pico resets when the motors start | The motors are pulling the supply down. Use charged 18650 cells, keep the buck converter on its own wires from the battery, and add a 470 µF capacitor across VM and GND. |
| Robot wobbles on straight lines | Lower KP or raise KD, and reduce BASE_SPEED. |
| Robot overshoots sharp curves | Lower BASE_SPEED or raise KP; move the sensor array further ahead of the wheels. |
| Stops for no reason | The ultrasonic sensor sees the floor or the track edge. Point it slightly upward or reduce STOP_CM. |
| OLED stays blank | Check SDA on GP0 and SCL on GP1, and that the ssd1306 package is installed. Some modules use address 0x3D. |
Ideas to Extend
- Use a Pico W to send the live error and speed to a phone web page for wireless PID tuning.
- Add wheel encoders and log lap times to the OLED for competition practice.
- Use an 8-channel analog sensor array with the Pico ADC for even smoother steering.