【问题标题】:Python-3 Run a While Loop for X Amount of Time [duplicate]Python-3运行一个While循环X时间[重复]
【发布时间】:2019-06-17 21:33:14
【问题描述】:

我的程序用于一个树莓派项目,在该项目中,我为用户提供了在按下按钮时记录消息的选项。我目前的目标是让一个while循环通过按下按钮然后退出循环来提供录制选项,如果5秒内没有按下它就会退出循环。

我的代码如下所示:

w = True
while w:
    # if the button on the pi is pressed once this while loop begins,
    if GPIO.input(17) == 0:
        print ("Button Pressed")
        sleep(2)
        print ("Explaining recording instructions")
        pygame.mixer.Sound.play(record_s)
        sleep(8)
        print ("Recording")
        record_audio()
        # Exit the loop once message is recorded by pressing the button once more
        if GPIO.input(17) == 0:
            w = False
    # If the button is not pressed for 5 seconds,
    elif sleep(5):
        print ("No input")
        # Exit the loop
        w= False

我尝试了几种不同的方法,进行了大量的谷歌搜索并查看了类似的问题,但没有一个有效。

【问题讨论】:

  • 在开始循环之前将时间存储到变量start = time.time (),然后检查当前时间减去开始时间if time.time() - start > 5:
  • 谁能给我解释一下elif sleep(5):? sleep 随着时间的推移返回什么?
  • 调用 time.sleep (5) 在 5 秒后返回 None,所以在 if 中,它永远不会是 True

标签: python python-3.x raspberry-pi


【解决方案1】:
def run():
    while True:
    # if the button on the pi is pressed once this while loop begins,
        if GPIO.input(17) == 0:
            print ("Button Pressed")

        print ("Explaining recording instructions")
        pygame.mixer.Sound.play(record_s)
        sleep(8)
        print ("Recording")
        record_audio()
        # Exit the loop once message is recorded by pressing the button once more
        if GPIO.input(17) == 0:
            break

def main():
    t = threading.Thread(target=run)
    t.daemon = True
    t.start()
    time.sleep(5)

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多