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?

 
 

 

 

 

Code

import time
from machine import Pin

# Setup
button = Pin(7, Pin.IN, Pin.PULL_DOWN)
click_count = 0
last_press_time = 0
timeout = 0.5  # 500ms window for double click

while True:
    # 1. Detect the press
    if button.value() == 1:
        click_count += 1
        
        # 2. Wait for button release (Debounce/Hold prevention)
        # Added () to button.value and fixed indentation
        while button.value() == 1:
            time.sleep(0.01)
            
        last_press_time = time.time()

    # 3. After button is released, check if the timeout has passed
    if click_count > 0:
        if (time.time() - last_press_time) > timeout:
            if click_count == 1:
                print("Single click detected")
            elif click_count >=2:
                print("Double click detected")
            else:
                print("Long press detected")    
            
            click_count = 0  # Reset counter

    time.sleep(0.01)

 

 

 

Output

Video

Add a video of the output (know more)

 

 

 

Was this helpful?
Upvote
Downvote