PIR + Python + Raspberry Pi = Motion Triggered Audio Installation.

History of the Project:

My father is a curator of a small museum about the history of our village, Elgg Switzerland. He had the idea that a piece of music is played when someone approaches the "Äschli" exhibition. "Äschli" is an old historical tradition, which is celebrated here in our village only, for kids involving piccolo flute and drum music. If you like to know more about this tradition or the museum, please follow the link below.

He searched the internet for a ready made product, but had no luck. So we decided to build it by our own. Because the museum is run by volunteers the budget should be low. After a search of mine about different build ups. I found out that not much tutorials where around. Since I tinker a lot as hobby and working with electronics, the project wasn't that hard to realize from scratch. Because I'm a big fan of Eben Upton CEO of the Raspberry Pi Foundation, the decision away from Arduino with mp3/wav shield towards a Raspberry Pi was quickly made. Also it would be about the same price then a Arduino setup. Also a got a big stash of Raspberries and accessories around.

So my final Setup consists a PIR Sensor monitored by a python script running on the Raspberry. This will play the audio file when motion is detected. Further more i will use a external USB sound card, small PC speakers for playback and a WiFi dongle serving a AP w/ DHCP for hazel free service per SSH/SCP.


This tutorial will not teach you how to solder, cut or drill holes. It's totally open beside hardware, but i will show you what i have used and how i build it together. I will also provide links to other tutorials where available. [please post suggestions].

The skill level needed to complete this project depends on material and parts used. You may go for that fully housed soldered buildup or decide for breadboard cabling where no soldering and less crafting skills are needed.

But you should have played around with a Raspberry before or may start with some beginner guides first. You will need to setup a clean Raspbian image and then connect to the Pi over ssh. You will also need to transfer files and such, but i will try to guide you into the right direction.

Step 1: Hardware: Parts and Tools

Part List
- Raspberry Pi w/ SD-card
- Prototype shield or similar
- PIR Sensor
- 5V Power supply
- Small Electronics and Cables
- RPi compatible Speaker

- USB Sound

- WiFi / Network Adapter
- Case
- Jacks and Plugs
- Switch and Button
- Misc small parts


  • Raspberry Pi w/ SD-card

I used a RPI2 B512 with a 8gb SD-card but all other would work for this project. I would liked to use a Zero but it was totally sold out at the moment, so i bought a 3B but use the 2B because because the 3 was to shiny, i like to keep it to tinker around with the new CPU. It really not count which you use since the default GPIO pins in my script are on the same pin on all RPi's. And if you don't plan to run a very long audio file, even 256mB RAM would be enough.

  • Prototype shield or similar

Depending on which Raspberry you use and if you go for solder or breadboard setup you need to get the right part here. You could use jump wires only, in a breadboard setup.
I used: https://www.adafruit.com/product/801

  • PIR Sensor

I used a HC-SR505 because it's small. But you could use any PIR sensor with 5V supply and 3.3V Output. (You could use other supply and output types with the correct level shifter and power supply setup)

  • 5V Power supply

suited to your Setup (easiest solution is micro USB to RPi ).
I used a 5V 3A power supply from a old router.

  • RPi/PC Compatible Speaker

I used one with USB power and 3.5mm jack for audio. There are a couple of this kind of speaker around. I chosen a active speaker because it has dedicated volume control and spare power if it need to be a bit louder then normal. A small passive speaker had done the job, but they are hard to find here and about the same price like the active ones XD

  • Small Electronics and Cables

please see in the "Hardware:Schematic" step for more detail.

  • Misc small parts

I used shrink tubing, screws, screw posts, hot glue, CA glue and 2part Composite glue. Some old headphone cable for the PIR Sensor and some other small stuff.


  • USB Sound Card

You could use the audio Output of the Raspberry itself but since those USB adapters are cheap and the audio quality is way better. I always use one of these in my RPi audio projects. If you like to follow my Setup guide choose one with a c-media cm108 chip set.
I used: https://www.adafruit.com/products/1475

  • WiFi / Network Adapter

Not required but it's easier then wire the plug, to gain network access from outside of the box.
I used one with a Ralink RT5370 which was a little pain to setup in AP mode but if You like to follow my guide 1:1 use the same, but be warned there are other chip sets which are better supported on RPi/Linux.

  • Case

Suited to your setup if you will use one. This also strongly depend on the environment where you install the raspberry. Mine isn't heated in winter and cooled in summer but pretty dry and little bit dusty. More like a old Farm shack then a living room. Also there should only be one of one kind of connector, so anybody could unplug/plug it. That's the reasons why i gone the "hard way" with a case.

  • Jacks and Plugs

This depends on your setup and your skills. It's not that easy to cut out the needed holes for some plugs. Some are easy others are pain.You may not even need plugs since you could directly connect everything directly to the RPi.
I used a standard USB A jack for the speaker power, a standard dc jack for main power, db9 serial connector for the PIR sensor and free pins future ideas. I didn't need a audio jack, just used the one on the Sound Card.

  • Switch and Button

Optional but i like to have a Power switch on any Project. The Button will give you the ability to stop the music if unwanted trigger happens, b̶u̶t̶ ̶o̶p̶t̶i̶o̶n̶a̶l̶ (After a lot of long term test, I would highly recommend one!)


You may need other tools like the other things, it depends on your setup.
For reference here the tools i used:

- Soldering Iron with accessories
- Dremel with a 2 flute 1/8" cutter to cut out the Plug Holes
- Files
- Sanding paper
- heatgun (for shrink tubes)
- hot glue gun
- screwdriver
- side cutter
- claws
- different drills

Step 2: Hardware: Schematic

In the above schematics you can see how to connect everything together.

The PIR sensor have 3 pins:
+ connect to 5V
out connect to GPIO #17
- connect to GND

The Button will connect to 3.3V and to GPIO #18

On both GPIOs i got a 100nF cap, they could be omitted, but will provide AC decoupling and hardware debounce the button.

Since we are gonna use the internal pull down resistor of the GPIO we don't need a external one, but you may add a 3-10k one if you have problems with random triggering.

But beware the USB devices are missing on the Fritzing schematic. On the other schematic you can see the speaker power is connected to one of RPis USB ports. On my build the speaker power is connected directly to 5V.

Step 3: Hardware: PIR Sensor

Like said i used a HC-SR505 because it's small.

Through it's slim design it's hard to integrate in a small case, but would be perfect for a "in cable design".

So i first soldered a old 3pin old headphone Cable to it. Which we first measured as "enough long". It was about 2m but i wouldn't recommend to exceed 5m. The resistance of the cable could be to high for a clean HIGH input on the GPIO, beside a lot of other bad effects using long cables.

Also Protected the actual PIR Sensor to the PCB with some layers of hot glue.
i didn't take a picture but you can see the PIR sensor is not mechanically mounted to the PCB
only soldered. This means any mechanical stress will apply to the solder points which is a nono.

Then wrapped shrink tubes around it, to isolate the PCB from the outside and make the sensor black.

Step 4: Hardware: Case, RPi & Sound Card

I removed the unused connector of the sound card, so i could directly glue it to the case wall and provide the audio out connector on the outside.

Actually i just cut the holes per eye and checked if the connector fits.

It's not pretty, it's not air tight, but it works out! :)

You may also see that i prepared all pins of the db9 connector.
(I didn't follow any standard, just took the db9 because i got them around and doesn't have any other "small" 3 pin connectors which i could use for this.)

After all connectors fitted, i point fixed them with CA glue. Then secured them with epoxy resin glue.

The Raspberry Pi sits on 14mm M2.5 screw post.. This space will help with cooling. My Raspberry was already setup when i mounted it, you may go through the software steps before mount your RPi in to a case.

Step 5: Software: Basic RPi Setup

You will need to download a Image to your SD-Card. I used Raspbian Jessie Lite, but you could use the full blown Jessie too, since i don't need a X-server and all that shiny extras of the full Raspbian i took the lite. If you had never setup a Raspberry i will recommend to first read a beginners guide. But here is how i setup mine:

  1. Download Image: https://www.raspberrypi.org/downloads/raspbian/ (Jessie lite)
  2. Write the Image to SD using your favorite disk image software eg. Win32DiskImager or dd
  3. Put Card in the RPi
  4. Connect RPi to LAN, USB-Keyboard, HDMI-Monitor and Power
  5. Note RPis IP Address which is printed out during boot
  6. Login with Pi / Raspberry
  7. Start config utility

    sudo raspi-config

  8. Expand filesytem
  9. memory split -> GPU 16mb
  10. make sure SSH is enabled
  11. finish
  12. reboot

Then i disconnected the HDMI and USB-Keyboard. Since i will just interact with the Pi over SSH and SCP i don't need them anymore.

Also you could do this totally different. Some don't connect USB keyboard, just note IP address then connect through ssh. Others don't even need a monitor and find the ip with a look at DHCP table of there routers. The internet is full of guides how to setup your rpi, you may do some research.

Step 6: Software: Setup USB Audio

Since i got a cm108 c-media based card this guide will only apply on similar cards. You will need to setup your speaker/sound card to be default audio interface when play music in pygame or aplay.

You should have connected your sound card to USB right now, if not power down, connect, restart.
You should also connect your Speaker before boot too.

first you will need to install the ALSA utils: (you will need internet connection for this!)
sudo apt-get update
sudo apt-get install alsa-utils

Then you can check if the USB device is enumerated:


should give a list with all USB devices connected.
you need to look for a line with somethig like cm108 c-media

you can also check if aplay will see your card:

aplay -l

will give you something like: card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]

After i could see the Card was correctly installed by default i could start to make it default audio device:

sudo nano /lib/modprobe.d/aliases.conf

change line options snd-usb-audio index=-2
to #options snd-usb-audio index=-2
(add # to begin of the line aka comment out)
save and exit (Ctrl + x, y, {enter})

i also had to comment out one line in /boot/config.txt

sudo nano /boot/config.txt

change line dtparam=audio=on
to #dtparam=audio=on
save and exit (Ctrl + x, y, {enter})

then i needed to rise the volume of the output but first check which channel is associated:

amixer controls

will list you the mixer controls look for numid=6,iface=MIXER,name='Speaker Playback Volume'

amixer cset numid=6 95%

this will set volume to 95%, you may need to change numid to the right value you got from the mixer controls before

then save controls setup:

sudo alsactl store

then you can test your audio setup with:

speaker-test -t wav -c 2

you should hear a voice telling you front left/right, if you got your speaker connected already.

Step 7: Software: Setup Software

Install pygame for python 2 and git: (you will need internet connection for this!)

sudo apt-get update
sudo apt-get install python-pygame git

Confirm with y if asked

i put everything in home of user pi, into a folder called PIRMA.
make sure that you are in /home/pi/ directory then clone my repository to it.

cd /home/pi/
sudo apt-get install git
git clone git://github.com/FrYakaTKoP/PIRMA.git

now you need to copy your audio file to the same directory. I used WinSCP if you struggle here please search the internet for "how to copy files to raspberry pi".

The default filename is "audio.wav" rename your file to this or change audio file variable in the python script.

My audio file is a 44100Hz 16bit PCM Microsoft WAV. Pygame does also support other file types and sample rate. But would highly recommend to use this parameters for your Audio file. I used Audacity to covert my stereo mp3 to mono wav.

You can also alter the armed.wav if you like to have a different sound file for armed signalization.

After you have put your music to the pi you can test if everything works as expected, using following command:

sudo python pirma.py

Now you should hear a "woooup" which tell you the script is running and the PIR sensor is armed. Now if you trigger the motion detection, you should here your music start playing. After finish playing the script will hold for 10 seconds before rearming. It will also not arm if the input is high, means it will not retrigger if there is continues motion.

If you have a button, you can stop the playing and directly rearm with it.

I had some Problems with long term run, Pygame or Alsa seem to crash after about 5-8 hours. So I made the Script to Restart itself after playing the audiofile. Also added a restart when the Script is armed for more then 4 hours without motion. With this changes, the script has proven to run without a problem for more then 50 hours straight. Even though, for our application this wasn't needed, since the museum is open for about 4 hours and the system is without power when the museum is closed. So any time the museum opens there is a fresh boot of the system and before the script would hang the museum closes.

Step 8: Software: Autostart Script on Boot

Now we add the python script to auto start after reboot using cron:

sudo crontab -e

may get asked for editor choose nano then add following line to the bottom:

@reboot python /home/pi/PIRMA/pirma.py &

save and exit (Ctrl + x, y, {enter})

now you can reboot your pi and the script now autostart in background with the pi.

If you need to stop the script you can do with:

sudo killall python

Step 9: Software: WiFi Access Point

I configured the Wifi Interface to provide Access point with DHCP. Since the Raspberry is away from any other Wifi Access point. I needed something to connect to it if any problem appear or my Dad like to have some changes made. And for me this was the most comfortable solution.

This Guide will only apply if you have Ralink RT5370 based chipset but you may use my config files with different chip sets, since they are not Ralink specific.

Again connect the USB device before you power the Raspberry.

First check if USB device is enumerated:


look for line: Bus XXX Device XXX: ID 148f:5370 Ralink Technology, Corp. RT5370 Wireless Adapter

now see if the needed kernel modules (drivers) are loaded:


search for following:


If you got those lines your Wifi Adapter should work.

We need to install hostapd and udhcp: (you will need internet connection for this!)

sudo apt-get update
apt-get install hostapd udhcpd

Then to make your life easier i also pushed my config files to the github repository, they are found in the wlanAPcfgs folder in /home/pi/PIRMA/ if you cloned the full repository.

Start coping the config files to there destination.

sudo cp /home/pi/PIRMA/wlanAPcfgs/udhcpd.conf /etc/udhcpd.conf
sudo cp /home/pi/PIRMA/wlanAPcfgs/udhcpd /etc/default/udhcpd
sudo cp /home/pi/PIRMA/wlanAPcfgs/interfaces /etc/network/interfaces
sudo cp /home/pi/PIRMA/wlanAPcfgs/hostapd /etc/default/hostapd

edit /wlanAPcfgs/hostapd.conf file with you preference first:

nano /home/pi/pirma/wlanAPcfgs/hostapd.conf

you can change line ssid=PirmaAP to your preferred ssid. Also change the line wpa_passphrase=PirmaKey0 to your private key. After you made your changes, save and exit (Ctrl + x, y, {enter}).

Then copy your edited file to its directory.

sudo cp /home/pi/pirma/wlanAPcfgs/hostapd.conf /etc/hostapd/hostapd.conf

I also had to edit the init.d script or it would not get the config file as a parameter. This is a know bug, it will run fine if you start it over command line with the right parameters but not over the rc.d script. So copy this too:

sudo cp /home/pi/pirma/wlanAPcfgs/init_d/hostapd /etc/init.d/hostapd

Then we need to activate the deamons of hostapd and udhcpd

sudo update-rc.d hostapd enable

sudo update-rc.d udhcpd enable

Now reboot

sudo reboot

After boot you should find your RPis Access point listed on your notebook, tablet or phone. Now you have a wireless access to the RPi without take it out of your installation or connect a LAN cable to it.

Step 10: Software: Some Tips About Embedded Systems

Since our installation will not really run that much time, i don't did any preventive action to protect the system.

You may consider following tips if your RPi will run 24/7 or it will may fail after couple weeks! Since if run 24/7 the hours of runtime will count up pretty quick.

Protect your SD card from writing. Usually similar system with flash drive have a write protect filter active, so the SD-Card will less wear out over time. This is the most vulnerable part of this setup.

You may also consider build a Hardware watchdog to your RPi, if your system needs high availability. I didn't do that at all since with our short runtime, i had no problem with a hang of the system (expect for the pygame crash).

I would recommend you to test the system some days before mount/install it. It's a pain to find whats wrong if all cables and stuff is nicely layout.

Step 11: Finish

Luckly, i don't had to do a lot beside of installing it to the scene. I just could place the box and speaker on top/behind a wooden beam where you can not see it. The PIR sensor gets placed to the right of the scene, so it triggers when a person enters the scene only, but not if someone walks by in front of the part of the museum. I will give you the tip to position your sensor in a way, it will not trigger to much. It will be disturbing if it play music the whole day. You and your visitors will hate that music in short time, if it gets repeated permanently.

<p>Very cool! This looks like a great addition to your little museum. Great first instructable, too!</p>
<p>thank you</p>

About This Instructable




More by FrYakaTKoP:P.I.R.M.A Raspberry Pi PIR Motion Audio Installation 
Add instructable to: