PIR motion sensor with gpiozero on a Raspberry Pi 4
gpiozero MotionSensor on a Raspberry Pi 4: an HC-SR501 PIR on GPIO4 lights an LED on GPIO17 while something moves, and counts each movement. The whole build, a Raspberry Pi 4 and 3 more parts, runs here in your browser on the Python below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $60. On Mokxi they're free.
The code
The Python exactly as the editor opens it. Change a line there and press Run: the board runs main.py in a Python engine in the page, with gpiozero and RPi.GPIO, and nothing to compile.
# A PIR motion sensor with gpiozero on a Raspberry Pi 4.
# The HC-SR501 runs from 5V (pin 2) and ground (pin 6). Its OUT is a 3.3 V
# signal, safe for a Pi pin, on GPIO4 (pin 7). The LED is on GPIO17 (pin 11)
# through a 330 ohm resistor.
from gpiozero import MotionSensor, LED
pir = MotionSensor(4)
led = LED(17)
print("Waiting for the room to be still...")
pir.wait_for_no_motion()
print("Ready")
count = 0
while True:
pir.wait_for_motion()
count += 1
led.on()
print("Motion detected!", count)
pir.wait_for_no_motion()
led.off()
print("Still again")
Parts list
5 parts, plus the jumper wires. They retail for about $60; on Mokxi they're free.
- 1 × Raspberry Pi 4 Model B
- 1 × Half breadboard
- 1 × Resistor, 330 Ω
- 1 × LED, red
- 1 × Motion sensor
How it is wired
6 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Raspberry Pi 4 Model B pin 5V; Motion sensor pin VCC
- Ground: Raspberry Pi 4 Model B pin GND; Motion sensor pin GND
- Raspberry Pi 4 Model B pin GPIO4; Motion sensor pin OUT
- Ground: Raspberry Pi 4 Model B pin GND; LED, red pin C
- Raspberry Pi 4 Model B pin GPIO17; Resistor, 330 Ω pin 1
- Resistor, 330 Ω pin 2; LED, red pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.