int led1 = 8;
bool ledState = 0;
const int buttonPin = 2;
const unsigned long debounceDelay = 50;
const unsigned long longPressTime = 1000; // Milliseconds for a long press
unsigned long lastDebounceTime = 0;
unsigned long buttonPressStartTime = 0;
bool buttonState = HIGH;
bool lastButtonState = HIGH;
bool longPressDetected = false;
unsigned long lastLedUpdate;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
bool reading = digitalRead(buttonPin);
unsigned long currentTime = millis();
// Non-blocking debounce
if (reading != lastButtonState) {
lastDebounceTime = currentTime;
}
if ((currentTime - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) { // Button pressed
buttonPressStartTime = currentTime;
longPressDetected = false; // Reset the flag when pressed
} else { // Button released
if (longPressDetected) {
Serial.println("Long Press Released!");
// Perform actions that happen *after* a long press release (optional)
longPressDetected = false; // Reset for the next long press
} else {
Serial.println("Short Press (Ignored)");
// Optionally, you could add short press behavior here if needed later
}
}
}
}
lastButtonState = reading;
// Check for long press while the button is held down
if (buttonState == LOW && (currentTime - buttonPressStartTime > longPressTime) && !longPressDetected) {
Serial.println("Long Press Detected!");
// Perform your long press action here (occurs once when the threshold is met)
longPressDetected = true;
}
if(longPressDetected == true && millis()-lastLedUpdate >=1000){
//longPressDetected = false;
lastLedUpdate = millis();
ledState = !ledState;
digitalWrite(led1,ledState);
}
}