//Set the buzzer, green LED, and red LED pin numbers.
#define BUZZER_PIN 2
#define GREEN_LED_PIN 3
#define RED_LED_PIN 4
//Set up arrays for the melody notes.
int melody[] = {
261, 196, 196, 220, 196, 0,
247, 261
};
//Set up arrays for the note duration.
int noteDuration[] = {
4, 4, 4, 4, 4, 4,
4, 4
};
//Set the following pins as output pins.
void setup() {
pinMode(BUZZER_PIN, OUTPUT); //Sound Ouput(Buzzer sound)
pinMode(GREEN_LED_PIN, OUTPUT); //Visual Output(Green LED light)
pinMode(RED_LED_PIN, OUTPUT); //Visual Output(Red LED light)
}
//Loops the melody by performing each code inside.
void loop() {
for (int i = 0; i < 8; i++) {
int noteDurationMs = 1000 / noteDuration[i]; //Calculates note duration in milliseconds
tone(BUZZER_PIN, melody[i], noteDurationMs); //Activates the buzzer
digitalWrite(GREEN_LED_PIN, HIGH); //Turns on the green LED
digitalWrite(RED_LED_PIN, LOW); //Turns off the red LED
delay(noteDurationMs); //Pause for note duration
noTone(BUZZER_PIN); //Turn off buzzer
digitalWrite(GREEN_LED_PIN, LOW); //Turns off the green LED
digitalWrite(RED_LED_PIN, HIGH); //Turns on the red LED
delay(noteDurationMs); //Pause for note duration
}
}