Python Robotics Projects
上QQ阅读APP看书,第一时间看更新

Interfacing the PIR sensor

So far, so good! In this unit, we will go ahead and interface out first sensor, which is a passive infrared, commonly known as a PIR sensor. This sensor is a very special sensor and is used very commonly in automation projects. Its low energy consumption makes it a superb contender for IoT projects as well. So let's see how it works.

You must have noticed that when we heat a metal to a high temperature, it slowly gets dark red in color, and when we heat it further, it gets brighter and slowly goes from red to yellow as depicted in the below diagram which shows a red hot steel tab. Now, as the temperature increases, the wavelength of the emitted radiation decreases; that is why with the increase in temperature the color changes from red to yellow, as yellow has a shorter wavelength compared to red. 

But the interesting part is that even when the objects are not heated enough, they emit radiation; in fact, any object that is above the temperate of absolute zero emits some form of radiation. Some we can see with the naked eye, others we can't. So, at room temperature, objects emit infrared radiation which has a higher wavelength compared to visible light. Hence, we don't see it with our eyes. Nonetheless, it is still there.

What this PIR sensor does is that it senses the infrared light from the objects around it and whenever an object moves, it can sense the overall change in its pattern and, based on that, can detect if there is any movement that has happened in its proximity.

We assume that whenever there is someone in a room there will be some inherent movement that will happen, and hence this sensor is very commonly used as an occupancy sensor. Now, let's connect this sensor and see how we can use it:

Once you have connected it as per the preceding diagram, go ahead and upload the code: :

import time import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23,GPIO.IN)
GPIO.setup(24,GPIO.OUT)
while True:
if GPIO.input(23) == 1:
GPIO.output(24,GPIO.HIGH)
else:
GPIO.output(24,GPIO.LOW)

time.sleep(1)
GPIO.cleanup()

Now, let's see what is happening. The logic is very simple. As soon as the PIR sensor detects movement, it turns its output pin to high. All we have to do is to monitor that pin and that's basically it. 

The logic is entirely similar to that of a push-button switch, and it will also work in a similar manner. So not much explaining is needed.