The Official Raspberry Pi Projects Book - Projects_Book_v4

(singke) #1

Tutorial


raspberrypi.org/magpi The Official Raspberry Pi Projects Book 105


3V3GP2
GP3GP4
GP17GND
GP27GP22
GP103V3
GP09GP11
GNDDNC
GP5GP6
GP13GP19
GP26GND

5V5V
GP14GND
GP15GP18
GP23GND
GP24GND
GP25GP8
GP7DNC
GP12GND
GP16GND
GP20GP21

MAKE A WHOOPI CUSHION


import os
import random
from time import sleep
from gpiozero import Button

button = Button( 2 )
trumps = ['ben-fart.wav', 'ca-fart.wav', 'marc-fart.wav']

while True:
button.wait_for_press()
parp = random.choice(trumps)
os.system("aplay {0} ".format(parp))
sleep( 2 )

whoopee.py


Language
>PYTHON 3

DOWNLOAD:
magpi.cc/
WhoopiCushion

True:. Then, add button.wait_for_press() inside
the loop by indenting by four spaces. Each time
around the loop, the computer waits for the button
to be pressed.
On the next line, use the random.choice function
to select a sound at random from the list you created
earlier. That selected sound needs to be stored inside
another variable which you can call parp! Type parp =
random.choice(trumps).
The next line will play the sound selected at random
using aplay, as used earlier when testing sounds.
Type os.system("aplay {0}".format(parp)).
Finally, add sleep(2) to pause the program before it
starts the loop again. Your code should look like this:


while True:
button.wait_for_press()
parp = random.choice(trumps)
os.system("aplay {0}".format(parp))
sleep(2)

Save the file by clicking on File > Save. Test that your
code works by clicking on Run > Run Module. Use your
hand to push the top plate of your Whoopi cushion
down to make a connection between the foil sheets,
and you should hear a fun sound. If it doesn’t work first
time, don’t worry. Check your code through. Have you
typed your code out exactly as you see it here?


Setting it up
Carefully place your cushion in a spot where your
victim will sit on it (obviously!), but not under a really
heavy cushion where it will be squashed straight
away. The tricky bit is setting up the Pi so that it
can’t be seen: remember, you’ll need a plug socket to
connect it to the power, unless you’re using a battery
pack. Run the program, and wait. Here’s a hint:
whistle tunelessly and look around at the ceiling. This
will make you seem innocent, and will help to attract
potential victims.

Figure 5 Yours may
be considerably
tidier than this. Or
messier. It’s all good
Free download pdf