How to Use PIR Sensor with Raspberry Pi: Simple Guide
To use a
PIR sensor with a Raspberry Pi, connect its output pin to a GPIO pin on the Pi and power it with 5V and ground. Then, write a Python script using the RPi.GPIO library to read the sensor's digital signal and detect motion.Syntax
Here is the basic syntax to read a PIR sensor using Python on Raspberry Pi:
GPIO.setmode(GPIO.BCM): Sets the pin numbering system.GPIO.setup(pin, GPIO.IN): Sets the PIR sensor pin as input.GPIO.input(pin): Reads the sensor state (0 or 1).
python
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # Use Broadcom pin numbering pir_pin = 4 # Connect PIR output to GPIO4 GPIO.setup(pir_pin, GPIO.IN) # Set pin as input try: while True: if GPIO.input(pir_pin): print("Motion Detected!") else: print("No Motion") time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
Example
This example shows how to detect motion with a PIR sensor connected to GPIO4 on the Raspberry Pi. It prints "Motion Detected!" when movement is sensed and "No Motion" otherwise.
python
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) pir_pin = 4 GPIO.setup(pir_pin, GPIO.IN) print("PIR Sensor Test (CTRL+C to exit)") try: while True: if GPIO.input(pir_pin): print("Motion Detected!") else: print("No Motion") time.sleep(1) except KeyboardInterrupt: print("Exiting program") GPIO.cleanup()
Output
PIR Sensor Test (CTRL+C to exit)
No Motion
No Motion
Motion Detected!
Motion Detected!
No Motion
...
Common Pitfalls
- Incorrect wiring: Make sure the PIR sensor's output pin connects to a GPIO input pin, and power pins connect to 5V and ground correctly.
- Wrong GPIO numbering: Use
GPIO.BCMmode if you refer to GPIO numbers, not physical pin numbers. - No pull-up/down resistor: PIR sensors usually have built-in resistors, but if unstable readings occur, check wiring.
- Not cleaning up GPIO: Always call
GPIO.cleanup()to reset pins after your program ends.
python
import RPi.GPIO as GPIO # Wrong way: Using physical pin numbering but setting BCM mode GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN) # Pin 7 is physical pin, not BCM GPIO7 # Right way: GPIO.setmode(GPIO.BOARD) # Use physical pin numbering GPIO.setup(7, GPIO.IN) # Now pin 7 means physical pin 7
Quick Reference
Summary tips for using PIR sensor with Raspberry Pi:
- Connect PIR output to a GPIO input pin (e.g., GPIO4).
- Power PIR sensor with 5V and ground pins.
- Use
GPIO.setmode(GPIO.BCM)for GPIO numbering. - Read sensor state with
GPIO.input(pin). - Use
try-exceptto handle exit and cleanup GPIO.
Key Takeaways
Connect PIR sensor output to a Raspberry Pi GPIO input pin and power it properly.
Use Python with RPi.GPIO library to read the sensor's digital signal for motion detection.
Set GPIO mode to BCM to use GPIO pin numbers correctly.
Always clean up GPIO pins with GPIO.cleanup() after your program ends.
Check wiring and pin numbering carefully to avoid common mistakes.