在MicroPython中在事件之前显示图像

时间:2019-01-03 12:03:14

标签: micropython bbc-microbit

我正尝试使用BBC:Microbit在按下按钮a时在其led上显示闪光灯1秒钟。这可行,但是我希望它在等待按钮按下的同时显示动画(待机)。下面的代码仅显示待机图像,并且在按下按钮a时不运行其余代码。我怎么了?谢谢。

from microbit import *

standby1 = Image("00000:"
             "00000:"
             "90000:"
             "00000:"
             "00000")

standby2 = Image("00000:"
             "00000:"
             "09000:"
             "00000:"
             "00000")

standby3 = Image("00000:"
             "00000:"
             "00900:"
             "00000:"
             "00000")

standby4 = Image("00000:"
             "00000:"
             "00090:"
             "00000:"
             "00000")

standby5 = Image("00000:"
             "00000:"
             "00009:"
             "00000:"
             "00000")

all_leds_on = Image("99999:"
             "99999:"
             "99999:"
             "99999:"
             "99999")

standby = [standby1, standby2, standby3, standby4, standby5, standby4, standby3, standby2]

display.show(standby, loop=True, delay=100)#Show standby LEDS on a loop

#Wait for button a to be pressed
while True:

    if button_a.was_pressed():
        sleep(1000)#pause program for 1 second
        display.show(all_leds_on) #Turn on LEDS for 1 second
        sleep(1000)#pause program for 1 second
        display.clear()

2 个答案:

答案 0 :(得分:2)

microbit.display.show的{​​{3}}说:

  

如果loopTrue,动画将永远重复。

因此,无需使用loop=True,而是需要编写自己的Python forwhile循环,以显示动画中的一帧,检查是否按下了按钮并退出如果是循环。

您需要在此循环中自己添加时间延迟,还需要弄清楚在显示了最后一帧后如何返回到第一帧-您可以采取多种方法那个。

答案 1 :(得分:2)

正如nekomatic所说,替换loop = True是一种解决方案。请在下面找到一些示例代码。

事件处理程序将是处理按钮按下的更干净的方法。 microbit上的micropython实现缺少事件处理程序,例如micropython的完整实现。 pyboard有。事件处理程序在可用于微比特的C编译器中可用。

from microbit import *

standby1 = Image("00000:"
             "00000:"
             "90000:"
             "00000:"
             "00000")

standby2 = Image("00000:"
             "00000:"
             "09000:"
             "00000:"
             "00000")

standby3 = Image("00000:"
             "00000:"
             "00900:"
             "00000:"
             "00000")

standby4 = Image("00000:"
             "00000:"
             "00090:"
             "00000:"
             "00000")

standby5 = Image("00000:"
             "00000:"
             "00009:"
             "00000:"
             "00000")

all_leds_on = Image("99999:"
             "99999:"
             "99999:"
             "99999:"
             "99999")

def flash_all():
    ''' Flash all LEDs on the display. '''
    display.show(all_leds_on)
    sleep(1000)
    display.clear()

standby = [standby1, standby2, standby3, standby4, standby5, 
        standby4, standby3, standby2]

while True:
    for image in standby:
        if button_a.was_pressed():
            flash_all()
        display.show(image)
        sleep(100)