Radio

  1. radio模块可以让设备通过简单的无线网络协同工作。
  2. 无线电模块在概念上非常简单:
  3. 广播消息的长度可配置(最多251字节)。
  4. 从消息队列中读取接收到的消息。如果队列已满,新消息会被忽略。
  5. 消息在预选频道(0-100)上广播和接收。
  6. 广播功率越大传输的范围越大。
  7. 消息通过address(如房间号)和group(如房间中的人)的方式过滤。
  8. 吞吐率可以是三个预定设置之一。
  9. 发送和接收来处理任意数据。
  10. 为方便孩子使用,将发送和接收消息转化成字符串方便操作。
  11. microbit的默认配置兼容其他的板子。

要访问此模块,您需要:

import radio

常量

函数

radio.on()

打开广播,这函数必须被调用,因为无线电会消耗功率并占用你可能需要的内存。

radio.off()

关闭收音机,节省电量和内存。

radio.config(**kwargs)

配置与收音机相关的各种基于关键字的设置。可用的设置及其合理的默认值如下所示。

如果config未被调用,则用上述默认值。

radio.reset()

将设置重置为默认值(如上述config的文档所列)。

注意:

*在广播打开之前,没有任何一个发送或接收函数会工作。
*

radio.send_bytes(message)

发送一个由字节组成的消息。

radio.receive_bytes()

接收消息队列中下一个传入的消息。如果没有消息,则返回None。消息被作为字节返回。

radio.receive_bytes_into(buffer)

接收消息队列中下一个传入的消息。将消息复制到buffer。如果没有消息,返回None。否则它返回消息的长度(可能比缓冲区的长度大)。

radio.send(message)

发送字符串消息。这是相当于send_bytes(bytes(message, 'utf8')),但是要在前端使用b'\x01\x01\x01'(为了使其与其他microbit兼容)。

radio.receive()

和receive_bytes的工作方式相同,但返回发送的内容。

目前,这相当于str(receive_bytes(), 'utf8'),但是会检测前三个字节是不是b'\x01\x00\x01'(为了让它与其他的microbit兼容)。

它在转换为字符串之前,它会去掉预先的字节。如果转换为字符串失败,就会抛出ValueError异常。

例子

# 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