Wednesday, August 22, 2018

Voyeur Bluebird House with a Raspberry Pi

     Previous readers of my blog may remember my initial foray into filming birds using the Raspberry Pi.  That first experience was inspired by coincidence, as a family of wrens made their nest on the windowsill of my basement workshop, and proceeded to raise five young babies.  I built a small wooden enclosure to house a Pi, motion detector, and camera, and set it on the windowsill adjacent to the nest.  Each time the mother flew in to feed the babies, or the babies started to move outside the nest, the camera would turn on, and continue to film until movement had ceased.  I enjoyed the process of filming these birds so much, that I decided to try to recreate the project.  This time, however, I doubted I could rely on fate to deliver another family of birds to my windowsill.

     I decided the best way to ensure birds would nest in a place suitable for filming would be to build a birdhouse, and install a camera inside.  I decided on Bluebirds as the species of bird I wanted to film, and a quick Google search told me the dimensions of the birdhouse and opening I would need to attract that specific variety of bird.

     If you are not interested in how this project was done, and would just like to see a video of the chickadee that originally settled in the birdhouse, as well as the final video of the baby bluebirds, just scroll down to the section entitled "Filming the Birds", and watch the two YouTube videos.  I would hate to see people get bored by the technical specifics of the project and stop reading before they get to the videos of the birds.  If you are interested in how I built this project, or would like to build one yourself, please continue reading.

Building the Birdhouse


     I chose cedar as the species of wood to build the birdhouse due to its resistance to insects and rot.  I purchased cedar that was rough-sawn on one side to give the birds a surface that they could easily sink their claws into.  I also chose not to build a perch outside the entrance hole.  Instead, I flipped a piece of the cedar so that the rough-sawn surface was facing outward, allowing the bluebirds to grip the surface with their claws, but making it less suitable for predators, or other species of bird that would likely kill the bluebirds and steal their house, such as sparrows.  Also, since I was concerned about potential heat generated inside the birdhouse by the Raspberry Pi, I decided to add a small sheltered area to the back of the birdhouse that could protect the Pi from the elements, but also keep me from having to place it inside the actual birdhouse.  Since there are literally thousands of birdhouse plans available on the internet, and anyone emulating this project will need to pick a species native to their geographical location, I won't go into great detail on the construction of the birdhouse here.  If anyone has questions on the specifics of how the birdhouse was built, please feel free to ask in the comments at the end of this post.


      One thing to keep in mind as you are assembling your birdhouse is that you don't want to make the top of the birdhouse airtight.  Instead, make sure to leave some air-gaps, and even drill a few holes in the side near the top as well as in the bottom to allow cool air to flow in through the bottom of the birdhouse and hot air to escape out the top so it doesn't get too hot in your birdhouse during the summer months.  Also, keeping in mind the way my first project filming birds ended (see the end of this post), I made sure to do everything in my power to protect the birdhouse from predators.  I covered the mounting post with PVC pipe to make it more difficult to climb, and I added a squirrel baffle between the PVC and the birdhouse to keep anything that was able to climb the PVC from reaching the house (this is not the exact baffle I purchased, but it is similar.)  If a squirrel or other large rodent was able to reach the birdhouse, the double wall around the opening would make it more difficult for anything to widen the opening by clawing at it.

Installing the Hardware


     With the birdhouse constructed, it was time to figure out how to film the birds.  Since it was going to be dark inside the birdhouse, I decided to use a infrared night vision camera.  I also needed to find one with an adjustable focus, since the birds would be very close to the camera.  Here is the link to the particular camera I purchased for this project.  In addition, I was going to need an infrared motion detector that could be powered by 5V DC, but would be capable of sending a 3.3V signal to the Raspberry Pi, which I found here.  Finally I decided to add an LM75A Temperature Sensor inside the birdhouse so I could ensure that all the electronics did not cause the temperature inside to get too hot.

     With hardware in hand, I needed to find a way to mount the camera, motion detector, infrared LED, and temperature sensor inside the birdhouse.  For the camera and infrared LED, I settled on using a small piece of clear acrylic that I cut and drilled to fit.  I then epoxied some 12 awg insulated solid copper wire to the bottom of the acrylic so that I could mount the wire to the back of the birdhouse, and then bend it to point the camera in the exact direction I needed it to point.  Once the acrylic was in place and focused towards the center of the birdhouse, I wedged the motion detector between the acrylic and the side of the birdhouse.  A couple of drops from the hot glue gun made sure everything stayed in place.  I allowed the temperature sensor to hang slightly below the rest of the electronics to allow it to measure the temperature closer to where the birds would be nesting.



     The Raspberry Pi model I chose for this project was the Raspberry Pi Zero W, because of it's much lower price point, and it's smaller size.  I purchased it in a kit that came with a plastic case, so that I could mount the case inside the enclosure on the back of the birdhouse, and easily remove the Pi from the case for maintenance.  I then ran the camera ribbon cable from the Pi on the back of the birdhouse to the camera inside the birdhouse.  A few more wires to get power and signal to the motion detector, power and signal to the temperature sensor, plus power wires for the infrared LED, and the Pi was ready to go.  Feel free to use any of the GPIO pins on the Pi you would like to use, just be sure that the pins referenced in the Python script match the pins used on the Pi.



     I used a 16GB USB flash drive as a hard-drive to store the video files.  Other options would have been to use the SD card that held the operating system, but that would have limited space, and could shorten the life of the SD card.  Alternatively I could have just automatically sent the video files to my file server, but that would involve another point of failure, so even if the Pi was up and running, if something knocked the server offline or the power flickered and the server powered down, then any files being sent from the Pi would be lost.  The flash drive seemed to be the simplest solution, and as long as I transferred the video files remotely and wiped the USB drive at some point before I collected 16GB of video, I should be OK.

     One last detail, in order to be able to plug in the power supply for the Raspberry Pi without having to worry about the length of the power cord, I mounted a 120V AC outlet inside an outdoor enclosure on the back of the birdhouse.  I then attached a piece of outdoor-rated flexible power cable with a three pronged plug to the outlet.  I could now power the outlet using this power cable, and just plug the Raspberry Pi power supply into the outlet on the birdhouse directly below it.

Writing the Software


     With the hardware complete, all I had to do was to write the software, which is pretty much the exact same Python script I used in my last post where I filmed the birds in the windowsill with an added bit of code for the temperature sensor.  Regardless, in case you would like to copy the script for use in your own project, I will post it below.  Don't forget to add a line to /etc/rc.local to tell the Pi to run the script on boot.  Here it is:

 #!/usr/bin/env python  
   
 import RPi.GPIO as GPIO  
 import picamera  
 import time  
 import smbus # lets us access the i2c bus  
   
 MOTION_PIN = 4  
 BUS_NUM = 1 # 1 is the I2C bus (board pins 3 and 5)  
 TEMP_SENSOR1 = 0x48  
 EMAIL_THRESHOLD = 98  
 GMAIL_USER = 'email1@gmail.com' # email account used to send email  
 GMAIL_PASS = 'emailpass' # password for email account used to send email  
 SENT_FROM = GMAIL_USER  
 SEND_TO = 'email2@gmail.com, email3@gmail.com' # email recipient for alerts  
   
   
 def take_video(channel):  
      print 'motion detected' # for troubleshooting only  
      timestamp = time.strftime("%m-%d-%y-%H-%M-%S")  
      #camera.annotate_background = picamera.Color('black')  
      #camera.annotate_text = timestamp  
      camera.start_recording('bvid%s.h264' % timestamp)  
      print 'recording started'  
      camera.wait_recording(10)  
      while GPIO.input(MOTION_PIN):  
           camera.wait_recording(5)  
      camera.stop_recording()  
      print 'recording stoped'  
   
 def WRITE_TO_FILE(temp):  
     print 'writing to file' # for troubleshooting only  
     timestamp = time.strftime("%y-%m-%d %H:%M:%S")  
   
     f=open('/mnt/usb/temperature.txt', 'a') # this opens a file for writing.  
                          # the 'a' means append, which will   
                          # add anything written to the end  
                          # of the file.  
   
           # The line below writes to the file we are appending  
     f.write('%s %d \n' % (timestamp, temp))  
     f.close() # This closes the file we just appended.  
   
   
 def CtoF( Ctemp ): # this function converts the Celcius temperature passed  
                       # to the funtion to Fahrenheit and returns it.  
     return((Ctemp*9.0/5.0)+32)  
   
             
 def GET_TEMPS( sensor_add ):  
   print 'getting temp'  
   Ctemp1 = bus.read_byte(sensor_add)  
   Ftemp1 = CtoF(Ctemp1)  
   return Ftemp1  
        
        
 def SEND_EMAIL ( temperature ): # This function sends an email  
   
     timestamp = time.strftime("%m-%d-%y %H:%M:%S")  
     subject = 'Birdhouse Temperature Too High' % (location) + timestamp  
     body = 'The temperature in the birdhouse is %d degrees.' % (temperature)  
   
     msg = MIMEText(body)  
     msg['From'] = SENT_FROM  
     msg['To'] = SEND_TO  
     msg['Subject'] = subject  
   
     try:  
       server = smtplib.SMTP_SSL('smtp.gmail.com', 465)  
       server.ehlo()  
       server.login(GMAIL_USER, GMAIL_PASS)  
        server.sendmail(SENT_FROM, SEND_TO, msg.as_string())  
        server.close()  
        print 'email sent' # for troubleshooting only  
     except:  
       print 'email atempted and failed' # for troubleshooting only  
             
 # Begining of Program  
   
   
 bus = smbus.SMBus(BUS_NUM) # sets the variable bus to refer to I2C bus 1  
   
 camera = picamera.PiCamera()  
 camera.led = False  
   
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(MOTION_PIN, GPIO.IN)  
   
 GPIO.add_event_detect(MOTION_PIN, GPIO.RISING, callback=take_video, bouncetime=1000)  
   
 while True:  
      Ftemp_1 = GET_TEMPS ( TEMP_SENSOR1 )  
      if Ftemp_1 > EMAIL_THRESHOLD:  
           SEND_EMAIL (Ftemp_1)  
      WRITE_TO_FILE(Ftemp_1)  
      time.sleep(300)  
             

Filming the Birds


     So that's the how-to, and now onto the fun part: filming the birds.  I set the birdhouse up outside my house in August of 2017 and plugged it into one of our outdoor outlets.  Honestly, after a few months I had forgotten all about it.  One day in late spring of 2018, my wife Courtney saw a bird fly out of the birdhouse and asked me to check the camera.  Much to my surprise, the Raspberry Pi was still up and running from 8 or 9 months prior, and had captured plenty of video.  All that time outside in the winter weather hadn't cause any issues with the Pi at all (that's some well made hardware!).  Upon examination of the video, it appeared we had a chickadee moving into our bluebird house.  Well, I'm not one to discriminate, I was just happy to have a bird enjoying the birdhouse, and I was even happier that the video recorder was working.


     We continued to check the camera from time to time, watching the chickadee as it gathered it's nest building materials and meticulously arranged them just so.  Then one day, all of a sudden, there was a bluebird in the birdhouse.  I reviewed the videos, and narrowed it down to the change, but there was no "event".  One video showed the chickadee working on it's nest, and the next video showed a bluebird checking out his new pad.  If there was an altercation it must have happened outside the birdhouse.  Alternatively the bluebird may have just moved in, and when the chickadee returned to find a bigger bird in his house, he just decided to move on.  Regardless, I was now filming bluebirds, which was my original intention.

     Fast-forward about a month, and the blue bird had completely revamped the nest, and laid some eggs.  I was very excited to see them hatch.  Unfortunately, I underestimated how often I would need to clean off the USB flash drive that was holding the video once the bird had laid eggs.  When the birds were building the nests, they would make an appearance here and there, and then go back out to forage for food, and find more nesting materials, which only created a limited number of videos.  Once the eggs were laid, the bluebird spent most of her time sitting on the eggs inside the birdhouse, and consequently the flash drive filled up with video in just a few days.  Once it was full, it stopped saving the recordings, so unfortunately I missed the moment of hatching while we were out of town for a weekend.  Once I returned home and realized what had happened I quickly downloaded the existing video and erased the drive, so I was at least able to film the majority of the young birds' infancy.

      Below is a montage of the baby bluebirds I put together .  The total span of the videos is only a couple weeks, so you can see that they grew quickly.  I lost my infrared LED a few days after the babies hatched, so the lighting is a little off in the second half of the video, but of course I couldn't get into the birdhouse to change the LED until after the birds had vacated the nest.  It still turned out great in my opinion.  My wife Courtney thinks these little guys are cute, but personally I think they're ugly little spuds before their feathers fully grow in.



No comments:

Post a Comment