int speakerPin = 9; // Pin for the speaker
int buttonPin = 7; // Pin for the button
int buttonState = 0; // Variable to store the button state
void setup() {
pinMode(speakerPin, OUTPUT); // Set speaker pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the button state
if (buttonState == HIGH) { // If button is pressed
playMelody(); // Call the function to play a melody
} else {
noTone(speakerPin); // Stop the sound if button is not pressed
}
}
void playMelody() {
tone(speakerPin, 440, 500); // Play A4 (440Hz) for 500ms
delay(500); // Wait for the note to finish
tone(speakerPin, 494, 500); // Play B4 (494Hz) for 500ms
delay(500);
tone(speakerPin, 523, 500); // Play C5 (523Hz) for 500ms
delay(500);
tone(speakerPin, 587, 500); // Play D5 (587Hz) for 500ms
delay(500);
tone(speakerPin, 659, 500); // Play E5 (659Hz) for 500ms
delay(500);
}