Cart 0

How to use the TCRT5000 IR line follower sensor with the Raspberry Pi

Line Follow Principle

TCRT5000 line followers are super easy to use! You will need two of these to be able follow a line.

Position the line followers next to each other with a slight gap between them. Your line should sit within this gap.

The way these work is quite simple. As your robot stays left or right, either the left or right sensor will move over the black line. When this happens, it will trigger that sensor to go low. Knowing which sensor has gone low allows us to move the robot left or right so that the line remains in between the two sensors.

For example, if your robot stays to the left, the right sensor will move over the black line. Knowing that the right sensor has gone low, means we can move our robot right, bringing the line back in between the sensors.

Wiring Up the Sensors

Sensor 1

VCC – 3v3
GND – Ground
OUT – GPIO11 / Pin 23

Sensor 2

VCC – 3v3
GND – Ground
OUT – GPIO09 / Pin 21

Basic Code

With the sensors wired up, we can use a very simple script to see which way the robot is straying.

#!/usr/bin/python

from RPi import GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

left_sensor = 11
right_sensor = 9

GPIO.setup(left_sensor, GPIO.IN)
GPIO.setup(right_sensor, GPIO.IN)

try:
	while True:
		if not GPIO.input(left_sensor):
			print("Robot is straying off to the right, move left captain!")
		elif not GPIO.input(right_sensor):
			print("Robot is straying off to the left, move right captain!")
		else:
			print("Following the line!")
		sleep(0.2)
except:
	GPIO.cleanup()


Older Post Newer Post