A MotionSensor (PIR) detects movement by sensing changes in infrared light. It helps your Raspberry Pi know when someone or something moves nearby.
0
0
MotionSensor (PIR) in Raspberry Pi
Introduction
To turn on a light automatically when someone enters a room.
To start recording video only when motion is detected.
To alert you if someone moves near your Raspberry Pi setup.
To save energy by activating devices only when needed.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) PIR_PIN = 7 GPIO.setup(PIR_PIN, GPIO.IN) try: while True: if GPIO.input(PIR_PIN): print("Motion Detected!") else: print("No Motion") time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
Use GPIO.setmode(GPIO.BCM) to refer to pins by their Broadcom number.
Always clean up GPIO pins with GPIO.cleanup() to avoid warnings.
Examples
Check if motion is detected on pin 7 and print a message.
Raspberry Pi
GPIO.setup(7, GPIO.IN) if GPIO.input(7): print("Motion detected!")
Check motion every half second and print "Motion!" if detected.
Raspberry Pi
import time while True: if GPIO.input(7): print("Motion!") time.sleep(0.5)
Sample Program
This program continuously checks the PIR sensor on pin 7. It prints "Motion Detected!" when it senses movement, otherwise "No Motion". Press Ctrl+C to stop safely.
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) PIR_PIN = 7 GPIO.setup(PIR_PIN, GPIO.IN) print("Starting motion sensor. Press Ctrl+C to stop.") try: while True: if GPIO.input(PIR_PIN): print("Motion Detected!") else: print("No Motion") time.sleep(1) except KeyboardInterrupt: print("Stopping motion sensor.") GPIO.cleanup()
OutputSuccess
Important Notes
Make sure your PIR sensor is connected correctly: power, ground, and signal to the correct GPIO pin.
Sometimes PIR sensors need a few seconds to warm up before detecting motion.
Use try-except to handle stopping the program safely and cleaning GPIO pins.
Summary
A PIR MotionSensor detects movement by sensing infrared changes.
Use GPIO input to read the sensor state on your Raspberry Pi.
Always clean up GPIO pins when your program ends.