int buttonState;
int lastButtonState = HIGH; // To store the last button state
int buzzerPin = 4;
int frequency = 0; // Starting frequency
const int fadeAmount = 5; // Amount to fade the sound
bool buzzerOn = false; // Buzzer state
void setup() {
pinMode(2, INPUT_PULLUP); // Set pin 2 as input with pull-up
pinMode(buzzerPin, OUTPUT); // Set pin 4 as output
}
void loop() {
buttonState = digitalRead(2); // Read the button state
// Check for a button press (transition from HIGH to LOW)
if (buttonState == LOW && lastButtonState == HIGH) {
buzzerOn = !buzzerOn; // Toggle buzzer state
frequency = buzzerOn ? 0 : frequency; // Reset frequency if turning off
delay(50); // Debounce delay
}
lastButtonState = buttonState; // Update the last button state for the next loop
// If the buzzer is on, increase the frequency
if (buzzerOn) {
if (frequency < 2000) {
frequency += fadeAmount; // Increase frequency
tone(buzzerPin, frequency); // Play tone
delay(100); // Control speed of fading
}
} else {
// If the buzzer is off, decrease the frequency
if (frequency > 0) {
frequency -= fadeAmount; // Decrease frequency
tone(buzzerPin, frequency); // Play tone
delay(100); // Control speed of fading
} else {
noTone(buzzerPin); // Stop the buzzer if frequency is zero
}
}
}