This project uses
the Raspberry Pi GPIO to generate various musical notes. We are going to get the RPi to play a pre-programmed
tune. This is one of 10 projects that can be made with the kit here and e-books is available for the Amazon Kindle here
We are going to use
a speaker for this. The RPi GPIO pins are not powerful enough to drive a
speaker, so we are going to use a simple transistor amplifier to make these
tones audible.
The tone from the
RPi digital output is a square wave and will sound quite distorted. The 220 ohm
resistor and the 1uF capacitor form a filter and improves the sound. Built on a
prototyping breadboard the circuit looks like this. It does not matter which way
round the speaker is connected.
The
Python code for generating the musical tones is shown below. This uses the
Pulse Width Modulated (PWM) output to generate square waves at
the right frequency. The notes and timing for “London Bridge is Falling
Down” is kept in two arrays. Each note is fetched in turn and played for the
specified time.
#!/usr/bin/env python
#Python code for RPi Tunes
#Plays "London Bridge
is Falling Down"
#www.sf-innovations.co.uk
import RPi.GPIO as
GPIO #import GPIO library
import time #import time library
GPIO.setmode(GPIO.BOARD) #use board pin numbers
GPIO.setwarnings(False)
GPIO.setup(11, GPIO.OUT) #setup pin 11 as output
#define frequencies
c=262
d=294
e=330
f=349
g=392
a=440
b=494
C=523
# London Bridge is falling
down - notes and timing
notes =
[24,g,a,g,f,e,f,g,d,e,f,e,f,g,g,a,g,f,e,f,g,d,g,e,c]
times =
[24,1,1,1,1,1,1,2,1,1,2,1,1,2,1,1,1,1,1,1,2,2,2,1,1.5]
#read the notes and timing
and output to pin 11
y = notes[0]
for x in range (1, y+1):
tone = notes[x]
b = GPIO.PWM (11,tone)
b.start(50)
delay = 0.3 * times[x]
time.sleep(delay)
b = GPIO.PWM (11, 10)
time.sleep(0.1)
GPIO.cleanup() #tidy up GPIO port
import sys #exit program
sys.exit()
Such a nice blog ,Thank you for sharing.-
ReplyDeleteIt will may help you :-
painted pine drawers