A timer that restarts on a trigger Python - how to restart?

Viewed 107

Bit of a newbie so bear with:

I am trying to make a crude 60s timer that is reset and starts again on the rising edge of a trigger (ie when a gate goes high). The problem I have is that it won't reset and restart unless the timer has completed (ie reached zero). How do I interrupt the while loop and get it to start again?

Here is my code:

import keyboard
import time

t=60

last = False
current = False

while True:
    current = keyboard.is_pressed('space') # triggered when space bar is pressed
    if last == 0 and current == 1: 
        while t>=0:
            print(t)
            t-=1
            time.sleep(1)
    last = current # reset
3 Answers

This is my suggestion. The problem is, that time.sleep is blocking, so when it's sleeping you cannot break it by pressing escape. You will have to spam the escape button, but it works.

import keyboard
import time

t=60

last = False
current = False

while True:
    current = keyboard.is_pressed('space') # triggered when space bar is pressed
    if last == 0 and current == 1: 
        while t>=0:
            if keyboard.is_pressed('escape'):
                t = 60
                last = False
                current = False
                print("Timer stopped.")
                break
            print(t)
            t-=1
            time.sleep(1)
    last = current # reset

Sample output/test:

60
59
58
57
56
60
59
58
57
56
60
59
60
59
58

Try this:

import time
import keyboard
x=60
while True:
    try:
        if keyboard.is_pressed('space'):
            x=60
            print(f"Timer reset to {x}")
        elif keyboard.is_pressed('space'):
            break
        else:
            print(f"{x} seconds left")
            time.sleep(1)
            x-=1
    except Exception:
        pass

To suggest a solution without break:

import keyboard
import time

last = 0
current = 0

while True:
    t=60
    current = keyboard.is_pressed('space') # triggered when space bar is pressed
    if last == 0 and current == 1:
        current = 0
        while t>=0 and current == 0:
            print(t)
            t-=1
            time.sleep(1)
            current = keyboard.is_pressed('space')
    last = current # reset

Not sure how you want to manage long presses here. If the spacebar stays pressed for more than one second, the timer will reset several times in (technically) one keypress.

Related