const int BTN_PIN = 10;
const int GRN_LED_PIN = 12;
const int RED_LED_PIN = 11;
int oldBtnState = HIGH; // pullup
int ledState = HIGH; // start with green on
// function returns true if button is pressed
bool checkButton() {
bool isPressed = false;
int btnState = digitalRead(BTN_PIN);
if (btnState != oldBtnState) {
oldBtnState = btnState;
if (btnState == LOW) {
isPressed = true;
Serial.println("Button pressed");
}
delay(20); // debounce
}
return isPressed;
}
void showLedState() {
Serial.print("'ledState' is now: ");
Serial.println(ledState ? "HIGH" : "LOW");
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(GRN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
digitalWrite(GRN_LED_PIN, ledState);
showLedState();
}
void loop() {
bool isPushed = checkButton();
if (isPushed) {
ledState = !ledState;
showLedState();
digitalWrite(GRN_LED_PIN, ledState);
digitalWrite(RED_LED_PIN, !ledState);
}
}