/****************************************************************** * SparkFun Inventor's Kit * Example sketch 11 * * BUZZER * * This sketch uses the buzzer to play songs. * The Arduino's tone() command will play notes of a given frequency. * * This sketch was written by SparkFun Electronics, * with lots of help from the Arduino community. * (This sketch was originally developed by D. Cuartielles for K3) * This code is completely free for any use. * Visit http://learn.sparkfun.com/products/2 for SIK information. * Visit http://www.arduino.cc to learn about the Arduino. * * Version 2.0 6/2012 MDG * Version 2.1 9/2014 BCH *****************************************************************/ const int buzzerPin = 9; // connect the buzzer to pin 9 const int songLength = 43; // sets the number of notes of the song // Notes is an array of text characters corresponding to the notes // in your song. A space represents a rest (no tone) char notes[songLength] = { 'F','E','F','E','C','A','D','B','C','C','F','g','a','c','a','D','E','D',' ','D','C','D','C','B','b','a','b','a','g','a','F','b','a','F','b','h','F','b','h','F','C'}; // beats[] is an array of values for each note. A "1" represents a quarter-note, // "2" a half-note, and "4" a quarter-note. // Don't forget that the rests (spaces) need a length as well. int beats[songLength] = { 4,1,1,2,3,1,2,4,3,2,1,4,1,1,2,2,.5,.5,2,3,3,2,1,3,3,3,2,1,3,3,3,2,1,3,2,1,3,2,1,3,3,4}; int tempo = 230; // The tempo is how fast to play the song (beats per second). void setup() { pinMode(buzzerPin, OUTPUT); // sets the buzzer pin as an OUTPUT } void loop() { int i, duration; // for (i = 0; i < songLength; i++) // for loop is used to index through the arrays { duration = beats[i] * tempo; // length of note/rest in ms if (notes[i] == ' ') // is this a rest? delay(duration); // then pause for a moment else // otherwise, play the note { tone(buzzerPin, frequency(notes[i]), duration); delay(duration); // wait for tone to finish } delay(tempo/10); // brief pause between notes } { // We only want to play the song once, so we pause forever } // If you'd like your song to play over and over, remove the while(true) // statement above } int frequency(char note) { int i; const int numNotes = 11; // number of notes we're storing char names[numNotes] = { 'A','B', 'C', 'D', 'E', 'F', 'g','h','a', 'b', 'C' }; int frequencies[numNotes] = { 440, 466.16, 523.25, 587.33, 659.25, 698.46, 783.99, 830.61, 880, 932.33, 1046.5}; // Now we'll search through the letters in the array, and if // we find it, we'll return the frequency for that note. for (i = 0; i < numNotes; i++) // Step through the notes { if (names[i] == note) // Is this the one? { return(frequencies[i]); // Yes! Return the frequency and exit function. } } return(0); // We looked through everything and didn't find it, // but we still need to return a value, so return 0. }