Timeout in Python

444 views Asked by At

I am currently programming what can be described as a 1-dimensional pong game with LEDs using a raspberry pi. I am trying to accomplish this using the gpiozero library. What I want is to implement something where once the led is on I start a timer and if a button is not pressed before said timer it breaks from the loop.

I would like to do something along the lines of:

while True:
  led.on()
  if button.value != 1 (in t seconds):
    break
  led.off()

but I have no idea how to implement the (in t seconds). It is important that I can control what happens on timeout because I plan on having it call a function that determines the winner.

SOLUTION: I figured there is a way to detect if the LED is on so I just did

while led.value == 1:
  if button.press == 1:
    press = 1

if press ==1:
  continue
else:
  break
1

There are 1 answers

1
AudioBubble On

You can use time.time() like this:

import time

start = time.time()
tseconds = 2
while True:
    print("led.on")
    now = time.time()
    # if button.value != 1.. your conditions
    if not now  - start > tseconds:
        print(now - start)
    else:
        break
print("lead.off")