#include "pitches.h"
#define REST 0
const int buttonPin = 7;
const int buzzerPin = 6;
bool buzzerState = false; // Fix: added missing semicolon
int buttonState = 0;
int lastButtonState = 0;
bool playing = false;
int tempo = 120;
int C = 11, D = 9, E = 10, FS = 8, G = 13, B = 12;
int melody[] = {
NOTE_B4, 8, NOTE_C4, 8, NOTE_D4, 8, NOTE_FS5, 8, NOTE_G5, 8,
NOTE_E5, 8, NOTE_C4, 8, NOTE_D4, 8, NOTE_E5, 8, NOTE_G5, 8,
NOTE_B5, 8, NOTE_FS5, 8, NOTE_D4, 8, NOTE_E5, 8, NOTE_FS5, 8
};
int notes = sizeof(melody) / sizeof(melody[0]) / 2;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT);
pinMode(E, OUTPUT);
pinMode(FS, OUTPUT);
pinMode(G, OUTPUT);
pinMode(B, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && lastButtonState == LOW) {
playing = !playing;
delay(50); // Basic debounce to prevent multiple triggers
}
lastButtonState = buttonState;
if (playing) {
int wholenote = (60000 * 4) / tempo;
int noteDuration;
for (int i = 0; i < notes * 2; i += 2) {
int pitch = melody[i];
noteDuration = wholenote / melody[i + 1];
turnOnLED(pitch);
tone(buzzerPin, pitch, noteDuration * 0.9);
delay(noteDuration);
noTone(buzzerPin);
turnOffAllLEDs();
if (!playing) break; // Stop instantly if button is pressed again
}
} else {
noTone(buzzerPin);
turnOffAllLEDs();
}
}
// LED control functions
void turnOnLED(int pitch) {
turnOffAllLEDs();
if (pitch == NOTE_C4 || pitch == NOTE_C5) digitalWrite(C, HIGH);
else if (pitch == NOTE_D4 || pitch == NOTE_D5) digitalWrite(D, HIGH);
else if (pitch == NOTE_E5 || pitch == NOTE_E6) digitalWrite(E, HIGH);
else if (pitch == NOTE_FS5 || pitch == NOTE_FS6) digitalWrite(FS, HIGH);
else if (pitch == NOTE_G5 || pitch == NOTE_G6) digitalWrite(G, HIGH);
else if (pitch == NOTE_B4 || pitch == NOTE_B5) digitalWrite(B, HIGH);
}
void turnOffAllLEDs() {
digitalWrite(C, LOW);
digitalWrite(D, LOW);
digitalWrite(E, LOW);
digitalWrite(FS, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
}