Showing posts with label birds. Show all posts
Showing posts with label birds. Show all posts

Tuesday, January 8, 2019

Automatic Chicken Watering Cup System

Over the past year, my wife and I tried our hand at raising backyard chickens for eggs.  We had a lot of fun, and learned a lot along the way, until our little chicken experiment came to an abrupt end shortly before the new year.  A predator (our research leads us to believe it was a raccoon or weasel) found a way inside the coop one night and killed the entire brood.  Since we don't plan to immediately acquire new chickens, I have decided to shut-down the website I started to chronicle our chicken adventures, and migrate some of the articles to this blog.  Below is such an article.  If you are interested in reading more about our experience raising backyard chickens, let me know in the comments below.  Thanks for reading.

The Watering System


Chickens are ironic creatures.  They require constant access to fresh, clean water, but given the first opportunity they will kick dirt and grass into it, walk in it, and even defecate in it if they happen to be standing in it when the urge strikes.  When we first started raising chickens, we used old pie tins as water dishes. These quickly proved inadequate as the chickens not only filled them with dirt constantly, but also walked in and on them so that they bent the sides down, spilling the water.  In a search for a more elegant solution, I came across Automatic Chicken Watering Cups on Amazon, and decided to give them a try. I’m glad I did, as they turned out to be an excellent way to keep clean water available for our chickens for days at a time.

Before I took the plunge and ordered my Chicken Watering Cups, I scrolled down to the customer reviews to make sure I wasn’t wasting my time and money.  It appeared that most of the negative reviews were from people that used these cups by mounting them directly into a bucket, or drilling the PVC themselves, and the result was a leaky watering system.  Another quick search on Amazon revealed a simple solution: Horizontal PVC T-Fittings with ⅛ inch female threads that were specifically designed to fit items with ⅛” threads like the Chicken Watering Cups.  Coincidentally, Chicken Water Nipples also have ⅛ inch male threads, so if you wanted to give those a try, you could use the same PVC T-Fittings.

Material List:


*Disclaimer: I purchased some of the items above at my local hardware store.  For your convenience I have included Amazon links to all items on the material list in case you would like to purchase everything at once and save a trip to the store. I have placed an asterisk next to the items that I did not purchase off of Amazon to make you aware, since I cannot vouch for their quality.  That being said, Amazon has an excellent return policy if anything you receive is not up to par.

My basic plan was to use a 5-gallon bucket as a reservoir, and to feed the water from the bucket to the watering cups with ½” SCH-40 PVC.  PVC is great for this project because is it durable, sun-proof, easy to work with, rigid enough to not need too much support, and most importantly, very inexpensive.

Below is a sketch of my layout, which also worked as my cut-list.  As I said before, your chicken environment will likely differ from mine, so your specific design and cut-list will also differ.  Just be sure to measure everything precisely. As the old saying goes: measure twice, cut once. If you have any questions about adapting my design to your environment, please ask in the comment section below and I will do my best to answer.


To begin, let’s drill the bucket.  The diameter of the male threaded end of the coupler (8) that goes through the hole in the bucket is slightly larger than 7/8″.  I used a 7/8″ spade bit to drill the bucket, and then widened the hole slightly with a knife, which shaved the soft plastic easily.

If you work with PVC all the time then you probably have a PVC pipe cutter, but if you don’t, there is no need to buy one unless you don’t own pretty much any other type of saw.  I used an upright bandsaw with a miter gauge to cut my PVC, but if you don’t have a bandsaw you can use a hacksaw, miter saw, or any saw that is made for wood or metal because PVC is relatively soft. To eliminate any possible confusion, after I cut each piece I used an ultra fine point Sharpie to write the length on each piece.

Once all the pieces are cut you will need to chamfer the edges by taking a blade and running it across the inside and outside edge of each length of PVC, removing any burrs left from cutting, and leaving a small 45 degree angle around both edges.  When all the pieces are ready it is a good practice to dry assemble the entire project to make sure everything fits as you planned it. Be sure to assemble the T-fittings so that the threaded receptacle will be parallel to the ground, or else your watering cup will end up tilted and the water will spill out.

At this point, while it is still dry assembled,  I like to use a sharpie to draw lines at each junction, originating on the joint, and continuing onto the length of the pipe for about an inch.  This ensures that once you apply the PVC primer and cement, you can align the pieces in the exact same orientation you did when they were dry-assembled.  It is easy to make a mistake while you are assembling the PVC, and once it is fused, there is no way to take it apart again. Be sure to draw the line at least one full inch up the PVC because once you add the primer and cement, the PVC will actually seat further up into the joint than when dry, and you want to make sure you can still see some of the line.

To bond the PVC together, first make sure you are in a well ventilated area.  While the primer and cement are both non toxic once cured, they are very toxic if inhaled.  You may also want to put down a drop cloth because the purple primer can stain. Apply two coats of the primer to both the inside of the joint, and the outside of the length of PVC with the provided applicator.  You can be fairly liberal with the primer, just be sure you don’t erase the entire length of line you drew to align the pieces because the primer will instantly erase the sharpie.

Next you will want to apply a liberal coat of the cement to the outside of the length of PVC and a thin coat to the inside of the joint.  To achieve this, I like to dip the applicator into the cement, and wipe off any excess on the rim of the can. First apply the cement to the outside of the length of PVC, then apply to the inside of the joint with what is left on the applicator, without dipping back into the can of cement.

As soon as the cement is applied, push the two pieces together, paying close attention to your sharpie marks to line up the pieces correctly.  While you hold them together for 30 seconds, the cement will actually melt the PVC, fusing the two pieces together. This creates a permanent bond that cannot be unwelded, which is why it is so important to make sure your pieces are lined up the first time.

Once you have repeated the process for the entire length of PVC you will want to let it cure for 24 hours.  At this point the cement and primer is 100% non-toxic, and cannot hurt you or your chickens, although I still like to flush the pipe out with water, just for piece of mind.

The section of PVC that attaches to the bucket does so mechanically by attaching the threaded male and female connectors specified in the drawing at the beginning of this section, but the seal will not be water tight.  Sealing the joint between the PVC and the bucket can be accomplished with a rubber washer or O-ring, but I simply used a silicone caulk to make the seal.

When installing the bucket and PVC in its final location, it will be necessary to raise the bucket up off the ground so that gravity will force the water through the entire length of pipe with enough force that the cups will fill up quickly when the yellow dongle is pushed or pulled.  Six 8”x8”x16” cinder blocks stacked two by two did the trick for me, setting the bottom of the bucket approximately 24” off the ground.

At this point the cap can be put on the other end of the PVC structure, and the cups can be screwed into the T-fittings.  Be sure not to over-tighten the cups on the T-fitting or they will leak. If you have leaks at the junction of the cup and the PVC when you test it out, try loosening the cup one turn to see if it solves the problem.

The part of the PVC with the cups should be fastened securely to some surface, such as the wall of the coop or the run, so that cups will sit about 6 inches off the ground.  The chickens will walk and perch on the PVC, so you want it to hold tight enough not to stress the joints. I found that two-hole conduit straps for ¾” EMT fit the ½” PVC perfectly, and hold it rigidly enough as to not allow it to bend under the weight of the chickens.  Plastic tie wraps (aka cable-ties or zip-ties) work well for additional support, but should not be used as the main supports because the sun will eventually cause them to turn brittle and break.

And that’s about it.  Connect the PVC sticking out of the bucket to the PVC attached to the run with the PVC Union, fill the 5 gallon bucket with water, and open the PVC valve.  You can then test the watering cups by pulling upwards slightly on one of the yellow dongles to see if the cup fills with water. If it does you’re in business.  Fill up all the cups so that the chickens can see the water, and let them at it. If they don’t start drinking out of it right away, try removing any other sources of water to force them to figure out how to use it.

We’ve had great success with the Automatic Chicken Watering Cups.  The smarter chickens in the bunch caught on immediately, and the rest of them figured it out not long after.  The one downfall of this system is that it won’t be able to be used after temperatures drop below freezing, but in this part of Virginia that will mean that it can be used for about 8 months out of the year, which is enough to make it worth it to me.

If you try this solution, let us know how it worked out for you in the comments.  Also, if you run into any problems building it, or getting it to work properly, feel free to leave your questions in the comments and I’ll do my best to help you out.


The Great Chicken Swap



Over the past year, my wife and I tried our hand at raising backyard chickens for eggs.  We had a lot of fun, and learned a lot along the way, until our little chicken experiment came to an abrupt end shortly before the new year.  A predator (our research leads us to believe it was a raccoon or weasel) found a way inside the coop one night and killed the entire brood.  Since we don't plan to immediately acquire new chickens, I have decided to shut-down the website I started to chronicle our chicken adventures, and migrate some of the articles to this blog.  Below is such an article.  If you are interested in reading more about our experience raising backyard chickens, let me know in the comments below.  Thanks for reading.

So It Begins


My wife Courtney and I had been talking about raising backyard chickens for a while, so when our friends Jeff and Katie told us they were putting their house on the market, and needed to find a new home for their brood, we knew it was time to take the plunge.  Over the next several weeks we cleared out a space at the top of our yard and began building an environment for the chickens. Having zero experience with chickens, and being unsure exactly what we would need, I only built what I thought would be the bare essentials, a cinder block pad to protect their coop from burrowing predators, a chicken tractor/run to give them some space outside the coop, and a compost bin to dispose of their droppings.  Since Jeff and Katie were going to give us the coop that the chickens were currently living in along with the chickens, we decided we had everything we needed to get started, so we set a date and began to plan for The Great Chicken Swap.

We quickly realized that none of us had any experience with transporting 7 full-grown chickens, and this might be more difficult than it had seemed at first.  After scrapping our first few schemes, Jeff came up with the idea of loading the coop onto a trailer and transporting the chickens inside their own coop. Despite the potential for many things to go wrong with this plan, it was the best idea we had come up with so far, so we decided to give it a go.

The weekend of the move finally arrived, and I was filled with conflicting feelings of excitement about our new found feathered friends, and apprehension about what could go wrong with our somewhat questionable plan to transplant them.  Jeff called me mid-day and said that the chickens were out in the yard, and I could come by to help load the coop on the trailer whenever I was ready. Moving it was easier than we expected. At that point there was nothing to do but wait, and hope that the chickens returned to their relocated coop at sun-down.  Sure enough, like clockwork, as the sun set the hens retired to their perches inside the coop as it sat on the trailer. With a few ratchet straps securing the coop to the trailer, Jeff skillfully navigated the chickens from their house to ours. Surprisingly, the chickens tolerated the whole process very well, and didn’t seem flustered in the least when they arrived in our yard.  To keep their disruption to a minimum, Jeff simply unhitched the trailer, and left it in our yard overnight.

On Sunday morning I woke up with the sun, excited to welcome our flock to their new home.  They seemed equally excited to be let out of their coop, so I set up some temporary fencing to guide them from the coop to the chicken run I had built for them.  With that accomplished, Courtney and I proceeded to unload the coop from the trailer onto the cinder block pad. Once again, everything went much more smoothly than anticipated.  We proceeded to build a tunnel out of stiff fencing material between the coop and the run so the chickens could traverse between the two. Then it was time to make some coffee and take the opportunity to rest and watch the chickens adapt to their new surroundings.  They even had the courtesy to lay five eggs for us that first morning to provide a late, but much appreciated breakfast.

Over the next week we continued to improve their environment by fencing in an area next to the garden with chicken wire so they could have a place to run around and eat grass and bugs during the day when we are home to keep an eye out for predators.  I built a second tunnel between the grassy area and the run to make moving them in and out easy. I also built a watering system for them that I will outline in another post in case anyone would like to build something similar. They have been laying 5 to 6 eggs per day, which is not bad for seven chickens, some of them already three years old.

We have lots of plans for the future.  I would like to expand their environment as time and money permit.  I also have a few more necessities to build, like a dust bath so they will stop making their own in places I would rather them not dig out.  I have also purchased a solar panel and battery so we can bring these chickens into the 21st century with some modern electrical amenities. I plan to use a Raspberry Pi (small single board computer you can read about here) to automate a few things like filling up their water system, dispensing their nonperishable feed, and automatically opening and closing the coop door at dawn and dusk.  And since I will already have power and a computer, no coop would be complete without a live streaming chicken-cam. Eventually I would also like to expand our flock by bringing in a few more birds, but one thing at a time.  For now it’s enough to let the hens get used to their new home, as we get used to life raising backyard chickens.

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.



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 Raspberrypi.org'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  
   
 MOTION_PIN = 4  
 camera = picamera.PiCamera()  
   
 GPIO.setmode(GPIO.BCM)  
 GPIO.setup(MOTION_PIN, GPIO.IN)  
   
 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)  
      camera.wait_recording(10)  
      while GPIO.input(MOTION_PIN):  
           camera.wait_recording(10)  
      camera.stop_recording()  
      print 'recording stopped' # for troubleshooting only  
   
 # Begining of Program  
   
 time.sleep(2)  
 while True:  
      print 'waiting for motion' # for troubleshooting only  
      GPIO.wait_for_edge(MOTION_PIN, GPIO.RISING)  
      print 'motion detected' # for troubleshooting only  
      take_video()  

As always, we need to make the file executable using sudo chmod +x /home/pi/motion-vid.py.  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/motion-vid.py &

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.