Lesson 22 Obstacle Avoidance Sensor

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp


An obstacle avoidance module (as shown below) uses infrared reflection principle to detect obstacles. When there is no object ahead, infrared-receiver cannot receive signals; when there is an obstacle in front, it will block and reflect the infrared light, and then the infrared-receiver can receive related signals.


– 1 * Raspberry Pi

– 1 * Network cable (or USB wireless network adapter)

– 1 * Obstacle Avoidance Sensor module

– Several jumper wires

Experimental Principle

An obstacle avoidance sensor mainly consists of an infrared-transmitter, an infrared-receiver and a potentiometer. According to the reflecting character of an object, if there is no obstacle, emitted infrared ray will weaken with the transmisasion distance and finally disappear. If there is an obstacle, when the infrared ray encounters it, the ray will be reflected back to the infrared-receiver. Then the infrared-receiver detects this signal and confirms an obstacle existing in front.

Note: The detection distance of the infrared sensor is adjustable – you may adjust it by the potentiometer on the module.

Experimental Procedures

Step 1: Build the circuit

              Raspberry Pi                             Obstacle Avoidance Sensor

                   GPIO0 ————————————– OUT

                   3.3V —————————————-  +

                   GND —————————————- GND

Step 2: Edit and save the code (see path/Rpi_SensorKit_code/21_obstacleAvoidence/obstacle.c)

Step 3: Compile

              gcc  obstacle.c  -lwiringPi

Step 4: Run


Now, put an obstacle in front of the module, and a string “Detected Barrier!” will be printed on the screen.


#include <wiringPi.h>
#include <stdio.h>

#define ObstaclePin      0

void myISR(void)
	printf("Detected Barrier !\n");

int main(void)
	if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
		printf("setup wiringPi failed !\n");
		return 1; 
	if(wiringPiISR(ObstaclePin, INT_EDGE_FALLING, &myISR) < 0){
		printf("Unable to setup ISR !!!\n");
		return 1;


	return 0;

Python Code

#!/usr/bin/env python
import RPi.GPIO as GPIO

ObstaclePin = 11

def setup():
	GPIO.setmode(GPIO.BOARD)       # 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 "Barrier is detected !"

def destroy():
	GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
	except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.