继续运行循环,直到使用gpiozero按下按钮-未按下按钮

时间:2019-03-26 23:04:23

标签: python raspberry-pi gpiozero

我在树莓派上有一些python代码,我想运行它们并进行循环,直到按下按钮为止。

button.wait_for_press()不适合,因为它会暂停程序直到运行,但是我已经尝试了一下,看看硬件是否正常工作。

def shutterPressed():
    global shutterHasBeenPressed
    shutterHasBeenPressed = True

def main():

    """
    Main program loop
    """

    #start camera preview
    camera.start_preview(resolution=(SCREEN_W, SCREEN_H))

    #Display Intro screens
    intro_image_1 = REAL_PATH + '/assets/intro_1.png'
    intro_image_2 = REAL_PATH + '/assets/intro_2.png'
    overlay_1 = overlay_image(intro_image_1, 0, 3)
    overlay_2 = overlay_image(intro_image_2, 0, 4)

    #Wait for button press
    i = 0
    blink_speed = 10

    button.when_pressed = shutterPressed

    while True:
        global shutterHasBeenPressed
        shutterHasBeenPressed = False
        #Stay in loop until button is pressed
        if shutterHasBeenPressed is False:
            i += 1
            if i == blink_speed:
                overlay_2.alpha = 255
            elif i == (2 * blink_speed):
                overlay_2.alpha = 0
                i = 0
            #Restart while loop
            sleep(0.1)
            continue
        #button has been pressed!
        print("Button Pressed!")

当我运行此代码时,根本没有按下按钮。

我怎么了?

编辑:所以我在printPressed()函数中添加了一条打印语句,并在按下按钮时确认它正在运行。

In还添加了一条语句,以在if语句之前打印shutterHasBeenPressed的值。这从未改变过。

但是,如果我在循环开始时删除了将变量更改为false的行,则代码可以正常工作,因此显然与运行各种位有关。也许while循环在shutterPressed()函数运行后再次开始?

无论哪种方式,我都通过将变量的重新分配移动到if语句之后来解决。

1 个答案:

答案 0 :(得分:0)

欢迎来到并发世界(一定)!

试想一下您的程序正在运行:指令按照它们定义的执行流程,按照{strong> {{1} }异步执行(也许)。

因此,假设我们进入循环并位于第一行shutterPressed

<here>

现在, while True: global shutterHasBeenPressed shutterHasBeenPressed = False # <here> #Stay in loop until button is pressed if shutterHasBeenPressed is False: i += 1 if i == blink_speed: overlay_2.alpha = 255 elif i == (2 * blink_speed): overlay_2.alpha = 0 i = 0 #Restart while loop sleep(0.1) continue #button has been pressed! print("Button Pressed!") 已设置为shutterHasBeenPressed,并验证了以下条件,以便我们输入False

程序一直运行,直到意外按下按钮。说,它达到了if

<here>

此时, while True: global shutterHasBeenPressed shutterHasBeenPressed = False #Stay in loop until button is pressed if shutterHasBeenPressed is False: i += 1 if i == blink_speed: overlay_2.alpha = 255 # <here> elif i == (2 * blink_speed): overlay_2.alpha = 0 i = 0 #Restart while loop sleep(0.1) continue #button has been pressed! print("Button Pressed!") 运行,将shutterPressed设置为shutterHasBeenPressed。然后,回到循环中,迭代完成,我们在循环开始时True,...在那里?!

continue

完全不注意到按钮按下!

我相信这可以回答您的问题,询问您错了什么。