Connecting a Motion Sensor to a Raspberry Pi

This article provides a straightforward guide on how to connect a PIR (Passive Infrared) motion sensor to a Raspberry Pi to build a basic DIY security system. You will learn about the necessary hardware components, how to wire the sensor to the Pi’s GPIO pins, and how to write a simple Python script to detect movement and trigger an alert.

Required Hardware Components

To get started on this project, you will need a few basic electronic components:

Understanding the PIR Motion Sensor Pinout

The HC-SR501 PIR sensor typically has three pins hidden beneath its plastic fresnel lens. You will need to look closely at the board’s markings (often found under the cap) to identify them correctly:

Wiring the Sensor to the Raspberry Pi

Before connecting any wires, ensure that your Raspberry Pi is powered off and unplugged to prevent accidental short circuits. Use the jumper wires to connect the sensor to the Pi’s GPIO (General Purpose Input/Output) header based on the following configuration:

Writing the Python Detection Script

Once the hardware is securely connected, power on your Raspberry Pi. Open a terminal or your favorite Python IDE (such as Thonny) and create a new script named security_system.py.

The following script utilizes the gpiozero library, which is pre-installed on Raspberry Pi OS and makes interacting with hardware incredibly simple.

from gpiozero import MotionSensor
from signal import pause
import time

# Define the GPIO pin connected to the sensor's OUT pin
# Pin 11 corresponds to GPIO 17
pir = MotionSensor(17)

def motion_detected():
    print(f"Alert! Motion detected at {time.strftime('%H:%M:%S')}")

def motion_stopped():
    print("Area is clear.")

# Assign the functions to the sensor events
pir.when_motion = motion_detected
pir.when_no_motion = motion_stopped

print("Security system active. Waiting for movement...")

# Keep the program running to listen for events
pause()

Testing and Calibrating the System

Run the Python script in your terminal. Wave your hand in front of the PIR sensor, and you should see the alert message print to the screen.

If the sensor is too sensitive or stays triggered for too long, you can adjust the two potentiometers (orange knobs) located on the side of the HC-SR501 circuit board: