Created
March 14, 2018 17:46
-
-
Save futurepaul/b8090d504137ed9013048a8de7678ec4 to your computer and use it in GitHub Desktop.
The “Why’d you push that button” button
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Step 1: Import the libraries we need | |
import pygame.mixer | |
import RPi.GPIO as GPIO | |
import glob | |
import random | |
import time | |
#Step 2: Fire up the sound mixer | |
pygame.mixer.init() | |
#Step 3: Register the GPIO pin we’ll be observing, and specify that want to “pull up” its voltage | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_UP) | |
#Step 4: Specify our folder of MP3s | |
soundfiles = glob.glob(“/home/pi/Desktop/Why-2/*.mp3”) | |
#Step 5: Here’s our play function! | |
def play(pin): | |
print(“playing”) | |
pygame.mixer.music.load(random.choice(soundfiles)) | |
pygame.mixer.music.play(1) | |
#Step 6: Print something when the script starts so we know it’s doing something. | |
print(“ready”) | |
#Step 7: Actually detect the button press | |
GPIO.add_event_detect(4, GPIO.FALLING, callback = play, bouncetime = 200) | |
#Step 8: Loop forever so the program stays alive while waiting for button presses | |
while 1: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment