Raspberry Pi Motion Sensor using a PIR Sensor

In this tutorial, we’re building a Raspberry Pi motion sensor that makes use of a PIR sensor (Passive Infrared Sensor).

Raspberry Pi Motion Sensor

A PIR sensor is a simple but excellent device for detecting when motion has occurred. In older style security systems these sensors were used a lot. However, most modern systems use video. I explain a bit more about the sensor further down this page.

To make this project a little more interesting, we will also be using a piezo speaker whenever motion is detected. Both these devices will need to be hooked up to the GPIO pins to work.

If you’re unfamiliar with electronics, then this tutorial is the perfect way to introduce yourself to different parts and circuits. I highly recommend investing in a breadboard as it will make building circuits a lot easier.

Equipment

In order to do this project, you will need some equipment this includes a Raspberry Pi PIR sensor and a piezo speaker.

Raspberry Pi

SD Card or Micro SD Card if you’re using a Raspberry Pi 2, 3 or B+ (8 GB+ Recommended)

PIR Sensor

Piezo Speaker

100-ohm resistor

Optional

Ethernet Cord or Wifi dongle (These are only required if you plan on remotely controlling the Pi)

GPIO Breakout Kit

Breadboard

Breadboard Wire

While the breakout board, breadboard, and the wire are optional, I do highly recommend using these as they will make your life a lot easier. Also, be sure to check out some of the best Raspberry Pi cases you’re able to get.

Video

If you would like to see a video on how to do this Raspberry Pi motion sensor, then be sure to check out the video I have prepared below.

Please be sure to follow us on social media or sign up to our mailing list if you like our content and would love to stay up to date on all the latest projects.

Adblock blocking the video? Support us by subscribing to our ad-free service.

Raspberry Pi PIR Sensor Hardware Setup

We will be putting together a simple circuit that makes use of a PIR sensor and also a piezo speaker.

A PIR sensor is most commonly seen in security systems to detect movement before sending the alarm off. They detect motion whenever there is a change of infrared temperature in their field of view.

Most PIR sensors have some adjustable screws on them that will allow you to adjust both the time and sensitivity of them. The time will allow you to set a delay before it goes off (Send a high signal). (About 2-4 seconds). The sensitivity is how much movement needs to occur before it goes off.

The piezo buzzer is a simple speaker that outputs a sound whenever a current is traveling through it. In this circuit, the buzzer will give a loud beep whenever the motion detector circuit is triggered.

A breadboard isn’t necessarily a requirement for this project, but I would highly recommend using one. A breadboard makes prototyping and building circuitry a lot easier.

You don’t have to use a breadboard like I am you can simply hook these straight up to the Raspberry Pi.

Raspberry Pi Motion Sensor Circuit

To construct the circuit simply do the following.

1. Run a ground pin to the ground rail on the breadboard.

2. Run a 5v pin to the positive rail on the breadboard.

3. Connect the piezo buzzer to pin 7 (Red wire) and the negative rail (Black wire).

4. Run a wire from pin 11 to the breadboard. Place a 100-ohm resistor at the end of the wire. Then connect this up to the yellow wire of the PIR sensor.

5. Now for the PIR sensor run the red wire to the 5v line and the black wire to the ground rail on the breadboard.

Raspberry Pi Motion Sensor Software Setup

To bring our Raspberry Pi Motion sensor circuit to life, we will need to do a little programming. This programming is relatively easy and much like our introductory post to the Raspberry Pi GPIO pins is an excellent way to learn the basics of python.

Firstly, on your Pi enter the following command to create a python script and load it in the nano text editor.

sudo nano motion_sensor.py

If you don’t feel like typing out the full script you can directly download, unzip and enter the script folder on the Pi by entering the commands below.

Alternatively, you can also download it directly from my GitHub page.

sudo wget https://github.com/pimylifeup/motion_sensor/archive/master.zip
unzip master.zip
cd ./motion_sensor-master

I will briefly explain what each part of the code does.

Firstly, we import the GPIO & time Python packages as we will need these to be able to interact with the GPIO pins and also pause our script.

We set 3 variables, the first 2 are references to our pins, and thus I have named appropriately. The current state variable is where we will store our sensor state. If this is 0, then it is off, or 1 means it has been activated.

For this tutorial, we will set our GPIO mode to reference the physical numbering of the pins rather than the actual numbering. This numbering is a little easier to understand/remember as all the pins are numbered in order.

We also set up our GPIO pins to be either outputs or inputs. For example, we want to detect motion so our PIR sensor will be input. On the other hand, our piezo buzzer is going to need to act as an output.

import RPi.GPIO as GPIO
import time

pir_sensor = 11
piezo = 7

GPIO.setmode(GPIO.BOARD)

GPIO.setup(piezo,GPIO.OUT)

GPIO.setup(pir_sensor, GPIO.IN)

current_state = 0

In this next part, we have an infinite while loop. This loop means it will never exit because it is always true. (You can still cancel the script by press ctrl+c in the terminal).

We begin by putting the script to sleep for 0.1 seconds. After this, we get the current state of the sensor, and if it is 1 (e.g. detected motion), then we run the code inside the if statement. If it isn’t 1, then we continue to loop continually checking the sensor.

The code in the if statement sends the piezo buzzer to high that should emit a noise. The script will do this for a second then turn the buzzer off. After this, it will wait for another 5 seconds before exiting the if statement and then rechecking the Raspberry Pi PIR sensor.

We have also nested out code within a try, except, finally block. We have added this because we will need to use the keyboard to stop the script. It is also very important that we run GPIO.cleanup() to ensure our script cleans up nicely. The try, except, finally code allows us to do this.

try:
    while True:
        time.sleep(0.1)
        current_state = GPIO.input(pir_sensor)
        if current_state == 1:
            print("GPIO pin %s is %s" % (pir_sensor, current_state))
            GPIO.output(piezo,True)
            time.sleep(1)
            GPIO.output(piezo,False)
            time.sleep(5)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

Once you have finished working in the script it’s now time to turn it on and test it out. To do this enter the following command:

sudo python motion_sensor.py

If you move in front of the Raspberry Pi PIR sensor, then it should turn the piezo buzzer on and emit a noise.

If it doesn’t then is likely you have hooked up wires to the wrong pins, or there is an error in the code. If it is a code error, you will most likely see an error in the terminal of the Raspberry Pi.

This tutorial is pretty basic and only the beginning of the many applications you can use the PIR sensor. You can get it trigger all sorts of things from something as simple as a counter (counts as people/cars/things go past it), a Raspberry Pi camera, activate a different script and lots more.

I hope you enjoy this Raspberry Pi motion sensor tutorial and have been able to build a cool circuit and bring it to life with code. If you have any feedback, thoughts, troubles or anything else, then feel free to drop us a comment below.

24 Comments

  1. Chuck on

    Very Interesting. Can this setup be used to measure distances using a PIR and a mirror?

  2. Jim Myers on

    Gus – what did you do about an enclosure for the breadboard and motion sensor? Any good ideas? I plan to use this with a battery pack to make it portable.

    Thanks again – Jim

    1. Gus on

      Hi Jim,

      Unfortunately, I never ended up building an enclosure. There are lots of good ideas on 3D print websites such as Thingiverse that’s worth checking out.

  3. Jim Myers on

    Thanks for getting me started. Your project worked great! I substituted a red LED for the speaker and used this to also trigger a camera for a series of 3 snaps.

    Great job –

  4. Jack on

    Can a separate python script be ran from this by replacing
    GPIO.output(piezo,True)
    ? I’d like to set this up and hide it, connected via wifi, running off of a battery, and SSH’d into from my main PC so if I could find a way to have this notify me somehow that’d be perfect.

    1. Gus on

      Yes, in theory, that should work.

  5. Javi on

    Very interesting tutorial. It would be fantastic if. you can teach us how to use a PiCamera instead of a Buzzer ^_^

  6. Lin on

    This is great project! I changed the code for buzzer to a controllable time range and tone.

  7. balasanjeev on

    I need to interface vibration sensor(sw 420) along with pir motion sensor. Is this possible?. i am getting output for pir detection, but have to interface both. can anyone help with code.thanks in advance 🙂

  8. Ivaylo on

    Here is a little modification of the code I did that logs the unix timestamp when a movement is detected to a database . I removed the piezo code because I did not connect piezo speaker to my pi.

    import RPi.GPIO as GPIO
    import time
    import MySQLdb
    
    pir_sensor = 11
    
    conn = MySQLdb.connect(host="localhost", user="test", passwd="", db="nolinka")
    cursor = conn.cursor()
    GPIO.setmode(GPIO.BOARD)
    
    GPIO.setup(pir_sensor, GPIO.IN,GPIO.PUD_DOWN)
    
    current_state = 0
    
    try:
    
        while True:
    
            time.sleep(0.1)
            current_state = GPIO.input(pir_sensor)
    
            if current_state == 1:
                print("GPIO pin %s is %s" % (pir_sensor, current_state))
                ts = time.time()			
                loggit = "UPDATE temperature SET Timestamp=%s WHERE ID=1"
                cursor.execute(loggit, (ts))
                conn.commit()
                time.sleep(1)
                time.sleep(4)
    
    except KeyboardInterrupt:
    
        pass
    
    finally:
    
        GPIO.cleanup()

    You can then convert this value to human time-stamp in php for example:

    while($row2 = mysql_fetch_array($retval2, MYSQL_ASSOC)) {
        $humantime = $row2['Timestamp'];
        $finaltime = date("Y-m-d\ T H:i:s\ ", $humantime);
        echo "last detected movement was on {$finaltime}  ";

  9. krishna on

    how can you do this project but replace the buzzer with a led?

    1. Luigi Lalonde on

      Hi,
      You really just have to physically replace the buzzer with a LED, that’s what I did and it flashes the LED instead of making a sound. No changes needed otherwise 😉

  10. Andy on

    Hello there! I am interested in working on a project similar to this one but i need to add a temperature sensor to this circuit,

    can you please suggest what i should do and what code i have to adjust! thank you for your time!

  11. Citizenchan on

    Thanks for this tutorial. Anyone else able to get the motion sensor working? I’ve got it hooked up exactly as the video, but I only get GPIO 11 is 1, repeating over and over, and either the sensor doesn’t pick up movement, or the signal is not being processing properly. Any ideas on how I can troubleshoot?

    1. Gus on

      Hi Citizenchan,

      On the sensor itself there should be two screws try adjusting these until the sensor is no longer sending pin 11 high all the time. I found it took quite a bit of tinkering to get the perfect level.

      In the script you can also try changing the setup line for the input pin to the following.

      GPIO.setup(pir_sensor, GPIO.IN, GPIO.PUD_DOWN)

  12. Alex on

    Excuse me, I’m working on a project where I have to use multiple PIR sensor. The idea is to use two for each spot to show when is occupy. Also, I have to create an error message if only one sensor is activate. Any suggestions on how can I decelerate multiple PIR sensors? Or create the error message?

  13. Christian Tambe on

    Hello,

    I’m trying to replicate the same project with a passive PIR Motion Sensor and a 30V(P-P) Max peizo transducer from radioshaq, but I’m not getting the same result. I can hear the piezo transducer (buzzer) every 5 seconds without me activating the motion sensor.

    Do you guys see what’s the problem?

    Thanks,

    Christian

    1. Gus on

      Hi Christian,

      There are a couple of things you can do to try and fix this. First try adjusting the two adjustable screws that should be located on the PIR sensor. I had to turn the sensitivity down quite a bit.

      The other option is adding pud_down to to our GPIO.setup line for the sensor. Eg.

      GPIO.setup(pir_sensor, GPIO.IN, GPIO.PUD_DOWN)

      I hope this helps.

    2. Christiatn Tambe on

      Thank you Gus. It’s working now

  14. Nicholas Francis on

    Hi If I wanted to set up a camera to snap shots when the motion detector picks up motion and have it emailed or stored preferably on a cloud what will the coding look like?

    1. Marabiloso on

      Actually, mostly the same… Just replace the line GPIO.output(piezo,True) by the code to take a picture and send it wherever you want (you’re gonna get 1 picture per second, you may want to alter the delay too…)

    2. Nicholas Francis on

      Thank you for the reply. I will try it out.

    3. Nour on

      Hello Gus;
      I see your project for motion sensor; it’s very good, thank you for sending me your tutorials; I built a raspberry webcam server, it’s functional very good, so I have Raspberry pi2 and I’m interested to make surveillance with webcam and if there is a motion detection like you did, the webcam will take a picture and the raspberry pi2 will send an notification e-mail with picture and a small streaming to my email address in Google for example. I saw some examples that send e-mail but not a picture.
      Would you like to help me to build this project? Or would you like to make it in your future tutorials.
      Thank you very much.

Leave a Reply

Your email address will not be published. Required fields are marked *