#include <Arduino.h>

// D2->button->GND, D8->resistor->LED->GND.
const int buttonPin = 2;
const int ledPin = 8;
// The last immediate button reading; switches can rapidly bounce between HIGH and LOW.
int lastRaw = HIGH;
// Our accepted button state after it has remained unchanged long enough.
int stableReading = HIGH;
bool ledOn = false;
// Remember the time (in milliseconds) when the raw reading last changed.
unsigned long changedAt = 0;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int reading = digitalRead(buttonPin);
  // != means not equal. Any new raw change restarts the 30 ms stability timer.
  if (reading != lastRaw) changedAt = millis();
  // Accept a new state only after 30 ms with no raw changes AND only if it differs from the
  // accepted state.
  if (millis() - changedAt >= 30 && reading != stableReading) {
    stableReading = reading;
    // Only a confirmed press toggles the LED; releasing does not toggle it.
    if (stableReading == LOW) {
      // Flip the stored on/off state. Unlike the earlier toggle, this filters contact bounce.
      ledOn = !ledOn;
      digitalWrite(ledPin, ledOn ? HIGH : LOW);
    }
  }
  // Save the raw input so the next loop can detect another change.
  lastRaw = reading;
}
