Cat-Wrangler Project: CATTACK!


Local cats are digging up a freshly planted garden!


MPEG-4 [AVI 255KB]

Use a Raspberry Pi and a web cam to detect motion in the garden and activate a sprinkler to scare the furry fiend away.

Here is a fun video showing the final device in action!

Project Overview

Logic Device: Raspberry Pi, referred to simply as a "Pi" in this document.

Camera: Cheap generic web cam. Only requirement is to be Linux / Debian compatible.

Control Circuit: Simple MOSFET gate circuit to allow the 3.3V from the Pi to drive a large current for the solenoid valve.

Sprinkler Valve: Cheap "washing machine" style solenoid valve, fits directly to a tap and is powered by a 12V power supply. The outlet is connected to a sprinkler.

Software: Use Motion program to capture video and analyse it for movement. When movement is detected it can record images and video as well as trigger a Python script to activate a GPIO pin.



The Pi shown with µSD card and adapter.

Model B rev 2 of the Raspberry Pi. Loaded with the default Pi Debian installation (Raspbian) on a standard 8GB µSD card. Fully updated (firmware and OS) as of July 2013. The Pi is being temporarily powered using a phone charger that was on hand, but a dedicated power supply is a good thing to have. Looking around on-line I see that a dedicated 5V power supply for your Pi is going to cost £5-10.

Tip: if on an absolute budget then keep an eye out for free or old second-hand phone chargers to fill this role, though be careful as these have been linked to problems with corruption of the SD card.


The web cam shown mounted in a small plastic plant pot to reduce window reflection.

"HP AU165AA#ABB Pro Web cam - Panda 15C" from Amazon for £5. It was impossible to determine whether this web cam would be Linux compatible in advance, I simply crossed my fingers and hoped for the best while knowing that I may have to return it and try another. In the end I got lucky!

Control Circuit

Salvaging parts to build the control circuit. The salvaged small-signal transistor shown here (circled) was subsequently replaced with the MOSFET.

I had a breadboard on hand, but if needed a small breadboard can be prchased for £5 or so. The parts for the circuit were mostly salvaged from an old speaker amplifier, except for the special low-voltage MOSFET STP36NF06 [PDF 324KB] which was bought from Rapid Electronics for £0.47.

Sprinkler Valve

The solenoid as it came from Amazon. Keys are for scale.

A cheap (£6.50) 12V solenoid valve from Amazon, powered by a 12V power supply that was salvaged from an old flat bed scanner.

Details and Discussion


The Raspberry Pi was purchased new for this project but is sure to have a long and fruitful life making other projects a reality in the future. The µSD card came from my Samsung Galaxy S2, which I also used to format the card before proceeding. Other smart phones will be able to format cards in this way, and digital cameras are also able to do this. Obviously I used an SD adapter to put the µSD card in the Pi. While the general details of how to do this are on the Pi website, here is a log detailing how I set up the Pi:

//Cat Wrangler - Software Config Log
//-1. Use SGS2 to format card and clear previous image.
//0. Flash SD card with Wheezy Raspbian, 2013-02-09
//1. Boot Wheezy: configure
// - Expand root partition: restart
// - Turn on SSH server
// - Change pi password, since Pi will be on internet: DO THIS!! The root account is disabled by default. Leave it that way.

// **We leave the desktop turned off to save resources for the programs that will be running.

// - Put Pi on network. Use router to idenfity IP address. Reserve as appropriate. Setting a static IP on the Pi is a pain, using fixed DHCP was much easier for my setup.

//Use remote SSH over LAN to access the Pi and verify that it is operating correctly. Proceed to next section.

//2. Install the follow dependencies (also handy for us anyway) which may take ten minutes to install (depends on net speed) and may require input

sudo apt-get update

sudo apt-get -y install apache2 mysql-server libmysqlclient-dev php5 php5-mysql g++ make netpbm libssl-dev libjpeg8-dev libmime-perl libwww-perl perl-modules libdate-manip-perl libarchive-zip-perl libmime-lite-perl libdbi-perl libdbd-mysql-perl libpcre3-dev libclass-dbi-mysql-perl openssl libssl-dev libclass-dbi-mysql-perl libgnutls-dev libsys-mmap-perl imagemagick uvccapture ffmpeg

// Test the web server by pointing a browser (on another computer) at the Pi's IP address (in my case: http:

// Force apache to load the PHP and MySQL modules by restarting it

sudo /etc/init.d/apache2 restart

// Re-test the web server by pointing a browser at the Pi's IP address
// A proper test requires making a PHP file with to do that:

cd /var/www
nano test.php

// Add the following line to the file:
// To save and quit hit CTRL+O (save) then CTRL+X (exit)

// Point web browser at this page: http:
// (obviously change to your own Pi's address)
// Scan the info page for MySQL to ensure that it installed properly. HOT DOG!!

// While in /var/www make a folder, we'll use it for motion later

sudo mkdir /var/www/motion

//3. Download and install motion - Get working with USB web cam

sudo apt-get install motion

// Run motion in console mode

sudo motion

// Check that motion runs, but it may not detect the camera.
// Close the program with CTRL+C.

sudo reboot

// Once rebooted, try to run motion again, and if it still won't run and/or detect the camera then investigate and edit the config file.
// Edit the config file using nano with the following command:

sudo nano /etc/motion/motion.conf

// If your pi has internet access then you can pull my motion config file directly from my server here. At the command line on the Pi type:

sudo wget -O /etc/motion/motion.conf

// You now have "" in your current folder and you can do what you like with it.

// For later convenience, or if using my config file, make an output folder (in the web root) here

sudo mkdir /var/www/motion/

//4. Set up Python script for controlling IO

sudo nano /var/www/motion/

// And type out the script supplied here, or something similar.

// If your pi has internet access then you can pull the script file directly from my server here. At the command line on the Pi type:

sudo wget -O /var/www/motion/

// You now have "" in your current folder and you can do what you like with it.


In the log above you will see that I offer a download for my motion.conf file and my python script. You are welcome to download them using the links (click to view, right click and "Save As..." to download) on this page or to use wget to download them directly to the Pi.

My motion.conf file allows unrestricted access to the live video feed and to the http based control system. Use my setup with caution!

I can't explain the Motion configuration in its entirety here, so at this point you should probably read the entire configuration file for yourself from top to bottom and learn how it works. There is also assistance on the Motion website and the wider internet.

MPEG-4 [AVI 716KB]

You are free to explore the many options that Motion offers, but I would suggest using the live view to check the image capture and image quality. I found that the Pi was only able to run the live view at 1 frame per second. As well as the live view, Motion can save single frames and video whenever the program detects movement in the image. I strongly suggest turning these features on for debugging and assessing the ability for the program to detect motion in your garden. It is also terribly good fun watching the comings and goings of animals when no people are around. We discovered quite a community of friendly (and less so) cats that we had never seen before. It would also be great to add a night vision camera and use this to capture images and video of nocturnal creatures. But more about that in the final section of this guide.


This camera mounting was zero cost, very simple, and totally impervious to the elements!

The USB web cam plugs directly into the Pi and was automatically detected by Linux. There is some configuration required because Motion needs to know what mode to use with the camera: for example resolution, frame rate and colour format of the images. It would be easy if the manufacturer provided a full list of specifications and details, but unfortunately that information was not on hand. Instead, Motion offers a testing mode that allows you to try different configuration options for the camera. If getting started with an unknown camera I would recommend trying 640x480 at 5 frames per second in the YYUV colour space. Nearly every cheap web cam will support this mode.

Most webcams will washout in bright light.

To make sure the camera was protected from the elements I mounted the camera inside the house and pointed it to look out through a window. To minimise reflections I made two shrouds from old recycled plant pots. These were simply washed thoroughly, cut to size and taped onto the window with regular tape. This approach has worked extremely well and I can thoroughly recommend it. However, if the camera is set to look directly through the glass then reflections from the glass (especially double glazing) may be a problem. Simply tilt the camera slightly (a few degrees will do) to avoid this problem.

Finally, considering the cost, this camera has worked very well except in very bright light. A cheap web cam of this style is designed for use indoors. As such it has a large aperture that lets as much light onto the CCD sensor as is possible. When used outside, in bright light, the image is entirely saturated. There is an excellent article here describing how a web cam can be modified to use a smaller aperture for better performance in bright light. I have not tried this with my web cam, but have every reason to believe that it would work. Otherwise, a more sophisticated camera set up can be used. I am now experimenting with a cheap security camera from eBay and a cheap USB capture device. So far I have been unable to get the capture device to work with Linux, but initial testing under Windows has shown improved images from the security camera, as shown below.

The camera was bought on eBay for £10 and the EasyCap capture device on Amazon for £5.
Camera comparison with indoor image.
Camera comparison with outdoor image, unfortunately not bright enough to saturate web cam as it is now winter!.
The cameras were tested side by side.

The improvement may not be obvious, but is much more apparent in bright light.

Control Circuit

Figure A: the simple circuit.

At its core the control circuit is very simple and is shown clearly in Figure A. The Pi can produce a 3.3V digitial signal on each GPIO pin, but these are only able to deliver a maximum of 0.016A (16 mA) each. The solenoid valve requires 0.3A at 12V, which is much bigger. So how do we do this? There are many ways to build this circuit, but I think the simplest is to use a device called a MOSFET. This is similar to a transistor, which if you are not familiar with, acts like a kind of variable switch: as well as being on or off it can have some value in between, a bit like a regular kitchen tap.

However, unlike a transistor a MOSFET is able to switch large loads, and the one I have used here is rated at 60A and 100V. There is no problem using a MOSFET well below its specified rating. However, not all MOSFETS will turn on fully with just a 3.3V signal. So the one I have chosen is a special MOSFET that opens fully at just 2.5V, which is perfect for our application here. The only detail to this simple circuit is the "pull down" resistor R1. This resistor is very important since a "floating" gate will leave the MOSFET is in an undefined state, which will cause it to either switch on, off, or wobble in between. It can even break some MOSFETS to leave them like this. So what's the idea behind R1? If you make the circuit without R1 then you will find that the MOSFET will switch on, but not off. This is because the Pi is simply turning off its 3.3V signal and some of that charge stays on the MOSFET gate and it stays on. What we really want is for the signal to go to ground, as this will then switch off the MOSFET. The resistor R1 provides a path to ground, and once the voltage from the Pi is removed the charge on the gate of the MOSFET will drain to ground and the circuit will switch off.

Infinite Current?
It is common to think of a short circuit as having zero resistance, which at a certain voltage: I = V / R, and with R = 0 leads to undefined, or infinite current. In reality R is not 0, it's just a very small number. You can measure the resistance of a piece of wire using your DMM. I just did this and for the short piece on my desk I measured 0.000000017Ω => I = 3.3 / 0.000000017 = 196700000A!!! The Pi can't really deliver this current, it simply cooks itself and stops working :(

It is important that R1 is a large value. Why is this, and how large is large? Remember that I mentioned the Pi as capable of delivering 16mA from its digital pins? What this means is that a short circuit (R = 0Ω) from a digital pin to ground will draw infinite (see box) current which is bad for the Pi. A very large resistance will draw a tiny current from the Pi, which is good for the Pi, but if it is too large then the MOSFET will take too long to switch off. For this project the switching time is not significant in any way, but if building a similar circuit to turn lights on and off quickly (modulation, for sending signals, or driving LEDs. As an aside, LEDs can be driven brighter if you turn them on and off again really fast) then this could be a problem.

So why don't we calculate the minimum resistance of R1 to ensure that the MOSFET switches off and the Pi does not break? The maximum current that the Pi can deliver is 16mA. We use the simple equation (Ohm's law) I = V/R and rearrange this to R = V / I. Now we can substitute and get R = 206Ω. So as long as R is larger than this value the Pi will not blow up? But what about the MOSFET? Doesn't it draw some current from the Pi? The answer is yes it does, but, the resistance (specifically referred to as the "Input Impedance") of the MOSFET is very very large, in the mega-ohm range. How much current will it draw? I = V / R => I = 3.3 / 106 = 0.0000033A. Such a small current can be ignored. OK, so if we only need a 206Ω resistor why is the circuit shown with a 100,000Ω one! In the first instance, there's an issue of safety, we don't really want to run the Pi right at its limits. We could double the resistance to 412Ω, but to be really certain we can double it again to 824Ω. Since resistors don't come in all values it makes sense to just round this up, and may as well go to 1000Ω which is a common value. That is the absolute minimum resistance I would connect to the digital pins on the Pi. But here's the bad news, if you made this circuit using a 1K resistor you will find that it doesn't work! If you have one, go ahead and try it. To discover why, take your DMM and measure the voltage at the input to the MOSFET. Remember that the MOSFET needs 2.5V to turn on? I made the circuit here with a 1K resistor and I measure 1.5V at the gate. Why is this? It's because the output pin of the Pi is suffering voltage droop due to the current drain through R1 to earth. So while the Pi is not blowing up, it is struggling to deliver the full 3.3V as well as this current. What to do? The solution is to rise the resistance of R1 until the MOSFET sees more than 2.5V, which is enough to switch it on fully. I simply had a 100K resistor on hand, and found (measured using DMM) that this gives 3.0V at the gate, which is enough for us. Anything in the range 50K to 1000K will probably be just fine, though really large values will affect the MOSFET's ability to switch off.

Figure B: the complete circuit.

The circuit shown in Figure A will work, but it is not suited for every day use. This is one of the great, and rewarding, challenges of engineering: to make something that doesn't just work, but works really well! Imagine, if you will, something as simple as a garden gate. Now, nearly anyone with a hammer and some wood can make one, and I am sure there are many such gates in people's gardens all around the world. But to engineer one that can open and close a dozen times a day for ten years, survive freezing weather in winter, scorching sun in summer, be lightweight, UV resistant, easy to paint, and made cheaply enough that it can be sold (or built) at a reasonable price. Wow, now that is a challenge! So we wish to take our circuit to the next level, and to actually engineer this circuit so it will last and work reliably we have to make some modifications, as shown in the complete circuit in Figure B.

(A) This resistor (R2) provides further protection to the Pi. The gate of the MOSFET has a small capacitance, so that when the digital signal goes hi there is an "inrush current" from the Pi to the MOSFET. It could be high, higher than 16mA, but it only lasts for a very short period of time. Depending on the MOSFET (and I mean the specific one you have in your hand, not just the make and model) this current may present no problems, or it may cook the Pi on the first go. Also, it may work fine for weeks, then mysteriously stop working. To limit the damage from this inrush current we simply use a small valued resistor here. If the resistor is too small then it provides no protection, if it is too large then the voltage at the MOSFET will be reduced (we've effectively made a voltage divider network) and it will not switch on. A range of 100Ω to 1K should be fine.

(B) This diode is called a "flyback" diode and it is here to protect the MOSFET. It is only required for protection from solenoid valves. The valve consists of a coil that creates a magnetic field which pulls the valve open against a spring. When the valve is turned off the spring pushes the valve closed and this action can produce a voltage spike in the circuit. That voltage spike may be sufficient to damage the MOSFET. The diode short circuits the voltage spike, yet does not affect the normal operation.

(C) The capacitor C1 is optional and is here to protect the power supply. When the MOSFET is switched on the solenoid draws a large current to actuate the switch. Once the valve is opened then only a small current is required to keep it open. The capacitor provides a buffering effect and offers some "oomph" for turning on the solenoid. Many power supplies have capacitors on their voltage rails to provide this smoothing effect anyway, so the capacitor is an optional addition to the circuit. You will notice that in some photos the capacitor is not shown, and indeed I was unable to fit in in the plastic case, so it was removed.

(D) The LED shown offers no protection but is useful for seeing the state of the switching circuit, especially if the solenoid is outside! The resistor R3 is chosen to limit the current through the LED, and is specific to the type of LED being used. Having said that, most LEDs can be run off 12V or less with a 1K resistor or greater.

(E) Finally, this switch was never added to my project, but would serve as a "manual override" for turning on the tap. Ideally the switch would be weather proof and mounted outside next to the tap. This would allow anyone doing gardening to simply override the computer control and use the hose as normal. Another useful addition would be a switch that prevents the solenoid from firing, which would allow a person to temporarily, and conveniently, disable the device while working in the garden. There are a few ways to do this: breaking the signal between the Pi and the MOSFET, or turning off the 12V supply, either at the wall or within the circuit. The exact implementation is left as an exercise for the reader.

Most of the components here were salvaged second hand from an old pair of amplified speakers. The only part purchased new was the MOSFET, which cost around £0.50. To make the order substantial I bought a set of five of these MOSFETs as they can be used for other projects. If you really do not wish to build this circuit yourself, consider buying a MOSFET controller board. In addition to the Pi these boards are compatible with a wide range of embedded systems (Arduino, Beagleboard Black, Teensy, etc...) and offer a very nice set of features such as opto-isolation, status LEDs and convenient screw terminals for hookups.

Sprinkler Valve

The solenoid attaches directly to a garden tap.

12V solenoid valves come in a wide range of sizes and types and quality. This is because industrial automation can be very demanding and potentially crucial to a production line or chemical handling process. As such, a top-of-the-line stainless steel solenoid valve could easily cost many hundreds of pounds, or even over a thousand! Luckily, a common type of solenoid vales is the sort found in washing machines and dishwashers, which are perfect for this project as they are designed to work with mains pressures and suitable flow rates. Unfortunately, and something to keep in mind, is that many washing machine solenoids run directly from mains power (240 or 120V) and would not be suitable for a home/school project such as this one. However, 12V models do exist and this is what I purchased from Amazon. A tip shop or recycling shop would probably have some old washing machines that could be inspected for solenoids, but beware that these do often fail (which could be why the machine was thrown out!) or be gummed up with grime and scale from years of use. £5 for a nice shiny solenoid valve seemed like a good decision to me. Whatever valve you choose to use, please be sure that it is "normally closed". This means that when power is removed from the device it will naturally clamp shut. While the system can be set up to work with a "normally open" valve (trivial changes to either the circuit, or the code) this would mean that a power failure to the house will turn on the garden sprinkler and could lead to a massive waste of water and/or a terribly large water bill!!!

More problematic than finding the valve was finding the fittings to attach it to the tap. My motivation is to make a really solid connection so there was no chance that the device could leak. As you can see in the photo the solenoid has 1/2" BSP threads at each end. The plastic adapter to 3/4" female came with the HoseLoc fitting. The metal female to female union allows the 1/2" male solenoid thread to mate with the 3/4" male thread on the tap. It took me some time to identify the correct parts and sizes, but once I had done this the union only cost £3.50 from a hydraulics supply company. Lots of Teflon tape was required to provide a leak free join, this is the difference between BSPP and BSPT, the BSPT threads seal up as they come together, while BSP requires an O-ring (as the HoseLoc fitting sports) or Teflon thread or paste.

Linking It All Together

Activating GPIO Pins

The Raspberry Pi has a number of GPIO pins that can be triggered from software. There are a number of ways to do this, but by far the easiest is to use the Python library supplied for this task.

What is Python?

Python is an interpreted scripting language with a straight-forward functional syntax. It can be launched from the command line using the command "python" followed by the filename of the script. The extension *.py is typically used for python files. If you wish to execute a script directly then you must add the "shebang" line to the top of the script file. This tells linux where the Python program is, and allows it to then run the script. On Debian systems Python is in the location shown. Because the shebang line starts with a # character it is seen as a comment line. This means that the script can also be run in the usual way. One final detail. For the script file to be executed in this way it must have its "excutable bit" set. This is achieved by typing the following command:

chmod +x

So, to recap, if your scripts have the shebang then they can be executed with either:


// or...


I wrote a simple script for testing your control circuit and to verify that everything is working. It can be downloaded here and is shown below:

#!/usr/bin/env python

# import libraries
import RPi.GPIO as GPIO
import time

# use Pi board pin numbers

# configure the pin for output
GPIO.setup(12, GPIO.OUT)

# P1_12 == 12 == GPIO1 == GPIO18
# How did they mess up the pin numbering so badly!!

# create a loop

while 1 : #infinite loop
print "Set Pin 12(GPIO18) High"
GPIO.output(12, GPIO.HIGH)
print "Set Pin 12(GPIO18) Low"
GPIO.output(12, GPIO.LOW)

It is a simple task to modify this to our final version, which can be downloaded here and is shown below:

#!/usr/bin/env python

# import libraries
import RPi.GPIO as GPIO
import time


# use Pi board pin numbers

# configure the pin for output
GPIO.setup(12, GPIO.OUT)

# P1_12 == 12 == GPIO1 == GPIO18
# How did they mess up the pin numbering so badly!!

# Turn on the sprinkler for 30 seconds
# the motion program has a 60 seconds "cooldown"

GPIO.output(12, GPIO.HIGH)
GPIO.output(12, GPIO.LOW)

The script works by turning the GPIO pin high, waiting for 30 seconds, then turning the pin low. The idea is that this will activate the sprinkler for 30 seconds, enough to scare the cat away. Now all we need is to trigger this script from Motion.

Triggering From Motion

The program Motion works by capturing frames from the camera and comparing them to detect movement events. Once an event is detected any number of actions can be triggered, with the primary actions of saving frames and saving video being handled by the program itself. But it is also possible to launch an external command, and it is this feature that we will leverage to activate the Pi's GPIO pin.

To configure Motion for this role, look to the section of the config file regarding triggering. All that is required is for you to enter the path to the script that was created earlier. Notice that we are using the executable form to run this script. To be honest I am not 100% sure if Motion supports parameters (when calling "python" the name of the script is the parameter) so to be safe I am making the scripts executable and just using the script name.

Finally, we do not want Motion to launch the script multiple times. To prevent this we set the event timeout/repeat to an appropriate value. I am using 60 seconds for my setup. So basically, if a cat walks into view the script will be executed, the sprinkler will come on for 30 seconds, and then there is a 30 second cooling off period before the script can fire again. You can modify all of these timings to suit your own preferences.


The device has been great fun to build and has worked really well, as the following compilation video shows.

A compilation of cats, but CATTACK gets one at the end!! MPEG-4 [AVI 5.8MB]

If you watch the video then you'll notice that towards the end the garden has grown up tall and the device triggers whenever it is windy! Read on for some suggestions for how to deal with this...

Making It Better

If you have read this far then I am sure you are already imagining how to make this project yourself and what you would do differently. That's great, and is mostly why I have taken the time to document this project, it's a great launch pad for many other adventurous Pi projects!

Here are some of my own ideas as to how I would take it further:

  1. Use a better camera so that the system can work as a security system, or to view wildlife. Try with a night vision system for 24-hour cat protection, or just to see hedgehogs and foxes (or possums, raccoons and bandicoots, depending on where you live) going about their business at night.

  2. Provide a web interface that allows for remote control of the valve. This would allow a gardener to turn on their sprinklers while on holiday or at work.

  3. Or, provide a timer system that allows for automated watering. Bonus points for tallying the time that cats trigger the sprinkler and deducting that from the automated time.

  4. Explore all of Motion's options to avoid false alarms due to moving shrubbery, or, add an anemometer gauge of some description and disable the device when it is too windy.

  5. Move beyond the motion detection program Motion and write your own movement detection software. An exciting possibility here is to use a clever algorithm to tell the difference between humans and cats and save you having to turn it off whenever you wish to use the garden. Even better would be cat identification (perhaps based on size, shape, colour, or distinctive markings) so that your own cat may roam with impunity :)


This project was undertaken by Ashley Norris in his spare time. All of the ideas and materials presented here are released under a creative commons license for educational purposes. Students, teachers, and enthusiasts are encouraged to take this material, do what they wish with it, and re-release their own works in a like-minded way.

Feedback, comments, and criticism are all welcome, please email me.

ashley @ norris . org . au

Anti-spam: sorry, you'll have to manually remove the spaces from my email address to make it go.

Creative Commons License
Cat-Wrangler: CATTACK! by Ashley Norris is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.