Who keeps opening the biscuit tin? Does the cat really sleep all night? A motion alarm can tell you. In this lesson you connect a PIR motion sensor to the Raspberry Pi. When someone moves in front of it, the Pi beeps, lights an LED and writes the date, the time and how long the movement lasted into a file called visits.csv. The next day you open the file and see every visit, even the ones that happened while you were asleep. You learn how Python reacts to events, and how to log data to a file.
What you'll learn
- How a PIR sensor notices people and animals by their body heat
- How to set the sensor's two knobs and its jumper
- How gpiozero runs your functions when motion starts and stops
- How to save data to a CSV file that a spreadsheet can open
- How to play a short tune on a piezo buzzer with
TonalBuzzer
What you need
- Raspberry Pi 4 Model B with Raspberry Pi OS on a microSD card (see the first lesson) and its USB-C power supply
- PIR motion sensor (ESP32 IoT Starter Kit)
- Piezo buzzer (ESP32 IoT Starter Kit)
- 1 LED and a 220 Ω resistor (ESP32 IoT Starter Kit)
- Breadboard (ESP32 IoT Starter Kit)
- Female-to-male jumper wires, to go from the Pi's pins to the breadboard. If you don't have any, plug a female-female and a male-male Dupont wire from the ESP32 IoT Starter Kit together.
Look after your Pi: the GPIO pins work at 3.3 V. The PIR sensor gets its power from a 5V pin, but its OUT pin only ever sends about 3.3 V, so it is safe to connect to a GPIO pin. Never connect 5 V to a GPIO pin, never connect a 3V3 or 5V pin to GND, and always shut the Pi down and unplug it before you change the wiring.
Wiring
Take the plastic dome off the PIR for a moment: the three pins are labelled underneath, usually VCC, OUT, GND. Always follow the labels on your module, and put the dome back on. Push the PIR's three pins into the breadboard (or connect them with female-to-male wires), then add the LED and the piezo buzzer.

| From | To |
|---|---|
| PIR VCC | 5V (pin 2) |
| PIR OUT | GPIO 4 (pin 7) |
| PIR GND | The blue (−) rail |
| GPIO 17 (pin 11) | 220 Ω resistor → LED long leg (+); LED short leg (−) → the blue (−) rail |
| GPIO 27 (pin 13) | Piezo buzzer + leg; the other leg → the blue (−) rail |
| The blue (−) rail | GND (pin 9) |
Set the sensor first. The PIR has two small orange knobs and a jumper. Turn the time knob anticlockwise as far as it goes, so the sensor resets after a few seconds instead of minutes. Set the jumper to H (repeat), so the signal stays on for as long as someone keeps moving. The sensitivity knob sets how far it can see, from about 3 to 7 metres.
The program
Open Thonny (Raspberry menu → Programming → Thonny), paste the program into a new file, save it in your home folder as motion_logger.py, and click the green Run button. Press the red Stop button (or Ctrl+C) to stop it. gpiozero is already installed on Raspberry Pi OS.
# Motion alarm that logs every visit (gpiozero + a CSV file)
from gpiozero import MotionSensor, LED, TonalBuzzer
from datetime import datetime
from signal import pause
from time import sleep
import csv
import os
pir = MotionSensor(4)
led = LED(17)
buzzer = TonalBuzzer(27)
LOG = os.path.expanduser("~/visits.csv") # the file goes in your home folder
visits = 0
start = None
def motion():
global visits, start
visits += 1
start = datetime.now()
led.on()
print(f"{start:%H:%M:%S} Motion! Visit number {visits}")
for note in ("E5", "A4", "E5"): # a short three-note alarm
buzzer.play(note)
sleep(0.15)
buzzer.stop()
def no_motion():
led.off()
if start is None:
return
seconds = round((datetime.now() - start).total_seconds())
with open(LOG, "a", newline="") as f:
csv.writer(f).writerow([start.strftime("%Y-%m-%d"), start.strftime("%H:%M:%S"), seconds])
print(f" Quiet again after {seconds} s. Saved to visits.csv")
if not os.path.exists(LOG): # first run: write the column names
with open(LOG, "w", newline="") as f:
csv.writer(f).writerow(["date", "time", "seconds"])
print("Warming up the sensor. Keep still for 60 seconds...")
sleep(60)
print("Ready. Watching for motion. Press Stop to end.")
pir.when_motion = motion
pir.when_no_motion = no_motion
pause()
Try it
- Run the program, then sit still or leave the room for one minute while the sensor warms up.
- When the Shell says "Ready", walk past the sensor. The LED lights, the buzzer plays three notes and the Shell prints the time and the visit number.
- Stand still or walk away. A few seconds later the LED goes off and the Shell says how long the visit lasted.
- Do it a few times, then press Stop. In Thonny, click File → Open, choose All files and open
visits.csvfrom your home folder: there is one line for every visit. - Leave it running overnight in a hallway, and look at the file in the morning.
What you should see

How it works

Everything warm gives off invisible infrared light, and people and animals are warmer than walls and furniture. The PIR (passive infrared) sensor has two small sensing areas behind the white dome. When a warm body moves across the room, one area sees it before the other, and the sensor turns that difference into a signal: OUT goes to about 3.3 V. "Passive" means it sends nothing out; it only watches. That is also why it needs to warm up: for the first minute it learns what the room normally looks like and may trigger by itself.
The time knob sets how long OUT stays on after movement, from about a second to a few minutes. With the jumper on H, every new movement starts that time again, so OUT stays on as long as someone keeps moving. That is why the logged "seconds" are the visit plus the few seconds of the time knob.
The program never checks the sensor in a loop. Instead, pir.when_motion = motion tells gpiozero "run my motion() function whenever OUT goes on", and when_no_motion does the same for off. This is called event-driven programming, and pause() just keeps the program alive while it waits. A CSV file (comma-separated values) is plain text with one row per line and commas between the columns, so spreadsheets like LibreOffice Calc, Excel and Google Sheets can all open it. Opening the file with "a" adds each new row to the end instead of starting again.
Try this next
- Make it quiet at night: only play the buzzer between 8:00 and 20:00, but keep logging all the time.
- Count the visits per hour and print a little bar chart of the busiest hours when you press Stop.
- Add the push button from the button lesson to switch the alarm on and off.
- Combine it with the web server lesson and show the latest visits on your phone.
Troubleshooting
- It triggers by itself all the time: wait for the full minute of warm-up, keep the sensor away from heaters, sunny windows and air vents, and turn the sensitivity knob down a little.
- The LED stays on for minutes: the time knob is turned up. Turn it anticlockwise as far as it goes.
- Nothing happens when you walk past: check that VCC is on 5V (not 3V3) and OUT on GPIO 4 (pin 7). Remember the sensor sees movement across the room much better than straight towards it.
-
The buzzer doesn't sound, or only clicks: check its two wires. If your buzzer beeps by itself as soon as it gets power, it is an active buzzer: use
Buzzer(27)withbuzzer.beep(0.1, 0.1, n=3)instead of the notes. - "Permission denied" when saving the file: run the program from your home folder, where you are allowed to write files.
-
Always shut down properly: click the Raspberry menu → Shutdown, or type
sudo shutdown now, and wait until the green light stops flashing before you unplug the power.
What next?
You have finished the Raspberry Pi starter path. Ready for bigger builds? The Raspberry Pi advanced projects path starts with a temperature logger with a live web chart and ends with three projects for the Raspberry Pi Pico.