int ledPin = 13; // Pin for the LED
int buzzerPin = 9; // Pin for the buzzer
int buttonPin = 1; // Pin for the button
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
}
int nowButtonState, oldButtonState = HIGH; // Button state variables
void loop() {
nowButtonState = digitalRead(buttonPin); // Read the button state
// Check if the button was pressed (transition from HIGH to LOW)
if (nowButtonState == LOW && oldButtonState == HIGH) {
digitalWrite(ledPin, !digitalRead(ledPin)); // Toggle LED state
// If LED is ON, turn on the buzzer
if (digitalRead(ledPin) == HIGH) {
tone(buzzerPin, 1000); // Start buzzer with 1kHz frequency
}
// If LED is OFF, turn off the buzzer
else {
noTone(buzzerPin); // Stop the buzzer
}
}
delay(10); // Small delay for debouncing
oldButtonState = nowButtonState; // Update the old button state
}