Close Menu
    Facebook X (Twitter) Instagram Pinterest YouTube
    Trending
    • Disable SSH Password Login on Raspberry Pi
    • Elecrow Meteor IPS Touchscreen with RGB LEDs
    • Pi Pico Pinout Display on the Command Line
    • How to Add a Raspberry Pi Pico Reset Button
    • Pi Pico Onboard LED
    • Pi Pico W Pinout and Power Pins
    • CrowPi L Raspberry Pi Laptop and Learning Platform
    • Pi Pico W Launched
    Mastodon YouTube Facebook Instagram Pinterest RSS
    Raspberry Pi SpyRaspberry Pi Spy
    • Home
    • Categories
      • General
      • Hardware
      • Programming
      • Python
      • Software
      • Tutorials & Help
    • BerryClip
      • BerryClip Instructions
      • BerryClip Plus Instructions
      • Videos & Reviews
    • Buy
      • Buy Pi
      • Buy Pi Accessories
      • Buy Books
    • Tools
      • Ultimate Raspberry Pi Alexa Skill
      • Pi Power Estimator App
      • Pi-Lite 14×9 LED Matrix Sprite Editor
      • RPiREF Pin-out Reference App
      • Simple Ohm’s Law Calculator
      • Web Sites & Links
    • Tutorials & Help
        Featured
        November 9, 20200

        Raspberry Pi Temperature Monitoring

        Recent
        February 16, 2024

        Disable SSH Password Login on Raspberry Pi

        December 23, 2022

        How to Add a Raspberry Pi Pico Reset Button

        November 20, 2022

        Pi Pico Onboard LED

      1. Contact Us
      2. Site Map
      Raspberry Pi SpyRaspberry Pi Spy
      You are at:Home»Hardware»Cheap PIR Sensors and the Raspberry Pi – Part 1
      PIR Module #1

      Cheap PIR Sensors and the Raspberry Pi – Part 1

      40
      By Matt on January 21, 2013 Hardware, Python

      PIR Module #1A great little sensor you can add to your Raspberry Pi projects is a PIR module. These 5V “Passive Infra Red” sensors are available for a few pounds from eBay. They can be powered from 5V and output 3V so can be connected directly to pins on the Pi’s GPIO header without any other components.

      The module sets a single output pin high whenever it detects movement within its field of view. It holds this pin High (3.3V) for a minimum period of time. If continuous movement is detected the output pin will stay High. When the time has elapsed and no more movement is detected the output pin returns Low (0V).

      I am currently using one in an alarm system and it works great for such a small and cheap device.

      PIR Connections

      Here is a diagram showing the pin-out on the PIR module and how I connected it to my Raspberry Pi :

      PIR Module
      PIR Module

      The device has two variable resistors that you can adjust to tweak the performance of the module.

      PIR Module #2
      Trimming Controls

      The first one (left-hand side on the photo) determines the sensitivity of the device. The default setting is usually 50%.

      The second control (right-hand side on the photo and usually marked “time” on the PCB) allows you to adjust the amount of time the output pin stays at 3V (high) when it is triggered by movement. This can be set from a few seconds to 200 seconds. The default setting is usually a few seconds.

      You can find on eBay vary in specification but they are all very similar.

      Python Example Script

      If you connect your module as shown in the diagram above the following Python script will allow you to get started. Cut and paste the script below into a text file and transfer to the Pi or download the script directly using this link.

      #!/usr/bin/python
      #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      #|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
      #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      #
      # pir_1.py
      # Detect movement using a PIR module
      #
      # Author : Matt Hawkins
      # Date   : 21/01/2013
      
      # Import required Python libraries
      import RPi.GPIO as GPIO
      import time
      
      # Use BCM GPIO references
      # instead of physical pin numbers
      GPIO.setmode(GPIO.BCM)
      
      # Define GPIO to use on Pi
      GPIO_PIR = 7
      
      print "PIR Module Test (CTRL-C to exit)"
      
      # Set pin as input
      GPIO.setup(GPIO_PIR,GPIO.IN)      # Echo
      
      Current_State  = 0
      Previous_State = 0
      
      try:
      
        print "Waiting for PIR to settle ..."
      
        # Loop until PIR output is 0
        while GPIO.input(GPIO_PIR)==1:
          Current_State  = 0
      
        print "  Ready"
      
        # Loop until users quits with CTRL-C
        while True :
      
          # Read PIR state
          Current_State = GPIO.input(GPIO_PIR)
      
          if Current_State==1 and Previous_State==0:
            # PIR is triggered
            print "  Motion detected!"
            # Record previous state
            Previous_State=1
          elif Current_State==0 and Previous_State==1:
            # PIR has returned to ready state
            print "  Ready"
            Previous_State=0
      
          # Wait for 10 milliseconds
          time.sleep(0.01)
      
      except KeyboardInterrupt:
        print "  Quit"
        # Reset GPIO settings
        GPIO.cleanup()

      This script can also be downloaded onto your Pi directly using this command line :

      wget https://www.raspberrypi-spy.co.uk/archive/python/pir_1.py

      This can then be run using :

      sudo python pir_1.py

      When run the script waits for the output pin to go Low. It then prints a message to the screen every time the output state changes. This is either when movement is detected (output changes to High) or the device sees no movement (outout changes to Low).

      Try changing the reset time by turning the “time” resistor clockwise by a few degrees. Run the script again, trigger the device and then wait to see how long it takes to go back to the ready state.

      Photos

      Here some more detailed photos of the PIR pins and two trimming controls :

      PIR Module #1
      PIR Module #2
      PIR Module
      PIR Module #3
      PIR Module #4
      PIR Module #5

      Calibration

      In Cheap PIR Sensors and the Raspberry Pi – Part 2 I show you how to calibrate your sensor to fine tune its performance.

      Applications

      The applications of this circuit include :

      • Security systems
      • Automatic photographs
      • Robot sensors

      Related Articles

      Here are some of my other articles you might find interesting if you enjoyed this one :

      • Ultrasonic Distance Measurement Using Python – Part 1
      • Ultrasonic Distance Measurement Using Python – Part 2
      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous ArticleTop 8 Free Windows Tools for Raspberry Pi Development
      Next Article Gertboard – The Ultimate Raspberry Pi Add-on Board

      Related Posts

      Elecrow Meteor IPS Touchscreen with RGB LEDs

      Pi Pico Pinout Display on the Command Line

      How to Add a Raspberry Pi Pico Reset Button

      40 Comments

      1. Michael Horne on January 22, 2013 7:47 am

        Hi Matt.
        Great information as usual.
        I don’t suppose you have a link to the eBay lot you purchased from, do you? Or a part number? I have one of these cheap sensors but without the trimmers and the pin-outs do vary a bit!
        —
        Mike

        Reply
        • Matt on January 22, 2013 6:24 pm

          The last two I got from eBay were from a seller called “abeyerr”. If you search for “PIR Motion Sensor Detector Module” you should see a load that look like the ones in my photos with the two trimmers on them.

          Reply
      2. Peter Bennett on January 25, 2013 10:02 pm

        I got one locally and also added this URL to my wish list.

        http://www.aliexpress.com/item/Free-Ship-10PCS-LOT-HCSR501-HC-SR501-NEW-Adjust-Infrared-IR-PIR-Motion-Sensor-Detector-Module/519751367.html

        Thanks Matt. Making a new breakout board to start testing one. To be added to the outdoor camera I am working on.

        —
        Peter

        Reply
      3. Ricardo Arturo Cabral on January 26, 2013 7:26 pm

        You can also buy a simplified version (no sensitivity or timing adjustment pot) from http://www.seeedstudio.com. I got mine from their website to use it with an Arduino but I have never hooked it up with the Raspberry Pi.

        Reply
      4. Duder on February 22, 2013 9:57 am

        Just a quick question about the diagram. It says to connect the module to the Pi via pin 2 and 6 for power.

        Isn’t Pin 2 for power “input” to the Pi? I read in another article on here that this Pin was used to power the Pi from batteries. So now I wonder how this Pin 2 can output 5V as well as take in 5V.

        Can anybody explain?

        Reply
        • Ben on February 24, 2013 3:52 pm

          If you don’t have a supply connected in the “usual” manner by the mini USB port you COULD supply the Raspberry by via it’s GPIO port on Pin 2.

          Should you already have the Pi powered up in the normal way, then +5V is presented to the GPIO pin which can then be used to supply other devices. Not to sure what sort of power you can draw from it though, guessing it won’t be all that much.

          Hope that helps

          Reply
      5. Eder Ollora Zaballa on February 25, 2013 11:21 pm

        Hi!

        That was an incredible post and thank to the post you explain how to install RPI GPIO package which helped too. I think a very good post.

        By itself the PIR and the script aren’t very useful but as soon as I run this script with a webcam and an automatic email sender script, this will be my next surveillance system 😉

        So thanks to you and thanks for taking your time, it really helps.

        Reply
      6. Pete on March 11, 2013 9:43 pm

        Hi,

        Thanks for this, it is very useful. I would like to suggest an improvement, if you put at the end of the loop but still within the loop a ‘time.sleep(0.01)’ (you will also need to import time). It will pause the software for just 10ms each loop allowing the processor to do other things. if you look at CPU stats, before doing this, python will take up all available processor power now it only take about 2%.

        Many thanks

        Reply
      7. Chook on April 8, 2014 9:07 pm

        HI,

        thanks a lot for your post!

        very simple and basic, so I guess that even I understood it this time 😉

        My problem is, that it doesnt matter if the PIR is assembled or not, the screen alternates between the two messages “ready” and “motion detected”.
        I tried to vary the potis, but without any success.

        Has someone a explanation for me?

        Reply
      8. Will on April 14, 2014 5:08 pm

        Hi there,
        I’m using this script to trigger the pi camera and have it in rc.local in order to run on startup, however, ctrl-c doesn’t exit the script and I’m stuck before the login screen permanently!

        Any ideas about what’s caused this?

        Cheers!
        Will

        Reply
        • David Ferguson on April 21, 2014 7:31 pm

          You can add a & sign to the end of your command in rc.local to make it run in the background. This will allow you to get to the login screen and use your Pi whilst it runs.

          Before:
          sudo python ~/pir.py

          After:
          sudo python ~/pir.py &

          Reply
      9. Pingback: Ultrasonic Distance Measurement Using Python – Part 2 | Raspberry Pi Spy

      10. Rubén García on April 24, 2014 10:17 pm

        Thanks a lot. Works perfectly. I have created a script based on the showed here, that use Pushover.net service to send push notifications to other devices and apps.
        The script has an .ini file to locate the script and configure it.

        Im using screen to run on the background.
        The Github repo is here:
        https://github.com/espunny/raspberrypi-Alarm
        to install:
        git clone https://github.com/espunny/raspberrypi-Alarm.git

        Corrections and suggestions are welcome.

        Reply
      11. Tony on May 19, 2014 8:48 pm

        Great little demonstrator. Instructions spot on worked first time. Now working on using Netio to set and unset it from outside the house, send picture via email from my PI Cam when triggered and then looking at hooking another PIR sensor up to a xbee module so I can have wireless remote sensors around the house. (I think that bit may be a bit more difficult!)

        Thanks

        Reply
      12. Jones on May 31, 2014 10:00 am

        Thanks for the script, it helped me a lot.
        But why do say that pin 6 is ground? I think that should be pin 7. It took me (an absolute beginner) a while to notice that it was wrong wired.

        Reply
        • Matt on May 31, 2014 12:48 pm

          On the Pi GPIO header Pin 6 is ground. Pin 7 is GPIO4. Take a look at the GPIO diagram on my Simple Guide to the RPi GPIO Header and Pins.

          Reply
          • Jones on May 31, 2014 2:00 pm

            Ah ok, sorry. I didn’t know that you are counting row-wise and not column-wise. Thanks!

            Reply
      13. Olaf on July 16, 2014 2:44 pm

        Thanks for this excellent tutorial.
        Do you have any knowledge about sizes and ranges this PIR sensor can detect?
        Looking for something to detect ‘fox sized’ animals in a 10meters range at night.
        Would that be possible?

        Reply
        • Matt on July 16, 2014 9:59 pm

          At the weekend we are deploying a wildlife camera in our garden using one of those sensors. I will try and get a better idea of range and post an update.

          Reply
          • Olaf on August 12, 2014 2:35 pm

            Hi Matt,
            Don’t want to put you under pressure – if you have any news regarding your test it would be nice if you can let me know.
            Cheers

            Reply
          • a2moosh on August 28, 2014 4:50 pm

            pir sensor is nice – anyway for you too I would recommend to use the motion-software that registers movements in front of the cam and can be set quite precise regarding amount of changed pixels, quality and “frames to record” before movement starts.

            Reply
            • Olaf on September 4, 2014 11:00 am

              @a2moosh: for the darkness I’m looking for some infrared led’s that could help raspberry’s PiNoir camera to help taking good pictures.
              Wasn’t successful yet, even with infrared led’s from the wildlife camera the raspberry picture quality is, well, ‘improvable’. Do you have anything there that works? Any suggestions? Any particuler devices? Cheers.

              Reply
      14. Pingback: Raspberry Pi Project : Motion Sensor Fortune Teller by Richard Julian

      15. Osiris on September 2, 2014 4:18 pm

        Thx Matt, I’ve used your script as a base for my worksite-surveillance script.
        I’m constructing a house & have 2 raspberry pi’s hanging around.
        It takes pictures at certain intervals and/or when motion is sensed

        https://github.com/TrueOsiris/pirsnap

        Reply
        • Matt on September 2, 2014 11:57 pm

          I’m looking forward to the first new story where a Raspberry Pi camera catches a burglar. Anything I can do to help that happen is great 🙂 I really must put more time into my security system which was the whole idea of me getting a Pi before I created this site!

          Reply
          • Steve on May 27, 2016 2:20 pm

            I’ve had two instances of clandestine dog pooping with no scooping since I got mine going. A gentle reminder to the owner that picking up after the dog would be much appreciated (bolstered with a finger point to the sensor and webcam in my front window) did the trick!

            Reply
      16. Jekl on September 5, 2014 7:27 pm

        Hey Matt,

        Thanx for your work, I am using this script to make my first steps on working with sensors!

        Reply
      17. Enno Lenze on September 9, 2014 4:47 pm

        yeaaahh! Thanks a lot. Took me 5 minutes and works perfectly! 🙂

        Reply
      18. Pingback: Détecteur de mouvement (PIR) du Raspberry Pi à la ZiBASE – Part 1/3 | Onlinux

      19. Pingback: Animalcam version 1 | garysshed.co.uk

      20. Matthias on December 3, 2014 11:36 am

        Hi Matt,

        If I understand this correctly, one could connect several PIR sensors to one RPi by just using different GPIO pins.
        However, do you have any idea/experience about the cables that can be used and their length in particular? Could I have the RPi in a central location and run the PIRs from anywhere in the house?

        Thanks for this great article!
        Matthias

        Reply
        • Matt on December 4, 2014 4:23 pm

          I think it would be a case of trying it with different cable lengths. I run two magnetic switches with 10 metres of telephone cable in my garage security system onto the GPIO and they work fine. Some people claim it shouldn’t work but it works just fine!

          Reply
      21. jacob on December 4, 2014 3:12 am

        This is one of the best tutorials I found to help connect this PIR to the raspberry pi and the script seems solid with only one current problem. I’m getting “Waiting for PIR to settle …” and it just sits here.

        Anyone have an idea what is wrong?

        Reply
      22. jacob on December 4, 2014 3:39 am

        amazing… googled the PIR model I had and although it physically looks like 90% of the other modules out there. This one had the ground and power reversed. It works!!!!

        Reply
      23. Pingback: Sensor de presencia en Raspberry Pi | Internet de las Cosas

      24. Doug Wyman on May 22, 2015 6:07 pm

        I have instructions on enclosing the PIR sensor for outdoor use. I also have Python code there for running multiple sensors on the Raspberry Pi

        Reply
      25. Pingback: Animalcam version 2 | garysshed.co.uk

      26. Sebastian on October 8, 2016 6:58 pm

        Nice Programm.
        Is there a possibility to safe the motion detection into a file? I want to know when the detector detect a motion.

        Can the programm also be autostarted?

        Reply
        • Matt on October 12, 2016 8:31 pm

          I would be possible to add a line to a text file with the time the motion was detected. Read up on the Python “open” command.

          Reply
      27. JimBob Electronics from the Ozarks on July 13, 2017 3:41 am

        Be careful! Some of these IR devices have the VCC swapped with GND vrs the diagram here.
        To be sure take off the plastic lens deal and look at the silkscreened labeling underneath.

        Reply
      Leave A Reply Cancel Reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Recent Posts
      February 16, 2024

      Disable SSH Password Login on Raspberry Pi

      March 13, 2023

      Elecrow Meteor IPS Touchscreen with RGB LEDs

      December 26, 2022

      Pi Pico Pinout Display on the Command Line

      December 23, 2022

      How to Add a Raspberry Pi Pico Reset Button

      November 20, 2022

      Pi Pico Onboard LED

      Categories
      • 1-wire
      • 3D Printing
      • Add-ons
      • BBC Micro:bit
      • BerryClip
      • Books
      • Camera Module
      • Cases
      • Events
      • General
      • Hardware
      • I2C
      • Infographics
      • Interfaces
      • Minecraft
      • Model A+
      • Model B+
      • News
      • Pi Models
      • Pi Pico
      • Pi Zero
      • Power
      • Programming
      • Python
      • Raspberry Pi OS
      • Raspbian
      • RetroGaming
      • Robotics
      • Sensors
      • Software
      • SPI
      • Tutorials & Help
      Tags
      Arduino audio battery berryclip Birthday bluetooth cambridge camera CamJam DigiMakers display games GPIO I2C interface Kickstarter Kodi LCD LED Linux media Minecraft Model A motionEyeOS PCB photography photos Pi-Lite Pi Pico power python Raspberry Jam Raspberry Pi Bootcamp raspbian Retrogaming retroPie screen SD card security sensor SPI SSH temperature ultrasonic video
      Raspberry PI Related
      • Adafruit Blog
      • Average Maker
      • Official RaspBerry Pi Site
      • Raspberry Pi Pod
      • RasPi.tv
      • RaspTut
      • Stuff About Code
      Tech Resources
      • MattsBits – Pi Resources
      • Microbit Spy
      • Technology Spy
      Archives

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2025 - All Rights Reserved - Matt Hawkins

      About

      Unofficial site devoted to the Raspberry Pi credit card sized computer offering tutorials, guides, resources,scripts and downloads. We hope to help everyone get the most out of their Pi by providing clear, simple articles on configuring, programming and operating it.

      Popular Posts
      September 19, 2014

      Top 5 Reasons The Raspberry Pi Sucks

      July 27, 2012

      16×2 LCD Module Control Using Python

      October 20, 2013

      Analogue Sensors On The Raspberry Pi Using An MCP3008

      Latest Posts
      February 16, 2024

      Disable SSH Password Login on Raspberry Pi

      March 13, 2023

      Elecrow Meteor IPS Touchscreen with RGB LEDs

      December 26, 2022

      Pi Pico Pinout Display on the Command Line

      Mastodon YouTube Instagram Facebook Pinterest RSS

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2025 - All Rights Reserved - Matt Hawkins

      mastodon.social@RPiSpy

      Type above and press Enter to search. Press Esc to cancel.