0

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
  • 2
    It depends on the exact behavior you want, but you could just use `time.time` to save the start time before the loop, then check `time.time` in the loop, and break if the difference is greater than `t`. That would be using a busy wait though, which isn't efficient. If you have access to `asyncio`, it has timeout mechanisms too I believe. – Carcigenicate Sep 27 '20 at 16:19

1 Answers1

0

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")
  • This doesn't quite work because it only check for the button value when it is called meaning that if the button is pressed and released before the timer ends it will not register resulting in a really narrow window assuming one is not just holding the button. – madamepsychosis Sep 27 '20 at 16:51