Chapter 3
Pi Motion Detection

In this chapter, we will be discussing how to turn your Raspberry Pi into a motion-detecting surveillance system. This is simpler to accomplish than it sounds, since the software we need is ready in a downloadable package for the Pi. Once it’s installed, we can dive right into operating and fine-tuning the program.
As with the previous project, we’ll be working mostly from within the terminal, though this chapter will cover how to view the program’s output with the GUI. We will be using the nano editor to help customize our program to suit our needs.
Motion detection allows for more selective and sophisticated image capturing than just taking a photo every 10 seconds. Now you can set up a wildlife camera that takes routine snapshots and automatically records video whenever an animal walks by. We’ll also show you how to set up filters so you can quickly find who’s been knocking on your front door without having to look through scores of images with the same view of your welcome mat. Last but not least, you can connect your motion-detection system to the Internet and watch what it sees wherever you are!
What Is Motion Detection?
Motion detection, in essence, is the search for changes in an environment caused by an object moving. A program does this by comparing two sets of input data about the environment and deciding whether there is a significant difference between them. In this chapter, we will compare literal images to try to detect whenever something has moved.
It’s important to understand how one image is compared to the last taken. Essentially, the program counts how many pixels have changed since the last image. With this in mind, we must set a threshold for the differences to be reported. If the threshold is set at a low percentage of changed pixels, then the system will flag minor events like branches or papers rustling in a breeze as movement. If the threshold is set higher, it will take a more drastic change to count as movement.

Figure 3-1: Environment before movement

Figure 3-2: Environment after movement
But not all changes to an image are caused by movement. Suppose your camera is looking at a deserted street at twilight. At the appropriate moment, the street lights will flicker to life. The scene will change drastically—formerly dark shadows will become warm pools of light. But does this count as movement?
This is where sensitivity comes in. Sensitivity refers to certain parameters designed to help reduce the number of false positives reported by the system. If sensitivity is not taken into consideration, the system will report any time there’s any significant change between images. This is fine when someone walks in or out of a room—but not when the light in the room is turned off. We can screen out such events by including a contrast setting with the camera.
Hardware
This chapter uses the same hardware listed in Chapter 1.
Set Up Motion Detection
You will need to download the software needed for motion detection. If you didn’t do so in Chapter 1, enter this command:
sudo apt-get install motion
While the packages are downloading, a prompt will come up asking if you wish to continue with the installation. Just press Y and then Enter to finish the download.
Testing motion with GUI
The motion
package is fairly ready to use once it’s
installed. The easiest way to test whether the program is
operational is to work using the Raspberry GUI. To get the package
running, first enter the command:
sudo motion
This command will start motion
and have it record
images. To view what your camera is seeing, open the Pi’s web
browser and type in the address http://localhost:8081
. This will establish a
connection to motion
and display its images in the
browser.

Figure 3-3: Streaming
motion
from localhost
When you first connect to the service, don’t be alarmed if the
images are small or the frame rate seems slow. These are the
default settings assigned to motion
. We’ll go over how
to reconfigure the service in the next section.
Testing motion with the Command Line
If you are only using the command line, testing
motion
isn’t too complicated. The first thing you need
to do is start motion
:
sudo motion
Now,
because you don’t have the web browser to watch the live feed from
the camera, let the program run for a few seconds before signaling
it to stop. After running motion
for about 30 seconds,
enter the following to kill the program:
sudo service motion stop
Once motion
is stopped, you can then try to look up
the images it took while it was running. By default,
motion
should save its images to the current working
directory. To check, type the following:
ls
Once you execute this command, you should see a list of JPEG
files. Most are named with a time code followed by the word
snapshot
. These are the snapshot images that
motion
takes at a set rate to look for changes. There
should also be an image named lastsnap.jpg
. This is
the latest image taken by motion
and is updated each
time motion
captures a new photo. It is also what you
see when viewing motion
in the browser.
The point of this test is to make sure motion
is
running as it should in its default state. If the program is
displaying what it sees in the browser and it is writing files as
described, then that means motion
is running fine.
This test also acts as a quick introduction into how to operate the
program. You’re ready to move to the next step!
Customizing motion
We mentioned earlier that it is possible to customize the
settings in motion
in order to have the program suit
your needs. Fortunately, almost all these changes can be made and
applied in a single file: motion.conf
.
To access motion.conf
, open the file using
nano:
sudo nano /etc/motion/motion.conf

Figure 3-4:
motion.conf
opened in nano
The configuration file for motion
is lengthy to say
the least, but don’t be daunted. The different settings are
documented and explained within the file, and if you need
additional information, you can find plenty of online
resources.
One of the perks of using nano to look at the file is that you can search for keywords by pressing Ctrl-W. This makes navigating the file and finding specific settings much easier than having to scroll down through the various configurations.
Let’s focus on some of the more basic options available.
A
good place to start in motion.conf
is the
height
and width
values. As you saw, the
default image in the browser is a bit on the small side. That’s
because the default values of height
and
width
are 240 and 320 pixels, respectively. If you
want to view a larger image, you simply need to replace those
values with larger numbers.
For practice, let’s double height
and
width
. Find those lines in the file and edit them to
say
width 640
height 480
Once you’ve specified the new dimensions, exit the file to test
them. To save the changes you made, press Ctrl-X followed by Y, and
then press Enter to reach the command line. Run motion
as you did in the previous section and see whether the image is
larger.
If the image in the browser is the same as before, you may need to reboot the Pi to have the new settings take effect. To initiate a reboot, at the command line type
sudo reboot
Once the Pi is rebooted and you are logged back in, you should
be able to start motion
and see the changes.
One other value we should look at is threshold
. The
threshold
value determines how many pixels need to
have changed between two snapshots to trigger an event. By
default, threshold
is set to trigger if 1,500 pixels
have been changed.
Now recall what we said about the main principles of motion
detection at the beginning of this chapter. Although 1,500 may
sound like a high number, that is 1,500 pixels out of the
entire image. Using the default settings in
motion
, let’s calculate what percentage 1,500 is of a
240×320 image:
240 × 320 = 76,800
1,500 / 76,800 = 0.02
Using the default settings, motion
triggers an
event whenever there is a 2 percent difference between photos. That
is far too sensitive! With a threshold that low, an event could be
triggered by a fly buzzing by the camera. The sensitivity is
increased even more for a 480 × 640 image: 1,500 pixels represents
a threshold of 0.5 percent.
To make motion
less sensitive and to help avoid
drowning in false alarms, let’s increase threshold
.
You can set threshold
to whatever you want, but for
the sake of this project, shoot to make it a manageable 25 percent.
To find the correct number, simply do the following calculations
with your doubled dimensions:
480 × 640 = 307,200
0.25 × 307,200 = 76,800
Now that you know how many pixels equal a quarter of the image,
you can plug that number in the configuration file for
motion
:
sudo nano /etc/motion/motion.conf
Find threshold
and edit the line to say
threshold 76800
Now
motion
will trigger an event when you wave your hand
in front of the camera—but not when a bug flies around on the other
side of the room.
The rest of the configuration settings for motion are certainly worth checking out and experimenting with, though doing so would be a bit outside the scope of this book. If you’re interested in learning about the various settings, you can find a good reference here: www.lavrsen.dk/foswiki/bin/view/Motion/ConfigFileOptions.
Streaming motion Remotely
Viewing motion
remotely operates much like viewing
it locally on the Pi. Once it’s set up, you can stream what
motion
sees from any web-enabled device, be it a
phone, a laptop, or even another Pi. Before you can do this,
however, there are a few things you’ll need.
First of all, you must enable remote streaming with
motion
. Start by opening motion.conf
:
sudo nano /etc/motion/motion.conf
Once the configuration file is open, find the
stream_localhost
line. This value determines whether
or not motion
allows remote streaming. To enable
streaming, change it to read
stream_localhost off
With streaming now enabled, you just need to find the Pi’s IP address so that you can connect to it. This is easy to do by typing the following at the command line:
hostname -I
The
output the command gives is the IP address of the Pi. Armed with
this knowledge, you can now stream motion
from a
remote device. Making sure that the Pi is connected to the
Internet, open the web browser on your device and type the Pi’s IP
address in the address bar, followed by the port number
8081
. The bar should resemble the
following:
http://192.165.76.3:8081
Start motion
:
sudo motion
Enter the IP address and your browser should look just as it did
when you viewed motion
locally on the Pi.
Going Headless
Streaming motion
headlessly—that is, without
connecting the Pi to a monitor or keyboard—is simple enough to do.
You know how to watch the stream from motion
remotely
at this point, which is half the battle. The other half is getting
motion
to run while the Pi is headless.
There are two ways to accomplish this. The first is to connect
to the Pi from a remote computer via SSH and tell
motion
to run.
The other way is to have motion
run automatically
when the Pi powers up. One of the best ways to do this is by using
crontab
. The crontab
(short for cron
table) file is used for scheduling different commands and programs
so that they run automatically without the system administrator
having to enter the same command every day.
To use crontab
, first open the file for
editing:
sudo crontab -e

Figure 3-5: Selecting an editor for
crontab
When you first open crontab
, the system will ask
you which text editor you wish to use. At the prompt, select nano
by typing 2
and pressing Enter. The
crontab
file should then open in the command
window.
Since you want to run motion
at startup and not at
any specific time, we will ignore the traditional scheduling
format. Instead, scroll to the bottom of the file and enter the
following:
@reboot motion
Now motion
will run every time you boot up your Pi.
Save your edit and exit the file.
To test and make sure the changes you made work, reboot your Pi:
sudo reboot
Then try to stream motion
via the
web browser. If everything is operational, you should see the feed
from motion
in the window without having to start the
program manually.