通过python/raspberry pi中的按钮实现用户输入的最大时间

通过python/raspberry pi中的按钮实现用户输入的最大时间,python,time,raspberry-pi,pycharm,Python,Time,Raspberry Pi,Pycharm,我正在努力寻找一种在嵌套的while循环中实现时间限制的方法。例如,我希望用户有一个设定的时间来按下按钮15秒。一旦达到最多三次可工作的冲床或超过时间限制,程序应中断嵌套循环。这是一段代码的一个自主钢筋混凝土车。提前谢谢 import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) button1 = 26 GPIO.setup(button1, GPIO.IN, pull_up_down=GPIO.PUD_UP) print("Wh

我正在努力寻找一种在嵌套的while循环中实现时间限制的方法。例如,我希望用户有一个设定的时间来按下按钮15秒。一旦达到最多三次可工作的冲床或超过时间限制,程序应中断嵌套循环。这是一段代码的一个自主钢筋混凝土车。提前谢谢

import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

button1 = 26

GPIO.setup(button1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print("Where do you want to go? Press once to go to the right, twice to go left or three times to go straight"
      "Wait one second inbetween clicks and 10 seconds to finish the process.")
while 1:
    clickCounter = 0
    while 1:  # Keeps track of clicks.
        if GPIO.input(button1) == 0:
            clickCounter += 1
            print("Amount of clicks: ", clickCounter)
            time.sleep(1)
        if clickCounter == 3 or x:  # Loop breaks if amount of clicks is 3 or if the time is up.
            break
    # Different outcomes based on the amount of clicks.
    if clickCounter == 0:
        print("Press the button 1-3 times.")
    elif clickCounter == 1:
        print("We're going to the right.")
        clickCounter = 0
        break
    elif clickCounter == 2:
        print("We're going to the left.")
        clickCounter = 0
        break
    elif clickCounter == 3:
        print("We're going straight.")
        clickCounter = 0
        break

您可以计算从循环开始所经过的时间,并在时间结束时退出循环

while 1:
    # Mark time at start of loop
    start_time = time.time()
    clickCounter = 0
    while 1:  # Keeps track of clicks.
        if GPIO.input(button1) == 0:
            clickCounter += 1
            print("Amount of clicks: ", clickCounter)
            time.sleep(1)      # I assume this is here for debounce
        # Calc time since start of loop
        elapsed_time = time.time() - start_time
        if clickCounter == 3 or elapsed_time >= 15:  # Loop breaks if amount of clicks is 3 or if the time is up.
            break
    # Different outcomes based on the amount of clicks.
    ....