Playing a Scale

For the first part of this lesson, the only thing on the breadboard is the Piezo buzzer. One pin of the piezo sounder goes to GND connection and the other to digital pin 12.

Program your Arduino with the following sketch:

/*
Adafruit Arduino - Lesson 10. Simple Sounds
*/

int speakerPin = 12;

int numTones = 10;
int tones[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440};
//            mid C  C#   D    D#   E    F    F#   G    G#   A

void setup()
{
  for (int i = 0; i < numTones; i++)
  {
    tone(speakerPin, tones[i]);
    delay(500);
  }
  noTone(speakerPin);
}

void loop()
{
}

To play a note of a particular pitch, you specify the frequency. See the following section on sound. The different frequencies for each note are kept in an array. An array is like a list. So, a scale can be played by playing each of the notes in the list in turn.

The 'for' loop will count from 0 to 9 using the variable 'i'. To get the frequency of the note to play at each step, we use 'tone[i]'. This means, the value in the 'tones' array at position 'i'. So, for example, 'tones[0]' is 261, 'tones[1]' is 277 etc.

The Arduino command 'tone' takes two parameters, the first is the pin to play the tone on and the second is the frequency of the tone to play.

When all the notes have been played, the 'noTone' command stops that pin playing any tone.

We could have put the tone playing code into 'loop' rather than 'setup', but frankly the same scale being played over and over again gets a bit tiresome. So in this case, 'loop' is empty.

To play the tune again, just press the reset button.

Last updated on 2015-05-04 at 04.27.11 PM Published on 2012-12-12 at 01.54.02 PM