5. You want to detect a single button press and toggle an LED state only once per press using software debounce. Which approach below correctly implements this behavior?
const int buttonPin = 4;
const int ledPin = 13;
int ledState = LOW;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != lastButtonState) {
lastButtonState = reading;
if (lastButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.println(ledState ? "LED ON" : "LED OFF");
}
}
}
}