2.2.5 IR Obstacle Avoidance Sensor¶
Introduction¶
In this project, we will learn IR obstacle avoidance module, which is a sensor module that can be used to detect obstacles at short distances, with small interference, easy to assemble, easy to use, etc. It can be widely used in robot obstacle avoidance, obstacle avoidance trolley, assembly line counting, etc.

Required Components¶
In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
---|---|---|
Raphael Kit |
337 |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
---|---|
Schematic Diagram¶

Experimental Procedures¶
Step 1: Build the circuit

Step 2: Change directory.
cd ~/raphael-kit/python
Step 3: Run.
sudo python3 2.2.5_IrObstacle.py
After the code runs, when you put your hand in front of the module’s probe, the output indicator on the module lights up and the “Detected Barrier!” will be repeatedly printed on the screen until the your hand is removed.
Code
Note
You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path like raphael-kit/python
. After modifying the code, you can run it directly to see the effect.
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
ObstaclePin = 17
def setup():
GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location
GPIO.setup(ObstaclePin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def loop():
while True:
if (0 == GPIO.input(ObstaclePin)):
print ("Detected Barrier!")
time.sleep(1)
def destroy():
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
Code Explanation
def setup():
GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location
GPIO.setup(ObstaclePin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
Set the GPIO mode to BCM Numbering. Set ObstaclePin
to input mode and initial it to High level (3.3v).
def loop():
while True:
if (0 == GPIO.input(ObstaclePin)):
print ("Detected Barrier!")
When ObstaclePin
is low level, print “Detected Barrier!”. It means that an obstacle is detected.