// https://wokwi.com/projects/380600410686023681
// https://forum.arduino.cc/t/storing-button-state/1185825

const int  buttonPin = 2;    // the pin that the pushbutton to ground
const int ledPin = 13;       // the pin where an LED and series 1K resistor to ground is attached

int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int ledState = 0;            // LED starts off. non-zero will mean on

void setup() {
  // initialize serial communication:
  Serial.begin(115200);

  // initialize the button pin as a input, using the internal pull-up - pressed switch reads LOW:
  pinMode(buttonPin, INPUT_PULLUP);

  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
}

void loop() {


// INPUT
  // read the pushbutton input pin:
  buttonState = !digitalRead(buttonPin);


// PROCESS
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // the state has changed, check what it is now
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      Serial.println("switch is pressed.");

      ledState = !ledState;   // and toggle the LED state
    } 
    else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("                 switch is released"); 
    }
  }
  // update the last state for next time through the loop
  lastButtonState = buttonState;


// OUTPUT
  digitalWrite(ledPin, ledState ? HIGH : LOW);

  delay(50);   // poor man's debounce - run the loop way slower than the button bounce.
}