Playing a Melody

We will use the speaker on the Circuit Playground Express to create a melody by playing a series of simple tones. We will store the actual notes of the melody in one tuple and the length of each note in another.

For example, here's a short little melody:

Download: file
        # notes in the melody:
melody = (
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
)

# note durations: 4 = quarter note, 8 = eighth note, etc.:
tempo = (
  4, 8, 8, 4, 4, 4, 4, 4
)
  
  

To play this back, we simply loop through the tuple and play each note. For the Circuit Playground, that would look something like this:

Download: file
    for i in range(len(melody)):
    note_duration = 1 / tempo[i]
    note = melody[i]
    if note == 0:
        time.sleep(note_duration)
    else:
        cpx.play_tone(note, note_duration)
  

We first compute the actual note duration based on the tempo value. We then check if the note is 0, which indicates a rest. If it is, we don't play anything and just sleep. Otherwise, we play the note.

Pitch Definitions

Note how in the melody array we used values that looked like NOTE_C4. This isn't some kind of built in CircuitPython magic. It is simply a variable that has been defined with the frequency value of the note C.

This information is stored in a separate file called pitches.py which you will need to place on your Circuit Playground Express. It is included in the zip file with the rest of the code. That is where all of these values are defined. It is nothing but a file with a bunch of lines that look like:

Download: file
NOTE_C4  = 262

And that's the line that defines NOTE_C4 as having a value of 262.

Sample Melody

Here's a set of files which plays the simple melody from the example above whenever either Circuit Playground button is pressed.

It's a zip file which contains both the main program play_melody.py along with the pitches.py file that defines the notes. So download it,unzip it, and copy both files to your Circuit Playground Express. You'll know you got it working when you hear Shave and a Haircut.

Be sure to change the name of play_melody.py to main.py so the program will run when you press reset.

This guide was first published on Apr 05, 2017. It was last updated on Apr 05, 2017. This page (Playing a Melody) was last updated on Aug 16, 2019.