All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

int pushButton = 12;
int LED = 7;

int lastState = HIGH;

unsigned long pressStart = 0;   
unsigned long lastRelease = 0;   
int clickCount = 0;   
bool longReported = false;    

const unsigned long LONG_PRESS = 800;    
const unsigned long DOUBLE_CLICK = 400;  

void setup() {
    pinMode(pushButton, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    digitalWrite(LED, LOW); 
}

void loop() {
    int state = digitalRead(pushButton); 

    if (state == LOW && lastState == HIGH) {
        pressStart = millis();    
        longReported = false;  
        digitalWrite(LED, HIGH);  
    }

       if (state == HIGH && lastState == LOW) {
        unsigned long pressDuration = millis() - pressStart;

        if (pressDuration >= LONG_PRESS) {
          
            Serial.println("Long Press");
            longReported = true;
            clickCount = 0;
        } else {
            // short press:
            clickCount++;
            lastRelease = millis();
        }

        digitalWrite(LED, LOW); 
    }

 
    if (state == LOW && !longReported) {
        if (millis() - pressStart >= LONG_PRESS) {
            Serial.println("Long Press");
            longReported = true;
            clickCount = 0;   
           
        }
    }

    if (clickCount > 0) {
        if (millis() - lastRelease > DOUBLE_CLICK) {
            if (clickCount == 1) {
                Serial.println("Single Click");
            } else {
                Serial.println("Double Click");
            }
            clickCount = 0; 
        }
    }

    lastState = state;
    delay(10); // 
}

 

 

 

Output

Video

Add a video of the output (know more)

 

 

 

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!