Raspberry Pi 5 Security Camera: How to Build and Secure One
To build a Raspberry Pi 5 security camera, connect a CSI camera module, install Raspberry Pi OS, and run a short Picamera2 script that records an MP4 clip whenever the picture changes. Then reach the footage through a VPN instead of an open router port. The build takes an afternoon, and every command and script below is ready to paste.
The problem is that most tutorials still point you to motionEyeOS or an old motionEye install. Those were written for earlier boards. The image-based motionEyeOS was never updated for the Pi 5, and the Pi 5 dropped the hardware H.264 encoder, so older recipes either fail or encode slowly. Many guides also tell you to forward a port on your router, which puts an admin page on the public internet.
This guide fixes both issues. You will pick the parts, set up the OS and camera, write the motion recording script, run it on boot, and add AI detection and alerts. At Vadzo we design MIPI CSI-2 camera modules for OEMs, including models with Raspberry Pi 5 driver support. So you will also see where a hobby build and a product build start to differ.
Raspberry Pi 5 Security Camera: What you need before you start
You need a Raspberry Pi 5, a CSI camera, a proper power supply, and fast storage. Plan the whole parts list first, because the Pi 5 has a few quirks that catch people out. Every step below assumes a headless setup that you control over SSH.
Hardware list
Here is a parts list that works for one camera. A Pi 5 with 4 GB of RAM is enough, because the script uses very little memory. The 27W USB-C power supply matters more than the RAM size, since an underpowered Pi throttles and drops frames.
Part | What to get | Why it matters |
|---|---|---|
Board | Raspberry Pi 5 (4 GB or more) | Quad-core CPU handles software H.264 encoding |
Power | Official 27W USB-C supply | Prevents throttling and USB power warnings |
Cooling | Active cooler or a ventilated case | Continuous 1080p encoding runs warm |
Storage | 32 GB+ A2 microSD, or a USB or NVMe SSD | Video writes wear cards quickly |
Camera | Any CSI camera supported on the Pi 5 | See the next section |
Cable | 22-pin to 15-pin adapter, if your camera uses a 15-pin cable | The Pi 5 uses smaller 22-pin camera connectors |
Choosing the camera
For a first build, the official Raspberry Pi Camera Module 3 is the easy answer. It has autofocus and works with the standard camera stack. Pick the NoIR variant only if you will add infrared lighting for night coverage.
Move to an industrial module when the scene is hard. For example, a global shutter sensor avoids skew on fast-moving subjects, and some sensors handle wide temperature ranges. Our Bolt-234CGH is a 2MP global shutter MIPI camera with VCM autofocus, listed from $190. Our Bolt-1335CRS is a 13MP color 4K camera with iHDR and low-light performance, listed from $165. Both ship as bare 38 x 38 mm boards, so you supply the housing. Check what the price includes, because our volume prices exclude lens and cable. Ask our application engineers to confirm driver support for your exact model and Pi 5 OS version before you order.
A security camera is only as good as its worst frame, so choose the sensor for your scene first and the software second.
Step 1. Install the OS and connect the camera
Flash Raspberry Pi OS Lite (64-bit) with SSH enabled, plug in the camera while the Pi is powered off, and confirm the Pi sees it with rpicam-hello --list-cameras. Do this before writing any code, because every later problem is easier to debug once the camera works on its own. This step uses the Raspberry Pi 5 as a headless surveillance camera, with no monitor attached.
Flash Raspberry Pi OS
Open Raspberry Pi Imager on your computer and choose Raspberry Pi OS Lite (64-bit). Open the customisation settings before you write the card. Set a hostname such as camera, create your username and password, add your Wi-Fi details, and enable SSH with your public key. Use Ethernet if you can, because a wired link is more reliable for a device that must run for weeks.
Boot the Pi, then connect and update it:
ssh youruser@camera.local sudo apt update && sudo apt full-upgrade -y sudo reboot
Connect and test the camera
Shut the Pi down and unplug the power. Lift the latch on one of the two camera ports, slide the ribbon cable in fully, and press the latch down. Follow the orientation diagram in the Raspberry Pi camera documentation, because a reversed cable is the most common reason for "no cameras available".
Boot again, then run these checks:
rpicam-hello --list-cameras rpicam-still -n -o test.jpg
The first command should list your sensor. The second saves a still image that you can copy to your computer with scp. Third-party sensors usually need a device tree overlay line in /boot/firmware/config.txt, and the vendor documents it. Use the same checks to aim the camera with a temporary live stream:
rpicam-vid -t 0 -n --codec libav --libav-format mpegts -o "tcp://0.0.0.0:8888?listen=1"
Open tcp://camera.local:8888 in VLC under Open Network Stream. Stop it with Ctrl+C before Step 2, because only one program can own the camera at a time.
If rpicam-hello --list-cameras does not show your sensor, stop and fix that first, because nothing built on top of it will work.
Step 2. Record video when something moves
Install Picamera2 and FFmpeg, then save one Python script that watches a low-resolution copy of the video and records a full 1080p clip while motion continues. The approach keeps CPU use low, because the expensive encoder only runs when there is something to record. A Pi 5 surveillance camera built this way idles at very low load.
Install the packages
The Pi 5 has no hardware H.264 encoder, so the script uses Picamera2's software LibavH264Encoder. The Pi 5's CPU handles 1080p comfortably. Install the dependencies:
sudo apt install -y python3-picamera2 python3-numpy ffmpeg
The motion recording script
Create the file with nano ~/camera.py and paste this in. The script compares each 320 x 240 grayscale frame with the previous one and starts an MP4 when the mean squared difference passes the threshold. It ends the clip after 8 quiet seconds.
#!/usr/bin/env python3 import time from datetime import datetime from pathlib import Path import numpy as np from picamera2 import Picamera2 from picamera2.encoders import LibavH264Encoder from picamera2.outputs import FfmpegOutput OUT_DIR = Path.home() / "recordings" THRESHOLD = 7 # motion score, raise it if you get false triggers COOLDOWN = 8 # seconds without motion before a clip ends LORES = (320, 240) OUT_DIR.mkdir(exist_ok=True) picam2 = Picamera2() config = picam2.create_video_configuration( main={"size": (1920, 1080), "format": "RGB888"}, lores={"size": LORES, "format": "YUV420"}, ) picam2.configure(config) encoder = LibavH264Encoder(bitrate=3_000_000) picam2.start() time.sleep(2) # let auto exposure settle w, h = LORES prev = None recording = False last_motion = 0.0 try: while True: frame = picam2.capture_buffer("lores") cur = frame[: w * h].reshape(h, w).astype(np.int16) if prev is not None: score = np.square(cur - prev).mean() now = time.time() if score > THRESHOLD: last_motion = now if not recording: name = datetime.now().strftime("%Y%m%d-%H%M%S") + ".mp4" picam2.start_encoder(encoder, FfmpegOutput(str(OUT_DIR / name))) recording = True print("Recording", name, flush=True) elif recording and now - last_motion > COOLDOWN: picam2.stop_encoder() recording = False prev = cur finally: if recording: picam2.stop_encoder() picam2.stop()
Run it with python3 ~/camera.py, wave a hand in front of the lens, and check ~/recordings for an MP4. The first seconds of motion are not captured, because the encoder starts after the trigger.
Tune the sensitivity
Start with a threshold of 7. Temporarily add print(round(score, 1)) after the score line and watch the numbers while the scene is still. Set THRESHOLD a little above the highest idle value. Trees, flickering lights, and auto-exposure shifts are the usual causes of false clips. Mount the camera rigidly, because a vibrating mount looks like constant motion.
Tune the threshold against your real scene for ten minutes and you will save yourself days of useless clips.
Step 3. Run the camera on boot and manage storage
Turn the script into a systemd service so the Pi 5 security camera starts after every power cut and restarts after a crash. Then schedule a cleanup job so recordings never fill the disk. Both take about five minutes and make the difference between a demo and a working camera.
Start it as a service
Create the unit file with sudo nano /etc/systemd/system/pi-camera.service. Replace youruser with your username in both places.
[Unit] Description=Pi 5 motion security camera After=network.target [Service] User=youruser ExecStart=/usr/bin/python3 /home/youruser/camera.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
Enable it and check the log:
sudo systemctl enable --now pi-camera.service journalctl -u pi-camera.service -f
You should see a "Recording" line each time something moves. Reboot once to prove it works without you logging in.
Keep the card from filling up
At 3 Mbps, one hour of recorded video is about 1.35 GB. If your scene triggers an hour of motion per day, 14 days of footage takes roughly 19 GB. That fits a 64 GB card with room to spare, but busy scenes need more. Add a daily cleanup with crontab -e:
0 3 * * * find /home/youruser/recordings -name "*.mp4" -mtime +14 -delete
For a camera that records hours each day, use a USB or NVMe SSD instead of the microSD card. Write endurance is the weak point of consumer cards. Change OUT_DIR in the script to the mount point of the drive.
Plan retention in days, calculate the gigabytes, and let a cron job enforce it, or the disk will decide for you.
Step 4. Add AI detection, alerts and safe remote access
Motion alone triggers on cats, shadows, and headlights. To record only people, add a detector that runs when the motion score fires. For alerts, push a notification when a clip starts. For remote viewing, put the Pi on a VPN. This step upgrades your basic Raspberry Pi 5 surveillance camera into one you can trust to ignore noise.
Add AI person detection
You have three practical routes. The principle is the same for all of them: use motion as a cheap gate, then run the model only on frames that pass it. Idle scenes then cost almost nothing.
Route | Where the model runs | Trade-off |
|---|---|---|
Raspberry Pi AI Camera (IMX500) | On the camera module itself | Limited to models the sensor supports |
AI Kit or AI HAT+ (Hailo) | M.2 accelerator on the Pi 5 PCIe port | Extra hardware, best throughput |
CPU only with OpenCV or TFLite | The Pi 5 cores | No extra cost, a few frames per second |
Raspberry Pi's camera software includes demo pipelines for the first two routes, so start with those if you want results quickly. Whichever you pick, change the script so the clip starts only when the detector reports a person, not just when score > THRESHOLD.
Send an alert
A phone alert makes the camera useful in real time. The simplest option is an HTTP push to a service such as ntfy. Add this inside the if not recording: block, right after recording = True:
import subprocess # put this import at the top of the file subprocess.Popen(["curl", "-s", "-d", "Motion detected", "https://ntfy.sh/your-long-random-topic"])
Pick a long random topic name, because anyone who guesses it on the public server can read your alerts. Self-hosting the server avoids that problem entirely.
View it remotely without opening ports
Do not forward a port to the camera. Install a VPN such as Tailscale or WireGuard on the Pi and on your phone or laptop, then reach the Pi by its private address. With Tailscale the install is curl -fsSL https://tailscale.com/install.sh | sh followed by sudo tailscale up. Then copy clips over the private link:
scp youruser@camera:recordings/*.mp4 .
Finish with a short hardening list:
Use key-only SSH and disable password login.
Run sudo apt full-upgrade monthly, or install unattended-upgrades.
Give the Pi no inbound router rules at all.
A camera that anyone on the internet can reach is worse than no camera, so keep it behind a VPN.
Build it once, then tune it
A Pi 5 security camera comes down to four jobs. Get the camera detected, record only on motion with software H.264, run the script as a service with a retention plan, and keep access private. Everything else, including AI detection and alerts, sits on top of that base.
If your project outgrows a hobby setup, for example when you need global shutter capture, 4K sensors, wide temperature range, or a custom board, our engineers can help you choose and integrate a module. Explore Vadzo's camera modules and talk to the application engineering team when you are ready to move from prototype to product.



