Audio Files

Be sure to download the following MP3 files so that you can hear the samples playing. These sounds we are using came from MATTIX at . 

  1. enter.wav
    • freesound 462093
  2. exit.wav 
    • freesound 454638

Pulling Down the Files on the Pi

We can use wget to pull down the audio files and code directly to the Pi we are working on. ssh into your pi and run the following command to pull down the two audio files and example python code.

$ wget
$ wget
$ wget

Select the Audio Port

If you are using the 1/8inch audio jack, you'll need to ssh into your Pi and run this command to route audio to that output
$ sudo amixer cset numid=3 1

The Code

import time
import board
from digitalio import DigitalInOut, Direction
import pygame.mixer

# setup inputs
door_switch_pin = board.D23
motion_sensor_pin = board.D24

door = DigitalInOut(door_switch_pin)
door.direction = Direction.INPUT

motion = DigitalInOut(motion_sensor_pin)
motion.direction = Direction.INPUT

# setup output LED indicators
motion_led_pin = board.D18
door_led_pin = board.D25

door_led = DigitalInOut(door_led_pin)
door_led.direction = Direction.OUTPUT
door_led.value = False

motion_led = DigitalInOut(motion_led_pin)
motion_led.direction = Direction.OUTPUT
motion_led.value = False

prev_door = False

# audio settings
pygame.mixer.init(44100, -16, 2, 1024)

# sound files expect to be in the same directory as script
enter_sound = pygame.mixer.Sound("./enter.wav")
exit_sound = pygame.mixer.Sound("./exit.wav")

while True:

    # toggle door LED based on door sensor
    if door.value:
        door_led.value = True
        door_led.value = False

    # toggle motion LED based on motion (PIR) sensor
    if motion.value:
        motion_led.value = True
        motion_led.value = False

    # When the door is opened, if there is movement outside,
    # It means that someone is entering.
    # If not, someone is exiting.
    if door.value and not prev_door:
        if motion.value:

    prev_door = door.value

Run the Code

Run the code on your Pi and make sure it works. If the green LED is lit (motion detected) it should play enter.wav when the door switch is opened, and exit.wav if there is no motion detected. 

$ sudo python3 ./

The PIR sensor has two physically adjustable potentiometers on it, I've found it's best to set it to max sensitivity and minimum retrigger time. For more info, check out the PIR tutorial

Now lets mount it!

This guide was first published on Dec 20, 2012. It was last updated on Dec 20, 2012.

This page (Code) was last updated on May 13, 2021.

Text editor powered by tinymce.