const int buzzerPin = 26; // Using GPIO 13 for the buzzer (you can choose any available GPIO pin)
const int inpin = 2; // Using GPIO 12 for the input button (you can choose any available GPIO pin)
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;
bool buttonPressed = false;
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(inpin, INPUT);
}
void loop() {
static unsigned long lastDebounceTime = 0;
static unsigned long debounceDelay = 50;
int reading = digitalRead(inpin);
// Check if button press state changed and debounce
if (reading == HIGH && !buttonPressed && (millis() - lastDebounceTime) > debounceDelay) {
buttonPressed = true;
lastDebounceTime = millis();
play_music(); // Play music when button is pressed
}
else if (reading == LOW) {
buttonPressed = false; // Reset button state when released
}
}
void play_music() {
int duration;
for (int i = 0; i < songLengthAmazingGrace; i++) {
duration = beatsAmazingGrace[i] * tempo;
if (notesAmazingGrace[i] == ' ') {
delay(duration);
}
else {
int freq = frequency(notesAmazingGrace[i]);
if (freq > 0) {
ledcWriteTone(0, freq); // Play the note on channel 0
}
delay(duration);
ledcWriteTone(0, 0); // Stop the tone after the note duration
}
delay(tempo / 10); // Small pause between notes
}
}
int frequency(char note) {
int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494};
char names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B'};
for (int i = 0; i < 14; i++) {
if (names[i] == note) {
return frequencies[i];
}
}
return 0; // Return 0 if no match found
}