Wednesday, July 26, 2017

Filming Birds with a Raspberry Pi (Part One)

I had recently purchased a camera module for the Raspberry Pi, mainly just out of curiosity, and a desire to learn how to use it.  In the back of my mind I had been working on an idea to build a birdhouse and use a Pi to film the birds, but I was currently working on several other projects, so I was in no hurry to start a new one.  One evening I was working at my desk in my shop, and I heard some chirping outside the window.  I pulled back the curtain to find a Carolina Wren's nest with baby chicks inside chirping away.  How fortuitous.  Suddenly my project to film birds with the Pi moved to the front of the list.  With little knowledge of how to use the camera, I bent a piece of 12awg copper wire into a makeshift camera stand, hooked it up to the Pi, and set it in the window.  A quick Google search told me that I could enable the camera module using the raspi-config menu, and then operate the camera from the command line using the following commands for pictures and video respectively:

raspistill -o birdpic.jpg

The above command takes an 8 megapixel image and outputs it to a file named birdpic.jpg.

raspivid -o birdvid.h264 -t 10000

The above command takes a video and outputs it to a file named birdvid.h264.  The -t specifies the length of the video in miliseconds, so -t 10000 takes a 10 second video.

It worked.  I sat there for a little while amusing myself taking video of the birds every time they started chirping, because that usually meant that it was feeding time.  The video through the window was decent, and I managed to edit together a short video.

Obviously, this was far from an optimal set-up.  The video through the window was OK, but it could definitely be better, and the whole thing was dependent on me sitting there listening for the chirping and hitting a button.  It was time to take this to the next level.  I had some IR motion sensors lying around, and some leftover 1/2" plywood from a previous project, so I whipped up a quick little box with a hinged lid and a removable front panel with holes for the camera and motion detector.  I decided to store the video on a 16 GB usb thumb drive.  The other options would have been to save it
to the SD card, which would only wear out the card faster, or stream it via wifi to my server.  I decided against wifi in case I wanted to use this project for filming something else that was too far away from the house for wifi.  The USB drive turned out to be an adequate solution.  I made sure to leave plenty of room in the box, and air gaps at the top to deal with the heat produced by the Pi and the USB stick.  To mount the motion detector and camera on the front of the box I simply used electrical tape, since this was more of a prototype or proof-of-concept than anything else.  I was pleased with my little box, considering I made it on the fly in just a little
 over an hour.  The IR motion sensor I used was a HC-SR501, which runs off of 5V, but conveniently send a 3.3V signal when motion is detected, so I could hook it up directly to the Pi using only three pins without having to use a level-shifter.  With that, the hardware was complete.  Now all I needed was a little code to automate the whole process.  Back to Google.

It turns out, as to be expected, the Raspberry Pi Camera Python module is located in the Raspbian repositories, so it can be installed with a quick:

sudo apt-get install python-picamera

I don't want to get too in-depth on how to use this module, so I will just point you to's documentation here.  The code is simple.  All I am going to do is to  monitor the GPIO pin that the motion sensor is connected to.  When motion is detected I am going to start recording.  After 10 seconds, I am going to check the motion sensor again.  If there is no motion, then the clip is over.  If there is still motion after 10 seconds then it will wait another 10 seconds and check again.  This results in a minimum size clip of 10 seconds, with no maximum size as long as motion continues.  To prevent video files from overwriting each other, each clip will contain a time-stamp in the file name.  I could have gone a little more advanced with the code, but I was in a hurry to get this up and running, so I kept it simple.  Here's the code if anyone would like to use it:

 #!/usr/bin/env python  
 import RPi.GPIO as GPIO  
 import picamera  
 import time  
 camera = picamera.PiCamera()  
 def take_video():  
      timestamp = time.strftime("%y-%m-%d-%H-%M-%S")  
      print 'recording started' # for troubleshooting only  
      camera.start_recording('vid%s.h264' % timestamp)  
      while GPIO.input(MOTION_PIN):  
      print 'recording stopped' # for troubleshooting only  
 # Begining of Program  
 while True:  
      print 'waiting for motion' # for troubleshooting only  
      GPIO.wait_for_edge(MOTION_PIN, GPIO.RISING)  
      print 'motion detected' # for troubleshooting only  

As always, we need to make the file executable using sudo chmod +x /home/pi/  I want to have this script run on start-up, so we need to add this file to the /etc/rc.local file, but before we do that, we need to think about the USB flash drive that we are using to store the video.  When a USB drive is inserted into the Raspberry Pi, it is not automatically mounted as it is in many other operating systems, so we need to make sure that the Pi also mounts the USB drive on start-up.  To do this, we must first determine the name of the drive, and of the partition on the drive.  Typically the first USB drive you insert in the Pi will be sda, but in the interest of being thorough we will double check just to be sure using the command ls /dev/sd*.

As you can see above, it returned two values.  sda is the name of the drive itself, and sda1 is the name of the partition on the drive.  We want to mount the partition.  Next we need to look to see if we have a place to mount the drive.  Navigate to /mnt using cd /mnt, and see if you have directories there.  If not, create a directory named usb (the name is arbitrary) using the command sudo mkdir ./usb.  We can now mount the usb drive using sudo mount /dev/sda1 /mnt/usb.

So now that we know how to do it, let's tell the Pi to mount the USB on boot and run the camera script.  Open up the /etc/rc.local file using your text editor du jour (i.e. sudo vim /etc/rc.local)and add the following lines to the file:

# The following line mounts sda1 to /mnt/usb
sudo mount /dev/sda1 /mnt/usb

#The following lines runs the script that takes video based on a motion sensor
cd /mnt/usb
sudo /home/pi/ &

And that's it.  I put the box on the windowsill next to the birds nest and plugged it in.  The first day I got just under 400 video clips, which took up about 3.5 GB.  That means with a 16 GB USB drive I would only need to swap out the drive every four days or so.  At any time I could log into the Pi over wifi to make sure it was still working, and view any of the clips I chose.  And of course, I had to make another bird montage:

And now for the sad conclusion of this project.  After a little less than a week of watching the birds, and admittedly becoming a bit attached to the little guys, I was working in my shop when I heard a commotion at the window.  I figured the birds were getting active, so I logged into the Pi and pulled down the last video clip.  Horrified I watched as one of the neighbor's cats pounced onto the nest and pulled it, and the baby birds, off of the window ledge.  C'est la vie.  It is nature after all, and cats will be cats.  I can't be happy they keep away the mice and snakes, and then fault them for eating the birds.  It wasn't the smartest place for the Wrens to build a nest anyway, 2 feet off the ground.  At least I got to watch them for a while, and it gave me a good starting point for this project.

So what did I learn, and what's next.  Most importantly, next time I film baby birds they will be in a bird house where they will be better protected from predators.  My code could also use a little bit of improvement, and next time I will probably just stream the video to a server instead of using the USB drive for storage.  I am already working on a design for a bluebird house that will have an internal camera and an external camera, and will be able to conceal the electronics in a separate compartment from the birds.  The biggest hurdle to overcome with that project will be powering two Pi Zeros and two cameras, but I'm sure I can come up with something.  Until then, stay safe, and keep building.

1 comment:

  1. pretty cool project man I might actually give it a shot but instead of filming birds I'll use it as a security system