This project will show you how to wire up buttons to your Raspberry Pi’s GPIO pins and then use them to play sounds with a simple Python application.
Parts Needed:
You will need the following parts:
⦁ 1x Breadboard
⦁ 1x Raspberry Pi
⦁ 4x Push Buttons
⦁ 4x 330 Ω or 220 Ω Resistors
⦁ 9x Jumper Wires
⦁ Hardware Hookup
Ready to start hooking everything up?
What you will learn
By creating a GPIO music box with your Raspberry Pi you will learn how to:
⦁ Learn how Sound Blocks work in Scratch
⦁ Connect a button to the GPIO pins on a Raspberry Pi
Circuit Diagram:
Connect the top right pin of the Push Button to Ground on the breadboard.
Connect the bottom right pin to ground on the breadboard using a resistor.
Connect the bottom left Pin to the correct GPIO port. (Push Button 1 to GPIO 2, Push Button 2 to GPIO 3, Push Button 3 to GPIO 4, and Push Button 4 to GPIO 5).
Connect Ground on the breadboard to Ground on the Raspberry PI.
Programming Code:
import RPi.GPIO as GPIO
import pygame, sys
from pygame.locals import *
pygame.init()
from time import sleep
sound1 = pygame.mixer.Sound(‘/home/pi/Documents/ButtonSounds/sound1.wav’)
sound2 = pygame.mixer.Sound(‘/home/pi/Documents/ButtonSounds/sound2.wav’)
sound3 = pygame.mixer.Sound(‘/home/pi/Documents/ButtonSounds/sound3.wav’)
sound4 = pygame.mixer.Sound(‘/home/pi/Documents/ButtonSounds/sound4.wav’)
i = 1
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.IN)
GPIO.setup(7,GPIO.IN)
while i<100:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5,GPIO.IN)
GPIO.setup(7,GPIO.IN)
GPIO.setup(8,GPIO.IN)
GPIO.setup(10,GPIO.IN)
if not GPIO.input(5):
print(“5: %s” % GPIO.input(5))
print(“Playing sound1”)
sound1.play()
i+=1
sleep(1)
elif not GPIO.input(7):
print(“7: %s” % GPIO.input(7))
print(“Playing sound2”)
sound2.play()
i+=1
sleep(1)
elif not GPIO.input(8):
print(“8: %s” % GPIO.input(8))
print(“Playing sound3”)
sound3.play()
i+=1
sleep(1)
elif not GPIO.input(10):
print(“10: %s” % GPIO.input(10))
print(“Playing sound4”)
sound4.play()
i+=1
sleep(1)
GPIO.cleanup()
GPIO.setwarnings(False)