SparkFun PIR Breakout Hookup Guide

Pages
Contributors: El Duderino, Englandsaurus
Favorited Favorite 0

Python Example

Note: This example assumes you are using the latest version of Python 3. If this is your first time using Python or GPIO hardware on a Raspberry Pi, please read through our Python Programming with the Raspberry Pi guide and the Raspberry Pi GPIO Tutorial.

If you've assembled your SparkFun PIR Breakout circuit with a Raspberry Pi or other Python-based development board, we've written a quick example to demonstrate how to read the PIR's output.

Example Dependencies

In order to interface with your Pi's GPIO ports your user must be a member of the gpio group. The pi user is a member by default. Users with sudo privileges can add users manually using the following command:

language:bash
sudo usermod -a -G gpio <username>

Simple Read

This example demonstrates reading the SIG output from the PIR sensor using digital reads. Copy the code below into your preferred Python interpreter or into a blank text file and save it. If you are using an interpreter like Thonny, you can run it from there. Otherwise, open the terminal and run it by entering the following command: python3 FILENAME.py

language:python
import time
import RPi.GPIO as GPIO
import sys

#Pin Definition
pir_pin = 4

#Set up pins and set PIR signal as an input
GPIO.setmode(GPIO.BCM)
GPIO.setup(pir_pin, GPIO.IN)

def run_example():

    #Wait 30 seconds for the PIR to stabilize

    print ("Waiting 30 seconds for PIR to stabilize")
    for i in range(0, 30):
        print(i)
        time.sleep(1)

    print ("Device Stable. Starting readings...")

    #Start monitoring the PIR output. If an object is detected, print "Object Detected" otherwise print "All Clear"

    while True:
        if GPIO.input(pir_pin):
            print("Object Detected")
        else:
            print("All clear")
        time.sleep(1)

if __name__ == '__main__':
    try:
        run_example()
    except (KeyboardInterrupt, SystemExit) as exErr:
        print("\nEnding Example")
        sys.exit(0)