Fareed Mohmed← Project library

Engineering · Raspberry Pi · Project 4 of 47 · Inputs · Beginner

Door alarm with a buzzer

A buzzer beeps while a door switch is open. You learn to wait for an input and to run a beep in the background.

▶ Open in the simulator

Raspberry Pi simulator drawing of the circuit for Door alarm with a buzzer: the board, its power supply and the parts wired to the 40-pin header

Parts in this circuit

PartType
BuzzerBuzzer
Door switchPush button

Wiring, pin by pin

Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.

#ColourFrom (part and leg)To (header pin)
1ColouredBuzzer - +Pin 12 (GPIO18)
2BlackBuzzer - -Pin 6 (GND)
3ColouredDoor switch - SignalPin 13 (GPIO27)
4BlackDoor switch - GNDPin 9 (GND)

Python code (gpiozero)

from gpiozero import Buzzer, Button

buzzer = Buzzer(18)
door = Button(27)          # the button acts as a door switch

print("Door closed. Press and hold to open the door.")

while True:
    door.wait_for_press()          # sleep until the door opens
    print("DOOR OPEN! Alarm!")
    buzzer.beep(0.2, 0.2)          # beep in the background
    door.wait_for_release()        # wait until the door closes
    buzzer.off()
    print("Door closed.")

How the code works

You will learn

  • wait_for_press and wait_for_release
  • Background actions: beep() keeps going while the code waits
  • Active buzzer versus passive buzzer

Try this

  • Beep faster: change both numbers to 0.05.
  • Count how many times the door was opened and print the count.
  • Add a red LED that stays on after an alarm until reset.

On a real Pi

  • An active buzzer has its own oscillator and just needs on/off. A passive buzzer needs a PWM tone.
  • Use a transistor for buzzers that draw more than about 10 mA.

Parts to buy

The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.

#ItemQtyBuy / compare
1Raspberry Pi 4 Model B
about 4000 to 9000 INR
1Robu.in Amazon.in ThinkRobotics
2Official 15 W USB-C power supply (5.1 V, 3 A)
Do not use an old phone charger
1Robu.in Amazon.in ThinkRobotics
3microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS)
And a card reader to write it
1Robu.in Amazon.in ThinkRobotics
4Tactile push button (12 mm, with cap)1Robu.in Amazon.in ThinkRobotics
5Active buzzer, 5 V1Robu.in Amazon.in ThinkRobotics
6Dupont jumper wires, male-to-female, 20 cm (pack of 40)1Robu.in Amazon.in ThinkRobotics
7Breadboard 830 points
For resistors and shared GND / 5 V
1Robu.in Amazon.in ThinkRobotics
← 3. Traffic light with a walk buttonAll projects5. Motion alarm with a PIR sensor →

This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.