The Official Raspberry Pi Projects Book - Projects_Book_v4

(singke) #1

Tutorial WALKTHROUGH


(^104) The Official Raspberry Pi Projects Book raspberrypi.org/magpi
amixer cset numid=3 1
If your Raspberry Pi is connected to the internet,
you could search for some suitable trumping sounds.
They need to be in WAV format to work. Alternatively,
download our example sounds here: rpf.io/farts.
Write a program in Python
Open Python 3 (IDLE) from the Programming menu
and click on File > New Window. This will open a blank
file. Click on File > Save As, name the file whoopee.py
and then type the following code into your file:
import os
import random
from time import sleep
from gpiozero import Button
This part of the code pulls in all the libraries that
you’re going to use to write your program. You’ll then
need to use the Button class in your code. You’ll have
to tell it that the button is on pin 2. To do this, write
the following code in your new file:
button = Button(2)
Now create a list of all your sound effects and store
them inside a variable that you can call later on in
your code:
trumps = ['ben-fart.wav', 'ca-fart.wav',
'marc-fart.wav']
In Python, square brackets are used to create a list.
Each item in the list is separated by a comma.
Once all the setup needed in the code is complete,
you can move on to writing the part of the program
that will make something happen when the button
is pressed. Begin by creating a loop using while
3V3
GP2
GP3
GP4
GND
GP17
GP27
GP22
3V3
GP10
GP09
GP11
GND
DNC
GP5
GP6
GP13
GP19
GP26
GND
5V
5V
GND
GP14
GP15
GP18
GND
GP23
GP24
GND
GP25
GP8
GP7
DNC
GND
GP12
GND
GP16
GP20
GP21
Connect the speaker to the Raspberry Pi using the
sound jack. Create a new folder called whoopee by
typing the following command in the Terminal and
pressing ENTER on the keyboard:
mkdir whoopee
Next, use cd whoopee to enter the folder you
have just created. We’re going to need a sample
sound file for this project, so we’ll use one from
Sonic Pi. Download this burp sample using the
following command:
wget http://rpf.io/burp -O burp.wav
Now, test that you can play the sound file using
aplay by typing:
aplay burp.wav
You should hear it from the speakers or headphones
connected to your Pi. If you can’t hear anything, make
sure that your speakers are connected correctly. If
this still doesn’t work, you’ll need to change your
audio configuration.
To switch audio to the headphone jack, return to the
terminal window and type the following command:
Figure 3 Again,
this will be the
same pin on any
Raspberry Pi
Figure 4 It’s a very
simple step but
best to get it right

Free download pdf