Monday 4 November 2013

A Raspberry Pi Security Camera
2013-11-04

I'd been looking for uses for my raspberry pi, and it finally hit me:  a security camera!

Given I already had the pi, and a charger, all else I needed was a webcam.  For this, I chose the Nexxtech HD Webcam; it's a decent little unit, with a 1280x720 CMOS sensor and plenty of low-level light pickup, and a relative bargain for $29 at The Source.

I rigged up a case for the pi from an empty cigarette pack; the new 25s are perfect for this.  With that, I just had to rig a little shelf, in the window beside the door, on top of which went the webcam, and away I went.  Perhaps the most technically challenging moment came in figuring out a way to run power to the downstairs entrance!

Now, you know me; I don't do things the easy way; I do them the efficient way.  I didn't want some GUI setup to worry about; everything would have to be done from the command line.  With that in mind...

The preliminaries:  I had to install a few things that weren't in the default Raspbian setup:
- Apache2
- fswebcam
- ImageMagick (just in case)
- Possibly others

The capture portion was easy enough to set up, with the proviso that the brightness be adjusted for day and night.  The image should be in two sizes, and should be saved to /var/www.  I put it into a shell script:

nano /home/pi/webcam.sh

#!/bin/bash
time=$(date "+%H%M")
if ((630 < 10#$time && 10#$time < 1700)); then 
    fswebcam -D 1 -f 2 --set brightness=20% -r 1280x720 --jpeg 95 /var/www/door.jpg --scale 320x180 --jpeg 95 /var/www/door-sm.jpg
else
    fswebcam -D 1 -f 2 --set brightness=100% -r 1280x720 --jpeg 95 /var/www/door.jpg --scale 320x180 --jpeg 95 /var/www/door-sm.jpg
fi

chmod +x /home/pi/webcam.sh


I wanted to capture four frames per minute from the camera (the relevant modules were already installed in Raspbian).

The other issue was the with the WiFi dongle setup, the pi was unstable; so I'd throw in a reboot every hour; it takes just seconds.  The easiest way to do all this was through cron jobs, as follows:

crontab -e

# m h   dom mon dow          command
0 * * * *                             /sbin/reboot
* * * * *                             /home/pi/webcam.sh
* * * * *                             sleep 15; /home/pi/webcam.sh
* * * * *                             sleep 30; /home/pi/webcam.sh
* * * * *                             sleep 45; /home/pi/webcam.sh


And that, literally, is all I needed to do.

The rig handles day- and nighttime illumination levels very well; attached is a jpeg.  I access it locally through the network at http://pi/door.jpg.  Works like a charm!



No comments:

Post a Comment