Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Projects

Project: A Motion-Detecting Alarm with PIR and Buzzer

Build a Raspberry Pi motion alarm: wire a PIR sensor and buzzer, arm and disarm it with a button, debounce triggers, and send notifications. Includes a state machine you can run.

A motion alarm is a small machine with clear states: it is disarmed, armed, or triggered. It looks simple, but a good one needs care. A PIR sensor fires several times per second for one passing person, a buzzer must not buzz forever, and you need a grace period to leave the room after arming. Handling these rules with a state machine makes the code clear and testable.

The GPIO parts need real hardware, so wiring and gpiozero code are read-only. The state machine itself is plain Python that runs here: we drive it with a scripted sequence of events, exactly what a test would do on the Pi too.

Parts and wiring

  • Raspberry Pi with the GPIO header.
  • HC-SR501 style PIR motion sensor (3 pins: VCC 5 V, OUT, GND). Its output is 3.3 V, safe for the Pi.
  • Active buzzer (it makes a tone when powered), connected through a transistor or small series resistor, to GPIO 18.
  • A push button on GPIO 23 to arm and disarm, and an LED on GPIO 24 to show the state.
TEXT
PIR   VCC -> pin 2 (5V)   OUT -> GPIO 17 (pin 11)   GND -> pin 6
Buzzer +  -> GPIO 18 (pin 12)   -  -> GND
Button    -> GPIO 23 (pin 16) and GND (internal pull-up)
LED + 330 ohm resistor -> GPIO 24 (pin 18) and GND

Most PIR boards have two knobs: sensitivity and hold time. Turn the hold time to minimum so your code decides how long an alarm lasts.

Reading the pins with gpiozero

gpiozero ships with Raspberry Pi OS and hides pin details behind device classes:

Python
from gpiozero import MotionSensor, Buzzer, Button, LED
from signal import pause

pir = MotionSensor(17)
buzzer = Buzzer(18)
button = Button(23)
led = LED(24)

pir.when_motion = lambda: print("motion!")
pir.when_no_motion = lambda: print("quiet")
button.when_pressed = lambda: print("button")
pause()      # keep the program alive, callbacks run in a thread

A PIR also needs about 30 to 60 seconds after power-up to settle. Wait for it before arming, or you will get false alarms at start.

The states

stateDiagram-v2
    [*] --> Disarmed
    Disarmed --> Arming: button
    Arming --> Armed: 30 s exit delay
    Armed --> Entry: motion
    Entry --> Disarmed: button within 20 s
    Entry --> Alarm: timeout
    Alarm --> Disarmed: button
    Alarm --> Armed: 60 s siren limit

The alarm waits through exit and entry delays before sounding the siren.

Each state answers two questions: what does the hardware do while in it (LED, buzzer), and which events move it to the next state. Writing this as a class makes every rule visible in one place.

A runnable state machine

The class below has no GPIO calls: it takes events and a clock value and returns the outputs. On the Pi a thin layer connects gpiozero callbacks to handle(), and the timer ticks every second.

Python The alarm state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the output to confirm the story: arming begins at t=1, the system is armed at t=4, motion at t=6 begins the entry delay, nobody disarms in time so the siren sounds at t=8, and the button silences it at t=12 (before the siren limit would have re-armed it). The motion event at t=3 was ignored because the system was still arming.

Debouncing motion events

A PIR may report motion, silence and motion again within a second. Counting each as a new event floods your phone. Debounce by ignoring repeats within a cool-down period.

Python Cool-down for repeated triggers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sending a notification

When the alarm goes off, tell yourself. Options, from simplest: write to a log with the timestamp; send a push notification through a service such as ntfy.sh (one HTTPS POST); publish an MQTT message to home/alarm; or send an email with smtplib. The ntfy call:

Python
import requests
requests.post("https://ntfy.sh/my-secret-topic-1f3a",
              data="Motion in the hallway", timeout=5)

Always set a timeout, and wrap the call in try/except: a Pi without Wi-Fi must still sound the buzzer. Keep secrets such as topic names or tokens out of the script, in an environment file that systemd loads.

Improving it

  • Add a camera snapshot on trigger (the camera chapter shows how).
  • Use a second PIR to cover another angle, and require two triggers within 10 seconds to cut false alarms.
  • Power the Pi from a small UPS or battery so a power cut does not disable security.
  • Use button.hold_time so that a long press arms and a short press does nothing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the alarm have an exit delay?

    Without it, your own movement while leaving would start the alarm.
  2. 2. What is the benefit of a state machine here?

    Events are ignored or accepted depending on the current state, which is easy to read and test.
  3. 3. What does a cool-down (debounce) do for a PIR sensor?

    It prevents a single passing person from creating many alerts.
  4. 4. Why should a notification call have a timeout and error handling?

    Unreliable networks are normal; local safety actions must keep working.

Summary

  • Model the alarm as states (disarmed, arming, armed, entry, alarm) and events.
  • Keep logic separate from GPIO so you can test it with a scripted clock.
  • gpiozero provides MotionSensor, Buzzer, Button and LED with callbacks.
  • Debounce triggers and limit siren time.
  • Notify through ntfy, MQTT or email, but never let notification failures block the alarm.

Next: Project: A Network-Wide Ad Blocker