在micro:bit的python源码的例程中有一个无线(radio)通信的例子,它通过无线方式,模拟萤火虫之间互相呼应的效果。
这个例程需要多个microbit,最少需要5个以上,数量越多效果越好。
开始的时候,需要随机选择一个microbit,按下A键,通过无线发送“flash”(闪光)命令,启动系统。其它microbit接受到信号后,随机延时 50 - 350ms,然后以显示一组动画画面(屏幕从亮变暗)。最后产生一个随机数,如果随机数的值是零,就将发送“flash”命令。如果microbit的数量足够多,整个过程就会不断持续下去,形成此起彼伏,互相呼应的效果。
代码: 全选
# A micro:bit Firefly.
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, sleep
# Create the "flash" animation frames. Can you work out how it's done?
flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
# The radio won't work unless it's switched on.
radio.on()
# Event loop.
while True:
# Button A sends a "flash" message.
if button_a.was_pressed():
radio.send('flash') # a-ha
# Read any incoming messages.
incoming = radio.receive()
if incoming == 'flash':
# If there's an incoming "flash" message display
# the firefly flash animation after a random short
# pause.
sleep(random.randint(50, 350))
display.show(flash, delay=100, wait=False)
# Randomly re-broadcast the flash message after a
# slight delay.
if random.randint(0, 9) == 0:
sleep(500)
radio.send('flash') # a-ha