All submissions

Single Double Click and Long Press Detection

Solving Approach

To solve this activity, I connected a push-button switch to one of the GPIO pins of the microcontroller with a pull-down resistor so that the pin stays LOW when the button is not pressed. In the Arduino code, I used the millis() function to measure the timing of button presses.

  • For single click, the button is pressed and released once within a short time window.
  • For double click, I checked if two presses happen close together within a set interval (for example, 400 ms).
  • For long press, I measured if the button stayed held down longer than a threshold (for example, 1 second).

By comparing the press and release times, the program can decide which type of action was made. Then, I used Serial.println() to display the action in the Serial Monitor.

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

When I tested the program in the Arduino IDE serial terminal, the outputs looked like this depending on how I pressed the button:

 

Single Click Detected Double Click Detected Long Press Detected

So the microcontroller was able to correctly recognize single click, double click, and long press actions, just like a computer mouse.

Video

Add a video of the output (know more)

PHOTO OF OUTPUT

 

 

Submit Your Solution

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