PIR (Passive InfraRed) motion sensor


In [ ]:
#We will use "RPi.GPIO" and "time" Python libraries in our code
import RPi.GPIO as GPIO
import time

#Set BCM numbering gebruiken for the Raspberry Pi GPIO pins (cfr numbers on the case)
GPIO.setmode(GPIO.BCM)

#The PIR pin of the sensor is connected to the Raspberry Pi pin nr 7
PIR_PIN = 7
#The LED will be connected to pin 18
LED_PIN = 18

#Set the pin mode to "input" for the PIR pin and "output" for the LED pin
#This way the Raspberry Pi can detect movement from the PIR sensor and drive the LED on pin 18
GPIO.setup(PIR_PIN, GPIO.IN)
GPIO.setup(LED_PIN, GPIO.OUT)

In [ ]:
#Create a function to flash the LED
def flash_led():
    GPIO.output(LED_PIN, 1)
    time.sleep(0.5)
    GPIO.output(LED_PIN, 0)

In [ ]:
#And based on that a new function we can call when a movement is detected
def on_motion(PIR_PIN):
    flash_led()
    print("Halt!")

In [ ]:
# Now we can link the PIR_PIN to the on_motion() function
# We register an event detection in the GPIO library and indicate that,
# whenever the Raspberry Pi sees a "RISING" signal coming in on the PIR_PIN (the pin going from a 0 to a 1 state),
# the on_motion() needs to be executed.

GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=on_motion)

You can now trigger the movement sensor and the Raspberry Pi will execute the function you created


In [ ]:
#Clean up GPIO:
#Remove the event registration and reinitialize the GPIO library
GPIO.remove_event_detect(PIR_PIN)
GPIO.cleanup()