#include <Arduino.h>

// Release between presses; contact bounce can cause double toggles.
const int buttonPin = 2;
const int ledPin = 8;
// Remember the previous button reading to detect a change, not just a held-down button.
int lastReading = HIGH;
// bool stores true or false; this remembers whether we want the LED on.
bool ledOn = false;

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

void loop() {
  int reading = digitalRead(buttonPin);
  // && means AND: detect the transition from released (HIGH) to pressed (LOW).
  if (lastReading == HIGH && reading == LOW) {
    // ! means NOT: switch true to false or false to true.
    ledOn = !ledOn;
    // The ternary ? : chooses HIGH when ledOn is true and LOW otherwise.
    digitalWrite(ledPin, ledOn ? HIGH : LOW);
  }
  // Save this reading for the next loop. Mechanical bounce can still cause extra toggles.
  lastReading = reading;
  delay(20);
}
