Python-3运行While循环X时间

时间:2019-06-17 21:33:14

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

我的程序用于树莓派项目,在该项目中,用户可以选择在按下按钮时记录消息。我当前的目标是让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

我尝试了几种不同的方法,进行了很多谷歌搜索,并研究了类似的问题,但是没有一个起作用。

1 个答案:

答案 0 :(得分:0)

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)