// Define the pin for the buzzer
const int buzzerPin = 12;
// Define the musical notes and their frequencies
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// Define the duration of each musical note (in milliseconds)
#define WHOLE 1000
#define HALF 500
#define QUARTER 250
#define EIGHTH 125
// Define the melody and the corresponding durations
int melody[] = {
NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, 0, NOTE_B4, NOTE_C4
};
int durations[] = {
4, 4, 4, 4, 4, 4, 4, 4
};
void setup() {
// Set the buzzer pin as an output
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// Play the melody
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = WHOLE / durations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
delay(noteDuration * 1.30); // Add a slight delay between notes
noTone(buzzerPin); // Stop the tone playing on the buzzer
}
// Repeat the melody after a short delay
delay(2000);
}