#define BLINK_TIME 500
int led1 = 8;
int blinkLed = 11;
bool ledState = 0;
const int buttonPin = 2;
const unsigned long debounceDelay = 50; // Adjust as needed
unsigned long lastDebounceTime = 0;
bool buttonState = HIGH; // Current debounced state
bool lastButtonState = HIGH; // Previous raw state
// Non-blocking function to detect a single click with debounce
bool isSingleClickedNonBlocking() {
bool reading = digitalRead(buttonPin);
unsigned long currentTime = millis();
static bool lastDebouncedState = HIGH; // Remember the debounced state
// Check if the raw button state has changed and the debounce time has passed
if (reading != lastButtonState) {
lastDebounceTime = currentTime;
}
if ((currentTime - lastDebounceTime) > debounceDelay) {
// Update the debounced state
if (reading != lastDebouncedState) {
lastDebouncedState = reading;
Serial.print("Button State: ");Serial.println(reading);
// Return true only on the falling edge (button press with pull-up)
if (lastDebouncedState == LOW) {
lastButtonState = reading; // Update last raw state immediately after debounce
return true;
}
}
}
// Update the last raw state for the next call
lastButtonState = reading;
return false; // No single click detected in this call
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(blinkLed,OUTPUT);
Serial.begin(9600);
}
unsigned long tNow;
bool blinkLedState=0;
void loop() {
if (isSingleClickedNonBlocking()) {
//Serial.println("Single Click Detected (Non-Blocking)!");
// Perform your single click action here
ledState = !ledState;
digitalWrite(led1,ledState);
}
if(millis()-tNow >= BLINK_TIME){
tNow = millis();
blinkLedState = !blinkLedState;
digitalWrite(blinkLed,blinkLedState);
}
// Your other non-blocking loop code here
// No blocking delays here!
}