// State change toggle

const int LED_PIN = 9;
const int BTN_PIN = 10;

bool oldBtnState = true; // INPUT_PULLUP idles high
bool state = false;

bool checkButton()  {
  bool isButtonPressed = false;
  
  int btnState = digitalRead(BTN_PIN);
  if (btnState != oldBtnState)  {
    oldBtnState = btnState;
    if (btnState == LOW)  {
      isButtonPressed = true;
      Serial.println("Button pressed");
    } else  {
      Serial.println("Button released");
    }
    delay(20);  // for debounce
  }
  return isButtonPressed;
}

void setup() {
  Serial.begin(115200);
  pinMode(BTN_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  bool pressed = checkButton();
  if (pressed)  state = !state;
  digitalWrite(LED_PIN, state);
}