const int buzzerPin = 9;
int inpin=2;
const int songLengthAmazingGrace = 33;
char notesAmazingGrace[] = "gCECEDCaggCECEDGEGECEDCaggCECEDC ";
int beatsAmazingGrace[] = {2,4,1,1,4,2,4,2,4,2,4,1,1,4,2,10,2,4,1,1,4,2,4,2,4,2,4,1,1,4,2,8,8};
int tempo = 300;
void setup()
{
pinMode(buzzerPin, OUTPUT);
pinMode(inpin, INPUT);
}
void loop()
{
if (digitalRead(inpin)==HIGH)
{
play_music();
}
}
void play_music()
{
int i, duration;
for (i = 0; i < songLengthAmazingGrace; i++)
{
duration = beatsAmazingGrace[i] * tempo;
if (notesAmazingGrace[i] == ' ')
{
delay(duration);
}
else
{
tone(buzzerPin, frequency(notesAmazingGrace[i]), duration);
delay(duration);
}
delay(tempo/10);
}
}
int frequency(char note)
{
int i;
const int numNotes = 14;
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B' };
int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494};
for (i = 0; i < numNotes; i++)
{
if (names[i] == note)
{
return(frequencies[i]);
}
}
return(0);
}