#!/usr/bin/python import RPi.GPIO as GPIO import time import os import sys # Set pins to BOARD GPIO.setmode(GPIO.BOARD) # Setup pins for relay Motor2A = 36 Motor2B = 32 Motor2E = 37 GPIO.setup(Motor2A,GPIO.OUT) GPIO.setup(Motor2B,GPIO.OUT) GPIO.setup(Motor2E,GPIO.OUT) # Setup pins for filter Motor1A = 16 Motor1B = 13 Motor1E = 7 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) GPIO.setup(Motor1E,GPIO.OUT) #PIR setup #set up PIR pin PIR_PIN = 15 #set PIR pin as input GPIO.setup(PIR_PIN, GPIO.IN) #set up BUTTON A pin BUTTON_PINA = 31 GPIO.setup(BUTTON_PINA, GPIO.IN) #set up BUTTON B pin BUTTON_PINB = 33 GPIO.setup(BUTTON_PINB, GPIO.IN) #below is the function MOTION which is called by the main program at the bottom def MOTION(PIR_PIN): print "motion detected" # double check # time.sleep(2) while GPIO.input(PIR_PIN)==1: print "confirmed" # time.sleep(1) # switch relay on GPIO.output(Motor2A,GPIO.HIGH) GPIO.output(Motor2B,GPIO.LOW) GPIO.output(Motor2E,GPIO.HIGH) print "light on" # wait 20 seconds - can change this print "waiting" time.sleep(10) # check the PIR again, if its on wait for another 20 seconds while GPIO.input(PIR_PIN)==1: print "still waiting" time.sleep(5) #turn off the relay GPIO.output(Motor2E,GPIO.LOW) print "motion stopped" print "Light off" def BUTTONA(BUTTON_PINA): print "button A detected" time.sleep(1) while GPIO.input(BUTTON_PINA)==1: print "confirmed" os.system('sudo poweroff') def BUTTONB(BUTTON_PINB): print "button B detected" # os.system("sudo ifup --force wlan0") # ---MAIN PROGRAM STARTS------ # message is prined at startup & gives the PIR sensor 2 seconds to settle down before the program starts. print "PIR Module test press Ctrl+C to exit" #turn off the relay GPIO.output(Motor2A,GPIO.HIGH) GPIO.output(Motor2B,GPIO.LOW) GPIO.output(Motor2E,GPIO.LOW) print "Light off" time.sleep(1) print "Sending signal" GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) time.sleep(0.1) GPIO.output(Motor1E,GPIO.LOW) print "Filter off" time.sleep(5) print "ready" # this runs all the time, checking to see if the PIR or buttons are triggered try: GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION, bouncetime=300) GPIO.add_event_detect(BUTTON_PINA, GPIO.RISING, callback=BUTTONA, bouncetime=300) GPIO.add_event_detect(BUTTON_PINB, GPIO.RISING, callback=BUTTONB, bouncetime=300) while 1: time.sleep(100) # stop program if ctrl+C is pressed except KeyboardInterrupt: print "quit" GPIO.cleanup()
Category Archives: garden
Trailcam – 1. Introduction
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates

Description
The intention is to create an animal camera to video the wildlife of the garden and the window cill bird feeder. The idea is that the camera could be used outside (night or day) powered by battery then be moved indoors to the window cill to record the bird feeder where it can be powered by mains.
Previous versions
This is the 3rd version of the animalcam / trailcam with the older versions showing the progression and further useful information. Previous versions can be found here:
General construction
To create this I’ve used a raspberry pi A,* powered by battery (which can be disconnected when connected to the mains) along with a pi noIR camera that has a moveable IR filter to give reasonable colour in the day and respond to IR light in the dark.
*: now using a pi zero – see here
The trailcam comprises of a main breakout board with the other elements attached separately – this helped me to construct the project in sections and allows for a level of upgrade later on. I ran in to issues on the previous version where the female to female jumpers kept coming off, resulting in a bunch of wires that I had no idea where they went, so this time I’ve soldered on JST connectors and colour coded them.
Overall concept:
In its current form, the trailcam simply uses pikrellcam to record video when it detects motion. In the dark, a PIR sensor is activated which turns on an I.R. lamp, pikrellcam then records the motion event as if it were daylight. A switchable I.R. filter is fitted to the camera which enables good quality day time video and I.R. sensitive night time video.
The facility for bypassing the software motion detection is built in so that the recording of video can be triggered by the PIR if required.
Useful links:
I’ve cobbled this together using the how-to’s, programs, diagrams and general knowledge of some very clever and generous people that have taken the time to make their information public knowledge online. Despite my limited skill level it actually works!
The following are the main personal blogs and websites that I’ve used for help. In addition, the suppliers as noted in section 7 have really useful websites and blogs to go with their products.
South Somerset Weather
This was the original inspiration and also has some great videos. |
http://www.afraidofsunlight.co.uk/weather/index.php?page=trailcam
|
Pikrellcam
The motion detection software used for this trailcam |
http://billw2.github.io/pikrellcam/pikrellcam.html
|
Envatotuts+
Description, diagrams and python prog to control the L293D chip that operates the IR filter |
http://computers.tutsplus.com/tutorials/controlling-dc-motors-using-python-with-a-raspberry-pi–cms-20051
|
Trevor Appleton
Handy guide for explaining cron |
http://trevorappleton.blogspot.co.uk/2014/06/scheduling-python-programs-using-cron.html |
Raspberry pi spy
Lots of useful tutorials |
http://www.raspberrypi-spy.co.uk/
|
This description has been split down in to the following sections:
Trailcam – 3. PIR sensor
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates
Description
The PIR sensor is a pretty standard piece of kit – I got mine from Tandy however they’re really common and stocked by the usual suspects (adafruit, pimoroni, Modmypi,maplin)
In the first version I had the PIR sensor triggering the recording however for this version I’ve altered it so that it just turns the IR lamp on leaving the motion detection in the software to do its thing..
Install

I had hoped that the PIR would “see” through the plastic on the box however it wasn’t happening so I ended up removing the defractor / lens, drilling a hole through the box to push the sensor through then stick the lens on the outside. It does increase the chance of letting water through however there isn’t really much choice and a big chunk of gaffer tape should sort it out.

Control programme
I modified the control program from raspberry pi spy to run the previous version of the trail cam however this version only needs to turn the light on an off, hence why it is a bit of a mess.
EDIT: Revised version here
#!/usr/bin/python # Original # By : Raspberry Pi Spy # Author : Matt Hawkins # Date : 21/01/2013 # Modification # By : G # Date : 24/04/2016 # Import required Python libraries import RPi.GPIO as GPIO import time import subprocess # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) # Define PIR GPIO to use on Pi GPIO_PIR = 22 print "PIR Running (CTRL-C to exit)" # Set PIR pin as input GPIO.setup(GPIO_PIR,GPIO.IN) # Echo Current_State = 0 Previous_State = 0 # Define GPIO for lamp control GPIO_LIGHT_ON = 17 # Set lamp on GPIO as output GPIO.setup(GPIO_LIGHT_ON,GPIO.OUT) # Echo try: print "Waiting for PIR to settle ..." # Loop until PIR output is 0 while GPIO.input(GPIO_PIR)==1: Current_State = 0 print " Ready" # Loop until users quits with CTRL-C while True : # Read PIR state Current_State = GPIO.input(GPIO_PIR) if Current_State==1 and Previous_State==0: # PIR is triggered print " Motion detected!" GPIO.output (GPIO_LIGHT_ON,1) print " Light on" # Capture a 5 second video # print " Record start" time.sleep(20) # Record previous state Previous_State=1 elif Current_State==0 and Previous_State==1: # PIR has returned to ready state GPIO.output (GPIO_LIGHT_ON,0) print " Light off" print " Ready" Previous_State=0 # Wait for 10 milliseconds time.sleep(0.01) except KeyboardInterrupt: print " Quit" GPIO.output (GPIO_LIGHT_ON,0) # Reset GPIO settings GPIO.cleanup()
Trailcam – 4. I.R. Lamp
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates
Description
The IR lamp is a kit from Maplin. I’d priced up getting the LED’s individually and putting them on to a bit of veroboard and the kit worked out much cheaper.

It is designed to be 12v but it works satisfactorily with a 9v source. I have bought another of the kits when they were on special offer so I may end up swapping out the resistors to make it truly 9v.

Powering the lamp
I wanted the lamp to be powered separately from the PI, initially because it is much easier to do but also because it’ll let me be a bit more flexible if I choose to change the lamp or power source (It also helps to reduce the load on the battery). I settled for a relay kit from Ciseco – as with the lamp it proved cheaper than buying the bits.

I’ve soldered this board so many times the tack has come off, so I’ve had to find alternative places to put the wires! This has become a major weak point of the build.
For debug purposes I’ve produced 2 python programs – one to turn it on and the other to turn it off.
On
#!/usr/bin/python import RPi.GPIO as GPIO import time import subprocess # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) # Define GPIO for light GPIO_LIGHT_ON = 17 # Set light on GPIO as output GPIO.setup(GPIO_LIGHT_ON,GPIO.OUT) GPIO.output (GPIO_LIGHT_ON,1) print " Light on" GPIO.cleanup() Off #!/usr/bin/python import RPi.GPIO as GPIO import time import subprocess # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) # Define GPIO for light GPIO_LIGHT_ON = 17 # Set light on GPIO as output GPIO.setup(GPIO_LIGHT_ON,GPIO.OUT) GPIO.output (GPIO_LIGHT_ON,0) print " Light off" GPIO.cleanup()
Trailcam – 5. I.R. Filter
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates
Description.
I bought the filter from an EBay seller in China. It took a while to arrive but was extremely cheap and pretty good quality. It comprises of a main body with an electrical connection coming out of it and works by sliding a tiny IR filter in front of the camera, replacing the missing filter on the pi noIR camera to give a better colour reproduction under natural light.
To get it to work the wires need to receive a brief current, when this is reversed (i/e the previous +ve connection becomes –ve) it goes the other way. I needed to find something that could reverse the polarity on a pair of wires and came across this description about a motor controller. http://computers.tutsplus.com/tutorials/controlling-dc-motors-using-python-with-a-raspberry-pi–cms-20051
I built this one using the diagram provided by Envatotuts+ on to a lovely adafruit permaproto board.
Mount to cam
The IR filter is clearly from some sort of CCTV camera and so comes with a couple of mounting holes. These almost line up with the mounting holes on the camera board and pimoroni camera holder so I’ve bolted them together with some nylon nuts and bolts.
I tried to fit the camera unit behind the clear plastic of the box but the result was disappointing with a very noticeable blue / grey tinge so I ended up cutting a hole through it and pushing the camera assembly through. I’m not too happy about the camera position in relation to the filter housing and intend to jiggle it about a bit in the future.
In order to prevent water getting in I’ve put a clear lens over the outside. This is from a go-pro and was a very cheap pattern part. A bit of tape and some blu-tak and it’s firmly in position.
Automatic switching.
In order to use the camera as both a night time trail cam and a daytime birdfeeder camera I needed to get the IR filter to switch automatically. This will also help to give a better picture on the trailcam in the summer when full darkness is brief.
I’ve looked at putting in an LDR (and may still do in the future) however for the time being I’ve set up cron to run the on / off program at specific times. Pikrellcam also has the facility to run scripts and I will investigate this in the future also.
Python script (taken from the Envatotuts+ blog)
filter off
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) Motor1A = 16 Motor1B = 18 Motor1E = 22 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) GPIO.setup(Motor1E,GPIO.OUT) print "Sending signal" GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) GPIO.output(Motor1E,GPIO.HIGH) sleep(0.1) print "Filter off" GPIO.output(Motor1E,GPIO.LOW) GPIO.cleanup()
filter on
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) Motor1A = 16 Motor1B = 18 Motor1E = 22 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) GPIO.setup(Motor1E,GPIO.OUT) print "Sending signal" GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) sleep(0.1) print "Filter on" GPIO.output(Motor1E,GPIO.LOW) GPIO.cleanup()
Addition to the cron
00 16 * * * /usr/bin/python /home/pi/filteroff.py
Trailcam – 6. Control buttons
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates
Description.
When the camera is put out in the garden it often drops the Wi-Fi link on the way so I wanted to fit the facility for a hardware button so that I could press it when the camera is positioned outside and re-establish the link.

When indoors & for testing I can use simple buttons however anything put outside stands the chance of being chewed so I’d like to be able to fit a waterproof button at a later date.
I’ve taken the button control straight from the main breakout board and it has the pull up resistors fitted before the male connector pegs, so it is simply a case of getting the new buttons fixed in the case and wiring on to them. I also added an LED that flashes (1, 2 or 3 times) depending upon which button is pressed.
The button wiring has been a huge pain. The single core wires regularly snap at the join with the board resulting it a confusing mess of soldering and bodging. The board and wires perform perfectly and it is all an issue with my workmanship – this are would really benefit from having a custom PCM made.
The following basic python script monitors and controls the buttons / LED and is run at startup via my new favourite thing – cron!
Python prog
#! /usr/bin/python import RPi.GPIO as GPIO import os import sys import time # set up button references BUTTON1 = 18 BUTTON2 = 4 BUTTON3 = 7 GREEN = 3 # set up buttons GPIO.setmode(GPIO.BCM) GPIO.setup(BUTTON1, GPIO.IN) GPIO.setup(BUTTON2, GPIO.IN) GPIO.setup(BUTTON3, GPIO.IN) GPIO.setup(GREEN, GPIO.OUT)
# button 1 = green - reboot # button 2 = yellow - restart wifi # button 3 = red -
# turn light off GPIO.output(GREEN,GPIO.LOW) while True: if GPIO.input(BUTTON1) == GPIO.HIGH: print("button 1") GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) os.system("sudo reboot") elif GPIO.input(BUTTON2) == GPIO.HIGH: print("button 2") GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) os.system("sudo ifup --force wlan0") elif GPIO.input(BUTTON3) == GPIO.HIGH: print("button 3") GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) GPIO.output(GREEN,GPIO.HIGH) time.sleep(.5) GPIO.output(GREEN,GPIO.LOW) time.sleep(.5) else: print("pin is low") time.sleep(2)
Trailcam – 7. Completion
Other sections
- Introduction
- Basic setup & Power
- PIR sensor
- IR lamp
- IR filter
- Buttons
- Completed pics, improvements and parts list
- Updates
Box / case
I’ve built the camera to be modular which helps when tinkering about with it but does take up a lot of space, hence the rather cramped appearance.




Component list & suppliers
GPIO Pin summary
Board
(physical) |
BCM
(logic) |
Use |
12 | 18 | Button 1 (green) – reboot |
7 | 4 | Button 2 (yellow) – restart wi-fi |
26 | 7 | Button 3 (red) |
5 | 3 | LED |
16 | 23 | Motor 1A |
18 | 24 | Motor 1B |
22 | 25 | Motor 1C |
11 | 17 | IR Lamp (connection to relay) |
15 | 22 | PIR sensor |
Examples
Filmed through glass and saved as an mp4
Filmed outside running on batteries. Video has been cut down in length using windows movie maker so is saved as a wmv
Now using adobe elements and with the interesting vids cut together
Improvements
Now that the weather has given me the chance to run the project outside, there are a couple of areas that I’m not happy with:
- reflection – there looks to be a noticeable reflection from the light on the lens (not helped by the badger nosing it!. I need to find some way of keeping it waterproof whilst stopping the reflection – also might try and find a way to stop the IR filter cutting off the corners of the image.
- Brightness of image – the image is too dark and noticeably darker than the previous version. I think that this is partly due to the camera being set as “auto” (hence it brightening up after the bager nosed it) and partly due to the lamp
- Lamp connection – The hardware weak point is the connection to the lamp. At every opportunity the wires fall off to such an extent that the solder pads on the lamp have fallen apart.
Animalcam v2.1 – alterations
I’m in the process of altering the outdoor camera to make it a bit more versatile and giving it the ability to be used via battery outside and on the window cill to look at the birds visiting the feeder.
To do this I’ve changed the software to PiKrellCam and modified the PIR sensor to only control the light, so the light comes on when the PIR is triggered and the motion detection software does its thing without interference.
The video above shows the first experiment of the camera outside with the light going off occasionally due to me not setting up the timeout for it correctly.
I have also added a high gain wireless network adaptor to the setup that I had kicking around (this one) It’s from Mod my pi and quite power hungry however I’ve swapped the rpi B for a rpi A in the setup and I’m only draining the battery 1/2 way for 10 hours use. The reception is patchy depending upon the position of the camera outside but my new router may help out with this when it arrives.
The next step is to play around with an IR cutout filter like this to try and get a more flexible setup.
Animalcam version 2
I’ve finally got around to constructing version 2 of the animalcam, following a cd card corruption in the spring.
It is broadly the same as version 1 but in a sturdier, more waterproof box. The clearer lid does help with the quality of the video however the PIR sensor was struggling to “see” through the plastic so I’ve drilled a hole in the lid and fitted the diffuser outside.
I’ve built a much smaller breakout board from the pi – simply a bit of veroboard with a 26 way plug on the bottom and a couple of connectors on the top for attaching the PIR & relay etc. The relay has been switched out from a latching to a standard type. Partly due to the latching one breaking and partly to simplify the connections. There has been no noticeable reduction in battery life.
The software has been updated to include a new raspbian and the new version of RPI web cam interface. The python script controlling it all remains as before – basically a botched together version of this one from raspberry pi spy, modified here, with the pipe calling discussion described in the thread here.
It now doesn’t start automatically so I need to plug in the wifi adaptor, access it via putty and get it running using nohup (otherwise it dies when the connection is terminated) To simplify this I’ve put it in a simple bash script:
#!/bin/bash
#starter for trailcamtrigger
sudo nohup python /home/pi/trailcamtrigger.py &
echo trailcamtrigger started
Once running, I unplug the wifi as it is very thirsty on the battery.
Overall I’m pleased with the change. On the plus size it is now much sturdier, less likely to fall over and with a much clearer picture.
The above video is “raw” from the camera with a B&W filter added in youtube.
There are a couple more here that I’ll add to when something interesting occurs.
I’m not so happy about having to unscrew the lid each time I put it out and bring it in – the first & last minutes of video are of my head! The battery is now harder to access however this has been eased by using a longer camera cable.
The next step with this is to alter the light and possibly fit an on/off button to save having to fiddle about with wifi and putty. The light doesn’t seem as effective as before – i’ve tried rotating it by 90° and changing the angle but it might need a rethink.
Animalcam version 1
I’ve had some success this year with a raspberry pi based infra red camera – along the lines of a trailcam.
I’ve based it and the python script on the excellent information here with the addition of a locking relay based infrared lamp that is triggered when the camera is run.
Hardware.
Infra red lamp kit – from Maplin
Raspberry pi model B – from CJE micro’s
Noir camera – from CJE micro’s
3v latching relay kit – from ciseco
PIR sensor – from Tandy
Following a rebuild, I upgraded my home made stripboard effort with an Adafruit Small-Size Perma-Proto board from Tandy
Battery from – from Amazon
The 2 kits worked out to be very cost effective and much cheaper than getting the components “loose”.
The maplin IR lamp kit is labelled as 12v however it works fine with a 9v battery.
The prototype:
Software
The unit runs RPi Cam Web interface by silvanmelchior as described on the rpi forum here. This is called via a pipe from a slightly modified version of the script originally from raspberry pi spy, and as modified here, with the pipe calling discussion described in the thread here.
As you can see, I’ve borrowed a lot of things from some very knowledgeable people so thanks to all concerned for all of your work and for teaching me!
Here’s a front view of the unit – I’ve put everything inside the clear lunchbox to keep it dry. This hasn’t had any effect on the PIR operation and the light is bright enough.
Internal view.
A festival of gaffer tape and wires! The pi is in the case, the pir beneath the tape. I’ve added a couple of switches, one turns the pi off with a “sudo poweroff” (the other is currently a spare).
The whole thing is stuffed in to an ASDA lunchbox and linked to the battery. It’s then wedged on a brick in the back garden under the bird feeder with a water bowl and some food scattered about…. and surprisingly works! – I’ve put some of the videos on youtube with the whole lot here.
Our first vid of a badger:
A compilation where you can see the flash as the cam is triggered before the light:
This is most definitely a prototype however the results have been much more than we expected. I’m now working on a version 2.0.