Using a Raspberry Pi as security camera hardware gives you total control over your video pipeline, local storage, and integration with home automation systems like Home Assistant. Unlike off-the-shelf IP cameras that lock you into proprietary clouds, a Pi-based setup lets you process frames locally, trigger captures via GPIO sensors, and push alerts over MQTT.
This guide targets the Raspberry Pi 5 (8GB variant) running Raspberry Pi OS Bookworm (64-bit), paired with the Raspberry Pi Camera Module 3 and an HC-SR501 PIR motion sensor. We will use the modern picamera2 and libcamera stack, which completely replaces the legacy picamera library deprecated in recent OS releases.
Estimated Time: 45 minutes
Target Board: Raspberry Pi 5 (8GB) / Raspberry Pi OS Bookworm 64-bit
Hardware Spec Sheet & Camera Module Comparison
Before ordering parts, you need to select the right optical path. The Camera Module 3 introduces the Sony IMX708 sensor, which supports HDR and phase-detection autofocus (PDAF)—a massive upgrade over the fixed-focus V2 module. Below is a data-dense comparison to help you choose the right variant for your security sightlines.
| Module Variant | Sensor | Resolution | Pixel Size | Field of View (FoV) | Approx. Price |
|---|---|---|---|---|---|
| Camera Module V2 | Sony IMX219 | 8 MP | 1.12 µm | 66° | $25 |
| Camera Module 3 (Standard) | Sony IMX708 | 12 MP | 1.4 µm | 66° | $30 |
| Camera Module 3 Wide | Sony IMX708 | 12 MP | 1.4 µm | 102° | $35 |
| HQ Camera (C/CS Mount) | Sony IMX477 | 12 MP | 1.55 µm | Variable (Lens dependent) | $50 + Lens |
Exact Parts List for This Build
- Compute: Raspberry Pi 5 (8GB RAM) - The 8GB variant prevents buffer allocation errors when capturing 12MP stills alongside preview streams.
- Optics: Raspberry Pi Camera Module 3 (Standard) or Module 3 Wide (for hallways/corners).
- Interconnect: 15-pin to 15-pin CSI ribbon cable (1-meter length for flexible mounting).
- Trigger: HC-SR501 PIR Motion Sensor (adjustable delay and sensitivity potentiometers).
- Power: Official Raspberry Pi 27W USB-C PD Power Supply (5V/5A). Do not use a standard 15W phone charger; the Pi 5 will throttle USB and peripheral power under load.
Wiring the Pi 5, Camera Module 3, and PIR Sensor
The physical layer is where most security camera builds fail. The CSI (Camera Serial Interface) ribbon cable is fragile, and the PIR sensor requires clean 5V logic to avoid false motion triggers.
Pin Mapping Table: HC-SR501 to Pi 5 GPIO
| HC-SR501 Pin | Pi 5 GPIO / Power | Physical Pin # | Wire Color (Standard) |
|---|---|---|---|
| VCC | 5V | Pin 2 | Red |
| OUT | GPIO 17 | Pin 11 | Yellow |
| GND | Ground | Pin 9 | Black |
Assembly Steps
- Seat the CSI Cable (Pi 5 End): Gently pull the black plastic locking collar on the Pi 5 CSI port outward (it only moves 1mm). Insert the ribbon cable. Critical: The blue stiffener tape on the cable must face outward toward the USB/Ethernet ports. The bare copper traces must face inward toward the HDMI connectors.
- Lock the Collar: Push the black collar back in evenly. Do not force it; if it snags, the cable is crooked.
- Seat the CSI Cable (Camera End): Repeat the process on the Camera Module 3. The blue tape faces the back of the PCB (away from the lens).
- Wire the PIR Sensor: Connect the HC-SR501 VCC, OUT, and GND pins to the Pi 5 according to the pin mapping table above. Adjust the orange potentiometers on the PIR: turn the delay pot fully counter-clockwise (minimum ~3s delay) and the sensitivity pot to the middle position to prevent thermal noise triggers.
- Power Up: Connect the 27W USB-C supply and boot into Raspberry Pi OS Bookworm.
Python Motion-Triggered Capture Code
The legacy picamera library is dead. For the Pi 5 and Bookworm OS, you must use picamera2, which interfaces directly with the libcamera C++ framework via Python bindings. Install the prerequisites via terminal:
sudo apt update
sudo apt install python3-picamera2 python3-libcamera python3-gpiozero
The following script initializes the camera, configures a high-resolution still stream, and waits for the PIR sensor to pull GPIO 17 high. It includes robust error handling to gracefully shut down the camera pipeline if interrupted.
import os
import time
from picamera2 import Picamera2
from gpiozero import MotionSensor
# --- PIN & PATH DEFINITIONS ---
PIR_GPIO_PIN = 17
SAVE_DIRECTORY = "/home/pi/security_captures"
# Ensure storage directory exists
os.makedirs(SAVE_DIRECTORY, exist_ok=True)
# Initialize hardware
pir = MotionSensor(PIR_GPIO_PIN)
picam2 = Picamera2()
# Configure camera for 12MP still captures
# We use a dedicated still configuration to maximize IMX708 resolution
config = picam2.create_still_configuration()
picam2.configure(config)
print("Starting camera pipeline...")
picam2.start()
# Allow the IMX708 sensor to adjust gain and white balance
time.sleep(2)
try:
print("Security camera active. Waiting for motion on GPIO 17...")
while True:
# Block until PIR OUT goes HIGH
pir.wait_for_motion()
timestamp = time.strftime("%Y%m%d-%H%M%S")
filepath = os.path.join(SAVE_DIRECTORY, f"intruder_{timestamp}.jpg")
# Capture and save to disk
picam2.capture_file(filepath)
print(f"[{time.strftime('%H:%M:%S')}] Motion detected. Saved: {filepath}")
# Block until PIR OUT goes LOW to prevent burst-flooding the storage
pir.wait_for_no_motion()
except KeyboardInterrupt:
print("\nKeyboard interrupt received.")
except Exception as e:
print(f"\nFatal error in capture loop: {e}")
finally:
print("Stopping camera pipeline and releasing resources...")
picam2.stop()
print("System halted safely.")
Debugging: "libcamera FATAL: *** no cameras available ***"
When working with the modern libcamera stack, the most common roadblock is the system failing to enumerate the sensor on the I2C/CSI bus. If you run the script and encounter this exact error block:
Traceback (most recent call last):
File "camera.py", line 14, in <module>
picam2 = Picamera2()
RuntimeError: Failed to configure camera configuration
This means the OS cannot communicate with the IMX708 sensor. Here are the ranked causes and the first three things to check when it fails:
- Ribbon Cable Orientation and Seating (90% of failures): The CSI cable is directional. If the blue tab is facing the wrong way, the data lanes are crossed. Furthermore, if the cable isn't pushed in perfectly straight before locking the collar, the I2C clock line (used for sensor discovery) will fail to make contact. Fix: Power down, unlatch both ends, verify blue tape orientation, reseat perfectly square, and latch.
- Legacy OS or Incompatible Kernel: The
picamera2library requires thelibcameraDRM/KMS stack, which is only fully supported on Raspberry Pi OS Bullseye (late updates) and Bookworm. If you flashed an older Buster image, or if you enabled the legacy camera stack inraspi-config, the modern library will fail. Fix: Flash a fresh Bookworm 64-bit image. Do not enable "Legacy Camera" in raspi-config; leave it disabled. - Power Supply Brownout: The Pi 5 requires a 5V/5A (27W) PD supply to maintain full peripheral voltage under load. If you are using a 15W phone charger, the Pi 5 will aggressively throttle power to the USB and CSI rails when the CPU spikes during boot, causing the camera I2C initialization to time out. Fix: Verify you are using the official 27W Pi 5 power supply. Check
dmesg | grep -i voltagefor undervoltage warnings.
Always verify hardware connectivity via the terminal before running your Python script:
libcamera-hello -t 5000
If this command opens a 5-second preview window, your hardware and OS stack are healthy, and any subsequent Python errors are strictly in your code logic.
Extending and Simplifying the Build
A barebones Pi security camera is a great starting point, but you will likely want to tailor the complexity to your specific deployment environment.
How to Simplify (No Hardware Wiring)
If you want to eliminate the HC-SR501 PIR sensor and the GPIO wiring entirely, you can rely on software-based motion detection. By integrating OpenCV (cv2), you can compare consecutive frames from the camera's low-resolution preview stream. If the pixel delta exceeds a set threshold, the script triggers a high-res capture. This reduces your BOM (Bill of Materials) to just the Pi and Camera, but it increases CPU load and requires careful tuning of the delta threshold to avoid false triggers from shifting shadows or sunlight.
How to Extend (AI & Smart Home Integration)
For a production-grade security node, extend the build in these two directions:
- Edge AI Object Detection: The Pi 5 features a PCIe 2.0 interface. By adding the Raspberry Pi AI Kit (Hailo-8L), you can run local YOLOv8 inference to differentiate between a human, a stray cat, and a swaying tree branch. This eliminates the "false positive" fatigue that plagues basic PIR setups.
- MQTT & Home Assistant: Instead of just saving a JPEG to local storage, import the
paho-mqttPython library. When motion is detected, publish a payload to your local Mosquitto broker (homeassistant/sensor/frontdoor/motion) and push the image URL via a Telegram or Discord webhook API. This transforms the Pi from a standalone DVR into an active smart-home sentinel.
Building a Raspberry Pi as security camera hardware bridges the gap between embedded systems engineering and practical home security. By leveraging the Pi 5's processing headroom and the IMX708 sensor's HDR capabilities, you get a highly customizable, locally-hosted surveillance node that outperforms commercial alternatives in flexibility and privacy.






