Raspberry Pi with IR Sensor

Hi Tech Freaks, I’m back with another interesting and important tutorial based on Raspberry Pi. So, today we gonna see how we can connect Raspberry Pi with IR Sensor. IR sensor is a very common sensor to use and make projects but it is not easy to use it with Raspberry Pi. So, to ease the problem for beginners, I’m am here to help you. With this we begin our journey of today’s topic.

IR Sensor:

IR stands for Infra-Red. These sensors are basically a pair of IR transceivers LED’s. Which emit and receive IR light for detection of any object in front of them. The sensors are usually built out of LM358 op-amp which delivers 5V on OUT pin when something is in front of IR LED’s. But Now-a-days there is another model (whose image is given below) which is very much trending in market. So, I’ll describe about both. Also code and explanation will be covered for both. This model is based on LM393.

You can adjust value of output by using potentiometers provided on the PCB of module. Which will directly affect the range of sensor until which it can detect any object. Also, since Raspberry Pi pins are only 3.3V Logic-Level tolerant so it will be nice if you power the module with 3.3V supply for safety purpose but it will not effect much for short time so for demonstration purpose I have used 5V supply. But for long time usage I highly ask you to use 3.3V logic level to keep your Pi alive.

Material Required:

  • Raspberry Pi with screen, keyboard & mouse
  • IR sensor
  • Buzzer
  • RGB Led
  • Jumper Wires
  • Bread board

Circuit diagram:

Programming:

So, first with these two statements we import Raspberry Pi GPIO module and sleep function from time module.

 import RPi.GPIO as gp  
 from time import sleep  

Then we set pin reffering to Board numbers

 gp.setmode(gp.BOARD)  

After it we define 3 pins as 1 input for IR Sensor and 2 output for buzzer and LEDs

 gp.setup(12,gp.IN)   
 gp.setup(32,gp.OUT)   
 gp.setup(36,gp.OUT)  

For continuation of code we include it in While loop. Loop section is different for different type of sensor.

For LM358 based sensors:

 print(gp.input(12))  
 gp.output(32,gp.input(12))  
 gp.output(36,gp.input(12))  

For LM393 based sensor:

 print(not gp.input(12))  
 gp.output(32,not gp.input(12))  
 gp.output(36,not gp.input(12))  

This ‘not’ invert the input of sensor received and hence give correct output for buzzer and LED

 import RPi.GPIO as gp  
 from time import sleep 
 gp.setmode(gp.BOARD)  
 gp.setup(12,gp.IN)  
 gp.setup(32,gp.OUT)  
 gp.setup(36,gp.OUT)  
 while True:  
   print(not gp.input(12))  
   gp.output(32,not gp.input(12))  
   gp.output(36,not gp.input(12))  

You can change the Code with respect to your sensor type. If any problem arise then ask meĀ  down below, I’ll surely help you out. I hope you find this tutorial helpful.

Leave a Comment