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, August 15, 2018

My Morning Routine

Good morning, and welcome back to my blog.  Anyone who has read my blog before knows, that while the topics can be eclectic, my posts typically deal with how to build something, be it using wood, electronics, computers, or a combination of mediums.  Since this is my first post after a year-long hiatus, I thought I would try something a little different and write a short post about my morning routine.  Over the past year, I have made several major life-changes, including quitting smoking, reducing my alcohol intake to next-to-nothing, drastically altering my diet, and starting a weightlifting routine.  The result of these changes are a healthier, happier me, and I would recommend any of them to anyone looking to get more enjoyment out of life.  Today I want to focus on a small, but important aspect of these life-modifications that has helped improve my life, and enjoy my days more thoroughly: my morning routine.

The way one starts and completes each day frames all of the experiences within.  By beginning the day on a positive, productive, and pleasurable note, I am able to set the tone of the day, and I have noticed a considerable difference in how I feel, and what I am able to accomplish.  The first item on the list was actually the most difficult for me, and I can't claim to be successful in this endeavor every single morning, but the first thing I strive to accomplish is to NOT HIT THE SNOOZE BUTTON!  I have struggled with waking up in the morning all my life, and had formed a habit of hitting the snooze button for anywhere from 20 minutes to an hour (or more) after the first time my alarm sounded.  The experts say that one actually feels more tired after hitting the snooze button than they would have if they had just woken up after the first alarm.  I don't know if that is true or not, but I doubt I get any added benefit from the additional sleep I get in 5 or 10 minute increment using the snooze.  One of the advantages I can attest to is more time in the morning, resulting in less stress and more productivity.  Also, if I successfully drag myself out of bed without hitting the snooze, I feel a sense of pride and accomplishment first thing in the morning, which is a nice way to start the day.

Once I am out of bed and have made a quick pit stop in the bathroom, I head to the kitchen, and turn on all the lights to make it as bright as possible.  This helps let my body know that even if it is still dark outside, my day has started (circadian rhythms and whatnot).  I notice that I feel significantly more awake after just a minute in a very bright room.  If you find yourself continuing to feel drowsy after getting out of bed in the morning, try adding some extra light in the room you spend your first 10 minutes in, and I would be willing to bet you will feel a noticeable difference.  If the sun is up when you get out of bed, then I would recommend stepping outside for a few minutes, as the the sunlight is tremendously more effective at waking one up than synthetic light.  Unfortunately I don't have the luxury of waiting for daybreak to start my morning, so man-made light has to suffice.

As the light begins to signal my brain that I am now awake, I turn my attention to hydration.  Assuming you do not wake up in the middle of the night to drink water, you will have gone without water since you fell asleep, and possibly longer.  As you will be able to surmise by the color of your morning urine, most people wake up dehydrated and craving fluids, whether you realize it or not.  I cannot claim credit for my morning cocktail recipe; it came from an excellent book by Aubrey Marcus titled Own the Day, Own Your Life: Optimized Practices for Waking, Working, Learning, Eating, Training, Playing, Sleeping, and Sex, which I highly recommend.  Aubrey's recipe is simple: water, sea-salt, and lemon.  I personally use the juice from 1/4 lemon and a pinch of Pink Himalayan Salt in about 16 oz of water.  Don't let the demonization of salt scare you away from trying this.  Unless you already have a serious heart condition, the salt is not bad for you, and will help your body absorb the water.  There is no need to chug it either.  Take your time, sip your water, feel yourself hydrating, and think about the great day you are about to have.

About this time the sun is beginning to peek over the horizon.  As sunrise begins to happen later in the morning, I may need to reorder my routine, but for now, it is time to feed the chickens and clean the coop.  Yep, you heard correctly, we have chickens.  As a matter of fact, my wife Courtney and I are planning on starting a chicken blog in the near future, and when we do, I will place a link to it here for anyone interested in taking a look at our fine feathered friends.  Anyway, the point here is not to specifically care for birds, but to accomplish some task, or set of tasks.  Some people recommend making your bed.  As long as you set your mind to doing something productive and accomplish it, you have set your brain on the right track for the day.

The next goal for myself is to get my heart rate up and get a little exercise.  Recently, this has been accomplished by taking a one mile walk with Courtney, but any physical exertion will do.  Sometimes we do a short steel maceworkout (trust me on this one and give it a try).  This is also a good time to get in a little stretching to keep the body limber and free from injury.  I don't do any serious weight lifting or cardio this early in the day, just enough to get the blood flowing.

Now that my body is nice and warm, it's time for my favorite part of the morning: a cold shower.  Seriously.  Not only has this been proven to have positive health benefits, it will also guarantee that you are fully awake.  In addition, it is one last test of willpower that will tell your mind and body that if you can endure this, you can accomplish anything today.  And in all honesty, it really isn't that bad.  I start my shower with warm water.  Since I bathe at night before I go to bed, all I do is rinse off in the warm water before I turn the knob to cold.  The key here is not to think about it.  Don't prepare yourself physically or mentally, just do it.  No need to torture yourself for too long, just a few minutes is all that's necessary.  Before I know it, it is time to get out, dry off, and head back to the kitchen for some well earned breakfast.

With all my other morning activities checked off my To-Do List, it's breakfast time.  Personally I like to have scrambled eggs loaded down with vegetables (onions, bell pepper, mushrooms, spinach, and whatever other left-over veggies or garden veggies we have that might go well in eggs.)  If eggs aren't your thing, eat whatever you like, but I highly recommend staying away from processed carbs, and certainly no refined sugar.  Anything with a high glycemic index will spike your blood sugar, and subsequently your insulin, and cause you to be hungry again in just an hour or two.  Starting your day off with an insulin-induced blood-sugar roller-coaster is a recipe for dietary disaster, not to mention the damage it can do to your pancreas, kidneys, and heart, among other things.

Last but not least, with breakfast out of the way, it is time for my morning coffee.  You may have noticed that I didn't mention coffee earlier in this article when I first got out of bed.  For over 20 years brewing coffee was the first thing I did in the morning upon getting out of bed.  If you just can't live without caffeine first thing in the morning, then an early cup of coffee or tea won't kill you, but I find with all the other stimuli I have early in the day, I really don't miss it.  Waking up without that jolt of caffeine in the blood is actually more pleasant, and if you really miss that jolt, reread the paragraph on a cold shower.

When it comes to additives to your coffee or tea, I would like to stress that I highly recommend passing on the sugar.  At no point in the day is refined sugar good for you, but I find it particularly destructive to your diet, appetite, and self-control first thing in the morning.  If you cut the large majority of sugar out of your diet all together, you will find that you no longer crave the sweetness, and things that used to need sugar will now taste fine on their own.  In addition to leaving out the sugar, if you add a little fat to your coffee it will slow down the absorption of the caffeine and give you more sustained energy instead of a quick jolt followed by a crash.  The traditional cream or half-and-half works fine for this, or you can go the more extreme route and use butter, as advocated by fans of bulletproof coffee.  Just remember, if you think using skim milk in coffee is a healthier option, lactose is just sugar, so skim milk is just sugar water that came from a cow.  Just say "no".

And that's my morning routine, for now.  As always things will continue to evolve, hopefully towards the positive.  I hope some of you were able to gain something from this post, and maybe even improve your own morning routines a little.  For everyone else, don't worry, I have several more posts on the way, including setting up a VPN using OpenVPN on a Raspberry Pi, building a bluebird-house with a built-in video camera activated by a motion sensor, building a chicken run, and live-streaming video from the chicken coop.  Until next time, stay safe and keep building.

EDIT: After my initial post, I was discussing my morning routine on reddit.com in the /r/productivity subreddit.  A user by the name of /u/iEphemeralX recommended I read the book The Miracle Morning: The Not-So-Obvious Secret Guaranteed to Transform Your Life (Before 8am).  Since I prefer audio books, I hoped over to Audible.com and picked up a copy.  While I can't say it was the absolute best self-improvement book I ever read, it was good enough that I finished the book in two days, and I would certainly recommend it to anyone looking improve their life.  Since reading the book, I have also adjusted my morning routine slightly.  I now get up at 5:30 instead of 6am, and I have added 15 minutes of meditation, followed by prayer, gratitude, and intentional thinking.  If you are looking for a little motivation or some direction on how improve your life, I recommend you give it a read.