Toggle once per stable press
const byte buttonPin = 2;
const unsigned long debounceMs = 30;
bool lastRaw = HIGH;
bool stable = HIGH;
bool ledOn = false;
unsigned long changedAt = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
const unsigned long now = millis();
const bool raw = digitalRead(buttonPin);
if (raw != lastRaw) {
changedAt = now;
lastRaw = raw;
}
if (now - changedAt >= debounceMs && raw != stable) {
stable = raw;
if (stable == LOW) {
ledOn = !ledOn;
digitalWrite(LED_BUILTIN, ledOn);
}
}
}
Every raw transition restarts the stability timer. Only a new stable value becomes an event. There is no delay, so other short tasks can run in the same loop. The 30 ms interval is an example, not a universal switch specification.
Acceptance checks: A tap toggles once. A two-second hold also toggles once. Release does not toggle. Ten deliberate presses produce ten toggles. If it never changes, check the button orientation; if idle reads LOW, inspect wiring to ground.
Extension: Record the time of the debounced press and subtract it at release to distinguish a short click from a long hold. Decide whether a long hold should suppress the short-click action.
A useful reminder
Clean Code: Use descriptive constants instead of magic numbers
Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.