Brooke's World

October 22, 2012

Using Raspberry Pi with PIR ( motion ) Sensor

Filed under: Uncategorized — Brooke @ 6:16 am

I have been using the Arduino for a few years now and recently curiosity got the better of me with the excitement around the Raspberry Pi. I purchased my first Raspberry Pi and since my interest is more in line with interacting with the physical than just having a small computer, I needed a second project. Of course, the first project was to blink an LED!

For my second project, I decided to expand on the first. I still use output to blink an LED, but now I also use input to decide when to blink the LED. The way this project works is by sensing motion using a PIR, Passive Infra-Red, sensor.

Using the Adafruit Raspberry Pi Cobbler, here’s how I connected the Raspberry Pi GPIO pins to the breadboard and wired up the PIR sensor and LED

Download the Fritzing diagram. This requires the AdafruitFritzing library.

Here’s the code!

import RPi.GPIO as GPIO
import time

PIR = 23
LED = 24

pirState = False                        # we start, assuming no motion detected
pirVal = False                          # we start, assuming no motion detected

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)

while True:
    pirVal = GPIO.input(PIR)            # read input value
    if (pirVal == True):                # check if the input is HIGH
        GPIO.output(LED, True)          # turn LED ON
        if (pirState == False):
            # we have _just_ turned on
            pirState = True
    else:
        GPIO.output(LED, False)         # turn LED OFF
        if (pirState == True):
            # we have _just_ turned off
            time.sleep(2)
            pirState = False;

Parts List / BOM (Bill of Materials) – Excluding Raspberry PI

Part Source Image Approx Price
1/2 Size breadboard Adafruit $5.00
Pi Cobbler Breakout Kit for Raspberry Pi Adafruit $7.95
PIR (motion) sensor Adafruit $10.00
220 ohm resistor RadioShack $1.19
Green LED RadioShack $1.69
Breadboarding Wire Adafruit $6.00
Total $31.83*

* = Prices are the best information from the time this tutorial was written. Prices do not include
shipping.

3 Comments »

  1. Hey i was working on this project, but i am having a little bit problem with the code, do u think u can email me the code ??

    my email is s.yusuf91@hotmail.com

    Comment by Mohammad Samian Yusuf — January 13, 2014 @ 10:53 pm

  2. Mohammad,

    The code is with the post. What is the issue you are having with getting the code from the web page?

    -Brooke

    Comment by Brooke — January 14, 2014 @ 9:41 pm

  3. Hey sorry there was a browser issue,,,,it worked actually…and my sensor was a little bit different,,but its working thanks for your tutorial…

    Comment by Mohammad Samian Yusuf — February 1, 2014 @ 7:30 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

Powered by WordPress