#include "pitches.h" // Ensure you have a pitches.h file for note definitions
int tempo = 114; // Set the tempo
int buzzer = 11; // Buzzer connected to digital pin 11
int buttonPin = 7; // Button connected to digital pin 7
int buttonState = 0; // Variable to store the button state
// Define the melody (frequencies for the notes) and durations
const int melody[] = {
NOTE_E4, NOTE_F4, NOTE_G4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_D4,
NOTE_C4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_D4
};
const int noteDurations[] = {
4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4
};
void setup() {
pinMode(buzzer, OUTPUT); // Set the buzzer pin as OUTPUT
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as INPUT with pull-up resistor
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the state of the button
// If the button is pressed, play the melody
if (buttonState == LOW) { // Button pressed (active low)
playMelody();
}
}
void playMelody() {
for (int thisNote = 0; thisNote < sizeof(melody) / sizeof(melody[0]); thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote]; // Calculate note duration
tone(buzzer, melody[thisNote], noteDuration); // Play the note on the buzzer
delay(noteDuration * 1.30); // Add a small delay between notes
noTone(buzzer); // Stop the tone
}
}