The Circuit Playground has a very simple speaker. It basically can just play one tone at a time. However, simple melodies can be created by stringing together multiple tones of different frequencies. This approach is covered here:
In each of these examples, two arrays are used to store the melody. The first holds the actual notes and the second specifies the duration for each note.
For example, from the Arduino ToneMelody example:
// notes in the melody: int 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.: int tempo[] = { 4, 8, 8, 4, 4, 4, 4, 4 };
To play this back, we simply loop through the array and play each note. For the Circuit Playground, that would look something like this:
for (int n=0; n<numberOfNotes; n++) { int noteDuration = 1000 / tempo[n]; CircuitPlayground.playTone(melody[n], noteDuration); delay(0.3*noteDuration); }
We first compute the actual note duration based on the tempo value. Then we play it. A small delay is added between each note to make them distinguishable.
Pitch Definitions
Note how in the melody array we used values that looked like NOTE_C4
. This isn't some kind of built in Arduino magic. It is simply a variable that has been defined with the frequency value of the note C.
This is discussed further in the links provided above. The key thing to remember here is that you will need to make sure to include the pitches.h file with your sketch. That is where all of these values are defined. It is nothing but a file with a bunch of lines that look like:
#define NOTE_C4 262
And that's the line that defines NOTE_C4
as having a value of 262
.
Sample Melody Sketch
Here's a sketch which plays the simple melody from the Arduino example whenever either Circuit Playground button is pressed.
It's a zip file which contains both the sketch along with the pitches.h file that defines the notes. So download it, unzip it, and load the sketch to the Circuit Playground. You'll know you got it working when you hear Shave and a Haircut.
Text editor powered by tinymce.