Knowledge for the World

How to set up a PIR motion sensor on the Raspberry Pi

What is a Raspberry Pi without a motion sensor? Kids can now sound the alarm if their parents are coming down the hall. Homeowners can turn on the lights or take a picture when someone comes to the front door. Or, if you're me, you can create a bird feeder that tweets pictures of birds as they come to eat.

In these interests [?]
  • diy
    52 Subscribers Subscribe
  • pi
    82 Subscribers Subscribe

Connect the jumper cables to the motion sensor

There should be three pins on the motion sensor. Before connecting the jumper cables, we need to look at the labels on the pins. One pin should say VCC or 5V, one should say GND, and one should say OUT. Make sure to identify these pins.

Connect a jumper cable to each pin. If possible, use a different color for each cable. I'm using black (GND), gray (5V), and white (OUT).

Connect the jumper cables to the motion sensor

Connect the jumper cables to the pi

Using the diagram found here or the image below, connect the jumper cables to the appropriate pins.

The 5V (gray) is attach to a 5V pin, the GND (black) is attached to a GND pin, and the OUT (white) is connected to the GP4 pin. It's important that you use the GP4 pin since that's what we'll use in our script in the following step.

Connect the jumper cables to the pi

Test it out

To test out the motion sensor, we'll create a simple Python script. SSH into your pi, and create and edit a script in your home directory called


Add the following:

import time

from gpiozero import MotionSensor

pir = MotionSensor(4)

while True:
    if pir.motion_detected:
        print('Motion detected')

This program prints 'Motion detected' when PIR sensor is tripped. Then we'll sleep for 10 seconds before checking again.

It relies on the gpiozero module so you'll have to install that if you haven't already. Via pip:

pip install gpiozero

Then to run the program:


Then wave your hand in front the motion sensor. You should see 'Motion detected' printed to the screen. Hit ctrl-c to stop the script.