Setup the PIR Motion Sensor on the Raspberry Pi

In this tutorial we will setup the PIR (Passive Infrared) Motion Sensor on the GPIO pins on the Raspberry Pi to detect movement.

pir-motion-sensor-raspberry-pi

We will also create a Python Script to trigger a event once we detect movement

Installation

Referenced from this post, the left pin (red / input power), the middle (brown pir output) and right (black / ground):

Connects to the GPIO pin on the raspberry pi:

  • Left Red -> GPIO Pin 2
  • Middle Brown -> GPIO Pin 26
  • Right Black -> GPIO Pin 6

Referenced from this post, so we will have something like this:

Interact with the PIR Motion Sensor

Let's use Python to interact with our PIR Motion Sensor, so whenever we detect movement, that we react on that event by calling a basic print function.

Our code for detect.py:

# colors
# https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python

import RPi.GPIO as GPIO  
import time

GPIO.setmode(GPIO.BCM)  
PIR_PIN = 7  
GPIO.setup(PIR_PIN, GPIO.IN)

def react_to_event():  
    timestamp = time.strftime("%F %T")
    print('{red} {text} {default} [{t}] motion detected'.format(red='\33[31m', text='WARNING', default='\x1b[0m', t=timestamp))
    return True

print("started")  
time.sleep(2)

while True:  
    if GPIO.input(PIR_PIN):
        react_to_event()
    time.sleep(1)

When we run it, and then make movement in front of the motion sensor:

$ python detect.py
started  
 WARNING  [2020-06-26 16:21:58] motion detected
 WARNING  [2020-06-26 16:21:59] motion detected
 WARNING  [2020-06-26 16:22:00] motion detected

Although, this is just a basic example, you can use the raspberry pi camera to take photos when you detect movement as an example.

I have a post on how to setup the raspberry pi camera if you would like to extend to this.

Resources

I stumbled upon these great resources which is related to this post: