Build a Motion Detection System with a Raspberry Pi

This project shows how to build a motion detection system with a Raspberry Pi. It may be used as a burglar detector, to take photos of wildlife applications, and for other purposes. We'll be using a Raspberry Pi V2 camera, and the code will be written in Python.

Note: This project is taken from the book “20 Easy Raspberry Pi Projects.” We recommend reading our Raspberry Pi Projects book if you wish to construct electronics projects with the Raspberry Pi using Python.

Prerequisites

Parts Required

Project Overview

This project's circuit consists of a PIR motion sensor, a pushbutton, and a camera module that you'll attach to your Raspberry Pi. You may halt the Python script using the pushbutton, which is an additional component.

motion detector with photo capture

We'll use a Python script and the Raspberry Pi's built-in Picamera library to program the device, making controlling the camera quite simple. We'll use the gpiozero library to control the GPIOs, which have classes for the most popular component types like pushbuttons, LEDs, motion sensors, etc.

Enable the Camera

Before using the camera module, you must activate Raspberry Pi's camera software. Go to the main menu in the desktop environment, then select Preferences > Raspberry Pi Configuration. The window shown below should appear after selecting the Interfaces tab.

Raspberry Pi Configuration

Alternatively, in the Terminal window, type the following command:

pi@raspberry:~ $ sudo raspi-config

You should see the Raspberry Pi software configuration tool. Select the Interfacing Options:

Interfacing options

Enable the camera and reboot your Pi:

enable camera raspi config

Connect the Camera

Shut down your Pi, and then connect the camera to the CSI port while the camera software is activated. As shown in the accompanying image, make sure the camera is connected and oriented with the blue letters facing up. Start up your Pi once again.

connect camera

Build the Circuit

With the camera connected, follow the next schematic diagram to wire the rest of the circuit.

pir motion sensor with raspberry pi
  • Pushbutton: GPIO 2
  • PIR motion sensor: GPIO 4

Note: In this project, the PIR motion sensor that we are using must be powered by the 5V pin. Other sensors required 3.3V to function. Before wiring the circuit, review the specifications for the sensor.

Writing the Script

Using the built-in Picamera library, you can control the camera. An overview of what the code should do is given below:

  1. Initialize the camera.
  2. Take a photo when the PIR motion sensor detects movement.
  3. Save the photos in your Desktop folder.
  4. Name the photos incrementally so you know what order they were taken in—for example, image_1.jpgimage_2.jpg, and so on.
  5. Stop the camera when the pushbutton is pressed. If you don’t include this feature, you won’t be able to exit the camera preview that pops up on your screen.

Entering the script

Create a new file using Python 3 (IDLE) and copy the following code. Then, save the code in the Desktop folder with the following name: burglar_detector.py.

#Project 13 - Burglar Detector With Photo Capture
#latest code updates available at: https://github.com/RuiSantosdotme/RaspberryPiProject
#project updates at: https://nostarch.com/RaspberryPiProject

#import the necessary packages
from gpiozero import Button, MotionSensor
from picamera import PiCamera
from time import sleep
from signal import pause

#create objects that refer to a button,
#a motion sensor and the PiCamera
button = Button(2)
pir = MotionSensor(4)
camera = PiCamera()

#start the camera
camera.rotation = 180
camera.start_preview()

#image image names
i = 0

#stop the camera when the pushbutton is pressed
def stop_camera():
    camera.stop_preview()
    #exit the program
    exit()

#take photo when motion is detected
def take_photo():
    global i
    i = i + 1
    camera.capture('/home/pi/Desktop/image_%s.jpg' % i)
    print('A photo has been taken')
    sleep(10)

#assign a function that runs when the button is pressed
button.when_pressed = stop_camera
#assign a function that runs when motion is detected
pir.when_motion = take_photo

pause()

How the code works

Because the program uses the picamera library to control the camera, you must first import the necessary libraries. The classes Button and MotionSensor in the gpiozero library are used to control the pushbutton and the motion sensor. We may deal with delays using the sleep method, whereas interrupts are dealt with using the pause method.

from gpiozero import Button, MotionSensor
from picamera import PiCamera
from time import sleep
from signal import pause

The pushbutton, PIR motion sensor, and camera are then references in the objects that you create. The motion sensor is on GPIO 4, whereas the pushbutton is connected to GPIO 2.

button = Button(2)
pir = MotionSensor(4)
camera = PiCamera()

Then, initialize the camera with camera.start_preview().

camera.start_preview()

Depending on how your camera is set up, you may also need to rotate it 180 degrees to prevent the photos from being taken upside down.

camera.rotation = 180

Next, you initialize a i variable that starts at 0.

i = 0

Then, we create the stop_camera() and the take_photo() functions that will be called later in the code.

The take_photo() function, will use the i variable to count and number the images, incrementing the number in the filename by one with each picture taken.

def take_photo():
  global i
  i = i + 1
  camera.capture('/home/pi/Desktop/image_%s.jpg' % i)
  print('A photo has been taken')
  sleep(10)

Specifying the directory you wish to save the image to within the brackets, you use the camera.capture() function to take and save a picture. In this instance, we are saving the images to the Desktop folder and naming them image_%s.jpg, where %s is replaced with the number we increased previously in i.

Replace this directory with the path to your preferred folder if you wish to save your files somewhere else. As long as the PIR sensor detects movement, you then impose a 10-second delay, which causes the camera to take pictures every 10 seconds. Feel free to change the delay time, but be cautious not to overload the Pi with tonnes of images by setting it too short.

The stop_camera() function stops the camera with the camera.stop_preview() method.

def stop_camera():
  camera.stop_preview()
  #exit the program
  exit()

This function exits the program and stops the camera preview. To close the program, just click “OK” in the window that pops up when the exit() function is used.

Finally, you define that when the pushbutton is pressed, the camera stops.

button.when_pressed = stop_camera

Finally, you tell the camera to take a photo by triggering the take_photo() function when motion is detected.

pir.when_motion = take_photo

The pause() at the end of the code keeps your program running so that interrupts can be detected.

Demonstration

Press F5 or choose Run > Run Module to run the script if you're using Python IDLE to write your code. You ought to get a preview of what the camera sees on your screen when the script is executing. Press the pushbutton, then click OK in the window that pops up to shut off the camera preview.

Alternatively, in the Terminal window you can type:

pi@raspberrypi:~ $ python3 burglar_detector.py

Congratulations! Your project is ready to detect motion and take some photos. You may place this project in a strategic place and return later to see any saved photos. The next figure shows a photo taken by this project.

motion detector with photo burglar

Conclusion

An easy task that can be applied to a wide variety of projects is using cameras with the Raspberry Pi. An easy way to operate the camera and GPIOs with the Raspberry Pi is to use the picamera and gpiozero libraries.

If you like Raspberry Pi, you may also like:

We hope you find this tutorial useful. Thanks for reading.

Oh hi there It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Read our privacy policy for more info.

Leave a Reply

Your email address will not be published. Required fields are marked *

20 Easy Raspberry Pi Projects Toys, Tools, Gadgets

20 projects using the Raspberry Pi, a tiny and affordable computer, for beginners looking to make cool things, Projects are explained with full-color visuals and simple step-by-step instructions.