Sample code for playing a melody on a piezo buzzer, adapted from SquareWear example code.
Also, check out this example that plays the Super Mario theme song!
1 x piezo buzzer
1 x 1k ohm resistor
1 x Arduino Uno
1 x breadboard
jumper wires
In this sketch, we use pin 3 for output; you can use any PWM pin (denoted by a ~).
/*
Melody
Plays a melody using piezo buzzer on digital pin 9
Written by Shani Mensing, edited by Audrey St. John
From example code in the public domain.
http://arduino.cc/en/Tutorial/Tone
*/
// the pin we will use for output
#define BUZZER_PIN 3
// notes for the song. A space represents a rest
char song[] = "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc ";
// the number of notes in the song
int songLength = 48;
// beats per note
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
// speed of song
int tempo = 300;
// convenience notes means we don't need Pitches.h
// names of the notes
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
// corresponding tones for C4 - B4, C5 (looked up values from Pitches.h)
int tones[] = { 262, 295, 330, 349, 392, 440, 494, 523 };
// number of notes
int numberConvenienceNotes = 8;
// play the song using the variables: song, songLength, beats
void playSong()
{
// for each note in the melody:
for (int noteIndex = 0; noteIndex < songLength; noteIndex++)
{
// if it's a space
if (song[noteIndex] == ' ')
{
// rest
delay( beats[noteIndex] * tempo/5);
}
// otherwise it's the name of a note
else
{
// play the note at that index for the specified time
playNote(song[noteIndex], beats[noteIndex] * tempo);
}
// pause between notes
delay(tempo);
}
}
// play the tone corresponding to the note name
void playNote(char noteName, int duration)
{
// loop through the names
for (int i = 0; i < numberConvenienceNotes; i++)
{
// if we found the right name
if (names[i] == noteName)
{
// play the tone at the same index
tone( BUZZER_PIN, tones[i], duration);
// don't bother looking through the rest of the names
break;
}
}
}
/**
* The code in this special method is executed
* once when the microcontroller is turned on
* (or the program is uploaded).
**/
void setup()
{
// play the song at the beginning
playSong();
}
/**
* The code in this special method is constantly executed
* after setup has occurred.
**/
void loop()
{
// it will be annoying to constantly hear the melody,
// so let's do nothing!
}