A passive infrared (PIR) sensor notices warm bodies moving in front of it. Pair one with a Raspberry Pi camera and you have a trail camera, a doorway logger or a bird-feeder cam that only saves the interesting moments.
What you need
- Raspberry Pi 5
- Raspberry Pi Camera Module 3 – the Wide version captures more of the scene
- Raspberry Pi 5 camera cable – Pi 5 uses the smaller camera connector
- PIR motion sensor
- Female/female jumper wires
- Raspberry Pi 27W USB-C power supply
1. Connect the camera
With the Pi powered off, open one of the two CAM/DISP connectors on the Pi 5 by lifting its latch, insert the narrow end of the Pi 5 camera cable with the contacts facing inwards, and close the latch. Connect the wide end to the camera the same way. Then check the camera from a terminal:
rpicam-hello -t 5000
A five-second preview should appear on the desktop. On Raspberry Pi OS Lite, install the Python camera library with sudo apt install -y python3-picamera2 --no-install-recommends. It is already included in the desktop version.
2. Wire the PIR sensor
| PIR sensor | Raspberry Pi pin |
|---|---|
| + (power) | Pin 2 (5V) |
| OUT | Pin 11 (GPIO 17) |
| − (ground) | Pin 6 (GND) |
The Adafruit PIR is powered from 5V but its output signal is 3.3V, so it is safe to connect directly to a GPIO pin. Give it about a minute after power-up to settle.
Tip: The two small knobs on the PIR adjust sensitivity and how long the output stays on after motion. Turn the time knob fully anticlockwise for the shortest pulse.
3. The code
Save as motioncam.py:
import time
from datetime import datetime
from pathlib import Path
from gpiozero import MotionSensor
from picamera2 import Picamera2
out = Path.home() / "captures"
out.mkdir(exist_ok=True)
pir = MotionSensor(17)
cam = Picamera2()
cam.configure(cam.create_still_configuration())
cam.start()
time.sleep(2) # let exposure settle
print("Waiting for motion…")
while True:
pir.wait_for_motion()
name = out / datetime.now().strftime("%Y%m%d-%H%M%S.jpg")
cam.capture_file(str(name))
print("Saved", name)
pir.wait_for_no_motion()python3 motioncam.py
Wave a hand in front of the sensor: a photo lands in ~/captures each time.
4. Make it a proper trail cam
-
Start at boot: add
@reboot python3 /home/yourname/motioncam.pytocrontab -e. - Night shots: the NoIR Camera Module 3 sees infrared. Add an IR illuminator for invisible night lighting.
-
Video clips: Picamera2 can record a few seconds of H.264 video instead of a still. See its manual for
start_and_record_video. - Weatherproofing: PIR sensors can't see through glass, so use a box with a cut-out for the sensor dome.