/*
Forum: https://forum.arduino.cc/t/button-pressed-when-not-pressed-code-bug/1433858/5
Wokwi: https://wokwi.com/projects/457651223100920833
2026/03/05
ec2021
This is one out of thousands of possible solutions.
An LED is used instead of a buzzer as the Wokwi buzzer is a passive device that requires
the tone library (or at least additional code to create a sound).
The "Debouncing" si inherent as the code does not react to bouncing
while buzzerActive is true (which happens with the first falling edge of the button signal).
So one can keep the buzzer buzzing by continousely pressing the button without releasing it.
*/
constexpr byte buttonPin {12} ;
constexpr byte buzzerPin {13};
constexpr unsigned long buzzerInterval {500}; // The time in milliseconds the buzzer shall be active after being triggered
unsigned long triggerTime = 0; // The time when the button switches from HIGH to LOW
boolean buzzerActive = false;
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int buttonTest = digitalRead(buttonPin);
if (buttonTest == LOW && !buzzerActive)
{
buzzerActive = true;
triggerTime = millis();
digitalWrite(buzzerPin, HIGH);
Serial.println("ButtonActive");
};
if (buzzerActive && millis() - triggerTime >= buzzerInterval)
{
buzzerActive = false;
Serial.println("ButtonDeactive");
digitalWrite(buzzerPin, LOW);
}
}