1

我正在尝试使用 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()
4

2 回答 2

2

文档microbit.display.show说 :

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

loop=True因此,您需要编写自己的 Pythonfor或循环来显示动画中的一帧,而不是使用while,检查按钮是否被按下,如果是则退出循环。

您需要自己在此循环中添加时间延迟,并且您还需要弄清楚当您显示最后一帧时如何返回第一帧 - 有不止一种方法可以做到这一点。

于 2019-01-03T15:44:49.413 回答
2

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

事件处理程序将是处理按钮按下的一种更简洁的方式。microbit 上的 micropython 实现缺少例如 pyboards 上 micropython 的完整实现所具有的事件处理程序。事件处理程序在可用于 microbit 的 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)
于 2019-01-07T16:19:59.300 回答