9. Single Double Click and Long Press Detection

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

How do you plan to solve it?

 We connect the switch to one GPIO pin and a ground. We use pull-up Resistors, to make sure that when the switch is pressed, it indicates a LOW. Using delay, we can figure out if it was a single press, a double press or a long press.
 

 

 

 

Code

/*Paste your code here*/

int buttonPin = 7;

void setup() {
    pinMode(buttonPin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(buttonPin) == LOW) {
        delay(30); // debounce

        if (digitalRead(buttonPin) == LOW) {
            unsigned long pressStart = millis();

            // Wait until button is released
            while (digitalRead(buttonPin) == LOW);

            unsigned long pressDuration = millis() - pressStart;

            if (pressDuration > 1000) {
                Serial.println("Long Press Detected");
            } 
            else {
                // Check if another press follows quickly
                delay(250); // "double press" window
                if (digitalRead(buttonPin) == LOW) {
                    delay(30); // debounce
                    if (digitalRead(buttonPin) == LOW) {
                        Serial.println("Double Press Detected");
                        while (digitalRead(buttonPin) == LOW); // wait release
                    }
                } else {
                    Serial.println("Single Press Detected");
                }
            }
        }
    }
}

 

 

 

Output

Video

Add a video of the output (know more)

 

Image

 

 

Was this helpful?
Upvote
Downvote