const uint32_t TWO_SEC = 2000;
const uint32_t DEBOUNCE_TIME = 20;
const uint8_t BTN_PIN = 12;
const uint8_t LED_PIN = 8;
uint32_t prevTime = 0;
bool ledState = false;
bool checkButton() {
static uint32_t lastTime = 0;
static bool lastState = HIGH;
bool isPressed = false;
bool currentState = digitalRead(BTN_PIN);
uint32_t now = millis();
if (currentState != lastState && now - lastTime >= DEBOUNCE_TIME) {
if (!currentState) {
Serial.println("Button pressed!");
isPressed = true;
} else {
Serial.println("Button released!");
}
lastTime = now;
lastState = currentState;
}
return isPressed;
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (millis() - prevTime >= TWO_SEC) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
prevTime = millis();
}
// other stuff happens here unaffected by the blinking
bool wasPressed = checkButton();
if (wasPressed) Serial.println("Pushed...");
}