Page 1 of 1

press and hold button for an input.

Posted: Wed Mar 03, 2021 5:37 pm
by Grumpy_Pig_Skin
Hi,

I want to use a push-button to activate a feature but only after it has been pressed for x amount of seconds. to prevent accidental bumps etc.

I've tried using the time.ticks_ms() but I can for the life of me get it to work.

heres a snip of the code:

Code: Select all

def manual_set_mode():
    global clock_set_mode
    global ts
    if btn0.value() == 0:
        btn0_press_time = time.ticks_ms()
        if time.ticks_diff(time.ticks_ms, btn0_press_time) > 2000:
            clock_set_mode = True
            print('clock set mode true')                                                                                                    
        if clock_set_mode == True:  

so here you can see I want to set clock_set_mode as True. only after the button has been pressed for 2 seconds... however, looking at how I've done it, it will turn Tre regardless of whether I let go of the button within that 2 second period.

If you can help that would be greatly appreciated.

Ollie

Re: press and hold button for an input.

Posted: Thu Mar 11, 2021 5:40 am
by jimmo
Grumpy_Pig_Skin wrote:
Wed Mar 03, 2021 5:37 pm
heres a snip of the code:
"time.ticks_diff(time.ticks_ms, btn0_press_time)" should be "time.ticks_diff(time.ticks_ms(), btn0_press_time)" (extra parens for ticks_ms)

I think I need to see more of the code to understand how your code works.

In general though, the approach would be something like this:

Code: Select all

clock_set_mode = False
global button_down = None
def check_button_press():
  if clock_set_mode:
    # Already detected.
    return

  if btn0.value() == 0:
    # The button is down.
    if button_down is None:
      # First time we've detected it.
      button_down = time.ticks_ms()
    else:
      # Previously detected, see if it's been down for two seconds.
      if time.ticks_diff(time.ticks_ms(), button_down) > 2000:
        clock_set_mode = True
  else:
    # The button is up, forget previous detection.
    button_down = None

Re: press and hold button for an input.

Posted: Thu Mar 11, 2021 8:12 am
by pythoncoder
@Grumpy_Pig_Skin If you are prepared to learn the basics of uasyncio this is a solved problem. The Pushbutton class provides for a callback after a long button press. "Long" defaults to 1 second but can be changed.