Raspberry Pi Project 3: Musical Tune Generator

We combine our passive buzzer circuit with a Python script to create tunes via the command line.

The following project uses the same circuit we used in tutorial 7:

Raspberry Pi Project 3: Musical Tune Generator Schematic Circuit Diagram

Open IDLE on your Raspberry Pi (Menu > Programming > Python 2 (IDLE)) and open a new project (File > New File).  Then type the following:

import RPi.GPIO as GPIO
import time
from sys import argv

bbm=100 #number of beats per minute
tempo=float(60/float(bbm))
gpin=18

GPIO.setmode(GPIO.BCM)
GPIO.setup(gpin, GPIO.OUT)
GPIO.output(gpin, False)
tune = argv[1]

note=[""]*25
freq=[0.0]*25

note[0]="-"
freq[0]=0.0

note[1]="C"
freq[1]=1046.50

note[2]="C#"
freq[2]=1108.73

note[3]="D"
freq[3]=1174.66

note[4]="D#"
freq[4]=1244.51

note[5]="E"
freq[5]=1318.51

note[6]="F"
freq[6]=1396.91

note[7]="F#"
freq[7]=1479.98

note[8]="G"
freq[8]=1567.98

note[9]="G#"
freq[9]=1661.22

note[10]="A"
freq[10]=1760

note[11]="A#"
freq[11]=1864.66

note[12]="B"
freq[12]=1975.53

note[13]="C2"
freq[13]=2093

note[14]="C#2"
freq[14]=2217.46

note[15]="D2"
freq[15]=2349.32

note[16]="D#2"
freq[16]=2489.02

note[17]="E2"
freq[17]=2637.02

note[18]="F2"
freq[18]=2793.83

note[19]="F#2"
freq[19]=2959.96

note[20]="G2"
freq[20]=3135.96

note[21]="G#2"
freq[21]=3322.44

note[22]="A2"
freq[22]=3520

note[23]="A#2"
freq[23]=3729.31

note[24]="B2"
freq[24]=3951.07

def buzz(frequency):
        etime=time.time()+tempo
        #print(time.time())
        #print(etime)
        while time.time()<=etime:
                #print(1/float(frequency))
                GPIO.output(gpin, True)
                time.sleep(1/float(frequency))
                GPIO.output(gpin, False)
                time.sleep(1/float(frequency))
        time.sleep(tempo/10)

def note2freq(inputnote):
        for ii in range(0,24):
                if inputnote==note[ii]:
                        if ii==0:
                                time.sleep(tempo)
                        else:
                                print(freq[ii])
                                buzz(freq[ii])
        

notes=tune.split(",")
for playnote in notes:
        print(playnote)
        note2freq(playnote)

Save your project as playatune.py (File > Save As) in your Documents folder.

Now open Terminal (Menu > Accessories > Terminal) and type the following command, along with a series of notes separated by a comma:

python playatune.py "A,B,C"

The buzzer will sound these notes.

You can use the notes C,C#,D,D#,E,F,F#,G,G#,A,A#,B. If your tune requires an extra octave (i.e. an extra set of keys) then you can also use the following notes as well: C2,C#2,D2,D#2,E2,F2,F#2,G2,G#2,A2,A#2,B2. You can also create a pause by using the - symbol.

So the following command will play "Happy Birthday":

python playatune.py "C,C,D,C,F,E,-,C,C,D,C,G,F,-,C,C,C2,A,F,E,D,-,A#,A#,A,F,G