In this task, we will implement a simple line following technique using the infrared sensor. We will make use of a pair of infrared sensors to track a black line on a white surface. The robot will move forward if both the sensors are on a white surface. The robot turns left if the left sensor is on the black line and vice versa.
The sensor needs to be soldered and connected to the Raspberry Pi (something like the one shown in the preceding schematic). Alternatively, you may use a sensor of your choice.
Rpi.GPIO
:import RPi.GPIO as GPIO from time import sleep
GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(18,GPIO.IN) GPIO.setup(25,GPIO.IN)
state = 1 prev_state = 0 while True: #both sensors are on white surface if ((GPIO.input(18)==GPIO.HIGH) and (GPIO.input(25)==GPIO.HIGH)): state = 0 #left sensor alone is on the black surface elif ((GPIO.input(18)==GPIO.LOW) and (GPIO.input(25)==GPIO.HIGH)): state = 1 #right sensor alone is on the black surface elif ((GPIO.input(18)==GPIO.HIGH) and (GPIO.input(25)==GPIO.LOW)): state = 2 #if sensor state has changed since last time, update motor control if state != prev_state: if state == 0: #move robot forward elif state == 1: #turn robot left elif state == 2: #turn robot right prev_state = state sleep(0.15)
The sensor states are checked once every 15 milliseconds. If there is a change of sensor states, the motor control is updated (as per the logic explained in this task).
18.118.193.108