const int buzzerPin = 9;
int inpin = 2;
const int songLengthAmazingGrace = 33;
char notesAmazingGrace[] = "gCecedcaggCecedgegecegacggCecedc ";
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'};
// Adjusted frequencies for a different pitch
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523, 587, 659, 698, 784, 880, 988};
for (i = 0; i < numNotes; i++) {
if (names[i] == note) {
return (frequencies[i]);
}
}
return (0);
}