KevsRobots Learning Platform
32% Percent Complete
By Kevin McAleer, 3 Minutes
Page last updated May 10, 2025

Line-following robots are one of the most classic and satisfying robotics projects. In this lesson, youβll learn how to use an IR sensor to detect a black line on a white surface and steer your robot to follow it.
IR (infrared) sensors detect reflected light. They shine infrared light onto the surface and measure how much bounces back:
Most basic IR line sensors use a digital output, but some give analog readings.
Weβll use a common TCRT5000 or similar sensor with digital output for this project.
Wire the sensor to the Pico as follows:
If youβre using two sensors (left and right), wire the second sensorβs output to GP7.
from machine import Pin
from time import sleep
# Sensor input pin
sensor = Pin(6, Pin.IN)
while True:
if sensor.value() == 0:
print("Line detected")
else:
print("No line")
sleep(0.1)
Try placing your sensor over black tape on a white surface to see the output change.
With two sensors (left and right), you can create simple decision-making logic:
from machine import Pin, PWM
from time import sleep
# Motor pins (as in previous lesson)
# ...
# IR sensors
left_sensor = Pin(6, Pin.IN)
right_sensor = Pin(7, Pin.IN)
def forward():
# your forward motor code here
pass
def turn_left():
# slow or stop left motor, run right motor
pass
def turn_right():
# slow or stop right motor, run left motor
pass
def stop():
# stop both motors
pass
while True:
left = left_sensor.value()
right = right_sensor.value()
if left == 0 and right == 1:
turn_left()
elif left == 1 and right == 0:
turn_right()
elif left == 0 and right == 0:
forward()
else:
stop()
sleep(0.05)
This is your robotβs first real autonomous behavior!
Next up: Obstacle Avoidance with Ultrasonic Sensors
You can use the arrows β β on your keyboard to navigate between lessons.
Comments