const int buttonPin = 6; // Button connected to pin 6
const int debounceDelay = 50; // Debounce time in milliseconds
const int holdTime = 1000; // Hold time in milliseconds
unsigned long lastDebounceTime = 0;
unsigned long buttonPressTime = 0;
bool buttonState = HIGH;
bool lastButtonState = HIGH;
bool isHolding = false;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
}
void loop() {
bool reading = digitalRead(buttonPin);
// Debounce handling
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// Detect button press
if (reading == LOW && buttonState == HIGH) {
buttonPressTime = millis();
isHolding = false;
Serial.println("Press Down");
}
// Detect hold
if (reading == LOW && (millis() - buttonPressTime) > holdTime && !isHolding) {
isHolding = true;
Serial.println("Hold");
}
// Detect button release (Open)
if (reading == HIGH && buttonState == LOW) {
if (!isHolding) {
Serial.println("Open");
}
isHolding = false;
}
buttonState = reading;
}
lastButtonState = reading;
}