PIR motion sensor connected with red, yellow and black wires to a Raspberry Pi fitted with a red prototyping board carrying radio modules

Raspberry Pi PIR Motion Sensor – Read and React with Python

A passive infrared (PIR) sensor detects movement without a camera and draws almost no power. Here, it switches your monitor on when someone walks into the room and off again when they leave, which is ideal for an info display or a wall-mounted screen. You need Raspberry Pi OS with desktop, since Lite has no desktop session for this to run in. The often-quoted vcgencmd display_power command no longer works on the current desktop, so this guide uses wlopm instead.

In short

On current Raspberry Pi OS with desktop, wlopm turns the monitor off and on, and a short gpiozero script ties it to the PIR sensor.

  • vcgencmd display_power and xrandr no longer work in the default desktop session (Wayland).
  • The script starts from the autostart file of labwc, the Wayland compositor behind the desktop, not as a systemd service.
  • Turn off screen blanking and turn on automatic login.
Two PIR motion sensor modules: one from the front with its white lens, the other flipped to show the circuit board with a jumper and two potentiometers
The PIR sensor from the front with its white lens, and from the back with the jumper and both potentiometers.

What you’ll need

Links marked with * are affiliate links, which makes them advertising. If you buy through one, I earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. Learn more

PIR sensor settings

  • The SW1 jumper sets how the sensor triggers. The letters L and H are printed next to it on the board:
    • L (single trigger): after motion, the output goes high for the set hold time and then drops, even if the motion continues.
    • H (repeat trigger): every new movement restarts the hold time, so the output stays high as long as someone keeps moving.
  • The Time potentiometer sets how long the output stays high after motion. Turn it clockwise for a longer hold time.
  • The Sensitive potentiometer sets the detection range. Turn it clockwise to pick up movement from further away.
  • Range: about 3 to 7 meters (10 to 23 ft), depending on the setting and the module. The datasheet gives a detection angle of just under 100 degrees.

We’d start with the jumper on H, Time turned fully counterclockwise (shortest hold time) and Sensitive in the middle. Point the sensor at the area where people move, not at radiators, lamps or drafty windows.

Back of the PIR module: jumper SW1 on the left, next to it the orange Time and Sensitive potentiometers
The back of the module: jumper SW1 (left) and the Time and Sensitive potentiometers.

Wiring

The sensor has three pins: VCC (5 V), OUT and GND. The order varies between modules, so check the labels printed on the board. On the Pi 2 through Pi 5, the even-numbered pins are in the outer row along the board edge. Pins 1 and 2 are at the end facing away from the USB ports, and pin 7 is the fourth pin in the inner row. Turn the Pi off before you wire it up.

  • VCC → 5 V → pin 2
  • OUT → data output (3.3 V) → pin 7 (GPIO 4)
  • GND → ground → pin 6
Wiring diagram: PIR sensor on a Raspberry Pi, red wire to pin 2, black to pin 6, yellow to pin 7
Red: 5 V (pin 2), black: GND (pin 6), yellow: GPIO 4 (pin 7).

Testing the sensor with gpiozero

The simplest way to read the PIR sensor from Python is the gpiozero library, which comes preinstalled on Raspberry Pi OS.

Your username: Raspberry Pi OS hasn’t had a default pi account since 2022. You choose the username during setup, usually in Raspberry Pi Imager. That’s why the commands here use ~, which points to your home folder, /home/<your-name>.

Create a new Python file:

nano ~/motion_gpiozero.py
#!/usr/bin/env python3

from gpiozero import MotionSensor
from datetime import datetime
import time

# PIR sensor on board pin 7 (GPIO 4)
pir = MotionSensor(4)

print("Motion sensor test with gpiozero (Ctrl+C to quit)")
print("===================================================")
print(f"{datetime.now()}: Initializing sensor ...")

# Wait until the sensor is ready
pir.wait_for_no_motion()
print(f"{datetime.now()}: Ready! Waiting for motion...")

try:
    while True:
        pir.wait_for_motion()
        print(f"{datetime.now()}: Motion detected!")
        pir.wait_for_no_motion()
        print(f"{datetime.now()}: No more motion.")

except KeyboardInterrupt:
    print("Stopped.")

Save with Ctrl+X, then Y and Enter, and run the script:

python3 ~/motion_gpiozero.py

When you move in front of the sensor, the terminal prints “Motion detected!” and “No more motion.”, each with a timestamp. After you connect the sensor, it needs about a minute to settle, and during that time it may trigger without any motion.

Terminal output of the motion sensor test: timestamped lines with the German message “Bewegung erkannt!” (motion detected)
Output of the test script (this older screenshot shows the German wording).

Switching the monitor on and off with motion

Older guides use vcgencmd display_power 0 or xrandr for this. Neither works in the default desktop session of current Raspberry Pi OS, which uses Wayland (the newer display system) instead of X11, and on a Pi 5 vcgencmd display_power just replies with “Command not registered”. wlopm takes their place and comes preinstalled with the desktop.

To check that your desktop runs on Wayland, run echo $WAYLAND_DISPLAY in a terminal on the Pi. If it prints something like wayland-0, the desktop runs on labwc under Wayland. An empty output means X11: switch over in sudo raspi-config under 6 Advanced Options → A7 Wayland → W2 Labwc and reboot.

Switching the monitor by hand

Try the commands first, in a terminal on the Pi’s desktop:

# Show the current state, e.g. "HDMI-A-1 on"
wlopm

# Turn the monitor off and back on after 5 seconds
wlopm --off '*'; sleep 5; wlopm --on '*'

On their own, wlopm --off '*' turns the monitor off and wlopm --on '*' turns it back on. The asterisk stands for every connected monitor, and the quotes stop the shell from treating it as a filename wildcard. After --off the monitor shows “No signal” or goes into standby, and after --on the picture comes back within a few seconds.

Over SSH, wlopm can’t reach the desktop session and fails with “WAYLAND_DISPLAY is not set”. First find the session’s name: run ls /run/user/$(id -u)/ and look for the wayland-… entry that doesn’t end in .lock (on our Pi 5 it was wayland-0). Then point wlopm at it with two environment variables:

WAYLAND_DISPLAY=wayland-0 XDG_RUNTIME_DIR=/run/user/$(id -u) wlopm --off '*'

The monitor script

Once switching by hand works, create the monitor script:

nano ~/monitor_pir.py
#!/usr/bin/env python3

from gpiozero import MotionSensor
from datetime import datetime
import subprocess
import time

# 4 is the GPIO number; the sensor is on pin 7
pir = MotionSensor(4)

def monitor_on():
    subprocess.run(["wlopm", "--on", "*"])
    print(f"{datetime.now()}: Monitor ON")

def monitor_off():
    subprocess.run(["wlopm", "--off", "*"])
    print(f"{datetime.now()}: Monitor OFF")

print("PIR monitor control started (Ctrl+C to quit)")

# Wait until the system has fully booted
time.sleep(10)

# Initialize the sensor
pir.wait_for_no_motion()
print(f"{datetime.now()}: Sensor ready.")

try:
    while True:
        pir.wait_for_motion()
        monitor_on()
        pir.wait_for_no_motion()
        # Wait 30 seconds before turning the monitor off
        time.sleep(30)
        if not pir.motion_detected:
            monitor_off()

except KeyboardInterrupt:
    print("Stopped.")

Save the file as before, then run it by hand in a terminal on the Pi’s desktop and move in front of the sensor:

python3 ~/monitor_pir.py

After a little over ten seconds the script prints “Sensor ready”. With a freshly connected sensor this can take up to a minute longer. After the last movement the script waits 30 seconds, plus the hold time set on the Time potentiometer, and switches the monitor off if nobody is detected. To change the delay, edit time.sleep(30).

Right after startup the monitor stays on even if nobody is there. The script only turns it off after the sensor has registered motion once and gone quiet again.

Turning off screen blanking

The built-in screen blanking in Raspberry Pi OS turns the monitor off after ten minutes without mouse or keyboard input, even if someone is in the room. To disable it, run sudo raspi-config, go to 2 Display Options → D2 Screen Blanking and answer No to “Would you like to enable screen blanking?”. The change applies after the reboot in the next section.

Starting the script automatically

To keep this working after a reboot, the script has to start with the desktop session. A regular systemd service starts outside that session, so wlopm fails with the same error as over SSH.

Use the desktop’s autostart instead. Raspberry Pi OS uses labwc, a Wayland compositor, which runs the file ~/.config/labwc/autostart at every login. Create the folder if it’s missing, then open the file:

mkdir -p ~/.config/labwc
nano ~/.config/labwc/autostart

If you’re creating the file from scratch, don’t worry: labwc also runs the system’s own autostart file, so the panel and file manager still start as usual. Add this line at the end, below any existing lines:

python3 -u ~/monitor_pir.py >> ~/pir_monitor.log 2>&1 &

The & at the end runs the script in the background so the desktop doesn’t wait for it. The -u flag writes output to pir_monitor.log immediately instead of buffering it.

Turn on automatic login. A display with no keyboard needs to log in on its own. Run sudo raspi-config and go to 1 System Options → S6 Auto Login. Answer No to the first question (console) and Yes to the second (desktop).

Reboot the Pi and check that the script is running:

sudo reboot
pgrep -af monitor_pir
tail -f ~/pir_monitor.log

pgrep should list a line with python3 -u /home/…/monitor_pir.py, and the log shows “Sensor ready”. Press Ctrl+C to leave tail -f. To stop the script itself, for example before you edit it and test it by hand again, run pkill -f monitor_pir.py. To remove the PIR switching for good, delete that line from the autostart file.

If it doesn’t work

  • The test script hangs at “Initializing sensor …”. The sensor keeps reporting motion. Give it the minute it needs to settle after you connect it. If that doesn’t help, see “The monitor doesn’t turn off”.
  • Nothing happens when you move. Check the wiring, especially that OUT goes to pin 7 and VCC to 5 V (pin 2).
  • pgrep shows nothing after the reboot. Check ~/pir_monitor.log for the script’s error message. If the log is empty, check the line in ~/.config/labwc/autostart and make sure automatic login is on. A script that has crashed won’t start again until the next reboot or login.
  • The log says “WAYLAND_DISPLAY is not set”. The script was started outside the desktop session, for example over SSH or as a systemd service. Always start it from the autostart file.
  • pgrep shows two lines. If you set the script up as a systemd service following an older guide, for example as pir-monitor.service, disable that service with sudo systemctl disable --now pir-monitor.service. If a manual test is still running in a terminal, stop it with Ctrl+C.
  • The monitor doesn’t turn off. Try wlopm --off '*' by hand. If that works, the sensor is probably still reporting motion. Shorten the hold time with the Time potentiometer, turn down the Sensitive potentiometer and check where the sensor is pointing (see “PIR sensor settings”).
  • The monitor doesn’t come back on. Run wlopm --on '*' by hand and check with wlopm that the output shows on. If it does and the screen stays black, use the monitor’s own menu to check that the right HDMI input is selected.
  • The monitor turns off after ten minutes even though someone is there. Screen blanking is still on. See “Turning off screen blanking” above.

Optional: testing with RPi.GPIO

You only need this if you’re adapting a project that uses RPi.GPIO. Raspberry Pi OS includes rpi-lgpio, a compatible version of RPi.GPIO that works on the Pi 5. It doesn’t run on the original Pi 1 (models A, A+, B and B+).

nano ~/motion_rpigio.py
#!/usr/bin/env python3

import RPi.GPIO as GPIO
import time
from datetime import datetime

# Board mode: pin numbers instead of BCM numbers
GPIO.setmode(GPIO.BOARD)

# PIR sensor on pin 7
GPIO_PIR = 7
GPIO.setup(GPIO_PIR, GPIO.IN)

Current_State = 0
Previous_State = 0

print("Motion sensor test with RPi.GPIO (Ctrl+C to quit)")
print("==================================================")

try:
    print(f"{datetime.now()}: Initializing sensor ...")

    # Wait until the sensor is ready
    while GPIO.input(GPIO_PIR) == 1:
        time.sleep(0.1)

    print(f"{datetime.now()}: Ready! Waiting for motion...")

    while True:
        Current_State = GPIO.input(GPIO_PIR)

        if Current_State == 1 and Previous_State == 0:
            print(f"{datetime.now()}: Motion detected!")
            Previous_State = 1

        elif Current_State == 0 and Previous_State == 1:
            print(f"{datetime.now()}: No more motion.")
            Previous_State = 0

        time.sleep(0.01)

except KeyboardInterrupt:
    print("Stopped.")
    GPIO.cleanup()

Save with Ctrl+X, then Y and Enter, and run it:

python3 ~/motion_rpigio.py
PIR motion sensor connected with red, yellow and black wires to a Raspberry Pi fitted with a red prototyping board carrying radio modules
The PIR sensor in use on a Raspberry Pi that also carries a prototyping board with radio modules.

Similar Posts