User Guide

193
5. On the Menu, click File and then click Save As.
6. Save the file to your folder, as doorbell.py.
7. Add the Python code below, and then save your
script again:
import RPi.GPIO
RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(2, RPi.GPIO.IN,
pull_up_down=RPi.GPIO.PUD_UP)
def Ring():
pass
while True:
if RPi.GPIO.input(2) == RPi.GPIO.LOW:
Ring()
This code detects a button press in the same way as described
in Chapter 7 – Controlling Input and Output Pins on page154. It
then calls the function Ring(), which does nothing yet.
To play a sound file from Python, you can use mpg321. This is a
command line tool for playing MP3 files on Raspbian, but you
can start it from a Python script. To install mpg321:
• In LXTerminal, type the following command and then
press Enter:
sudo apt-get install mpg321
Copy the sound effect .mp3 into your Doorbell folder.
Add the following import directive to the top of the script:
import os
Then in the Ring() function, remove the pass statement and add
the following code; replace the file name of the MP3 file if
necessary.
os.system("mpg321 ring.mp3")
The system() function in the os module runs command line tools
from Python scripts. To run the script: