1. 文档中心
  2. 比卜创造 Micro:bit
  3. API 参考
  4. machine

machine

machine 模块提供与 micro:bit 硬件相关的底层功能。多数接口允许直接、不受限地访问 CPU、定时器、总线等硬件块。使用不当可能导致故障、死锁、崩溃,极端情况下可能损坏硬件。

函数

machine.unique_id()

返回值:标识本板实例的唯一字节串,每块板不同。

machine.reset()

复位设备,效果类似按下外部 RESET 按钮。

machine.freq()

返回值:CPU 频率(Hz)。

machine.disable_irq()

关闭中断请求。

返回值:先前的 IRQ 状态(不透明值),应传给 machine.enable_irq() 以恢复。

machine.enable_irq(state)

重新开启中断。state 应为最近一次 machine.disable_irq() 的返回值。

参数

  • state:IRQ 状态。

machine.time_pulse_us(pin, pulse_level, timeout_us=1000000)

测量 pin 上脉冲宽度(微秒)。pulse_level 为 0 测低电平脉冲,1 测高电平脉冲。

若当前电平与 pulse_level 不同,先等待电平变为 pulse_level(*),再计时保持该电平的时长(**)。若已为 pulse_level 则立即开始计时。

等待(*)超时返回 -2;测量(**)超时返回 -1。超时均由 timeout_us(微秒)控制。

参数

  • pin:待测 引脚。
  • pulse_level:0 或 1。
  • timeout_us:超时时间,默认 1000000。

读取内存

machine 模块可按物理地址读取设备内存:1 字节 mem8、2 字节 mem16、4 字节 mem32。例如 mem8[0x00] 读取地址 0x00 处 1 字节。可用于读取 nRF52833 等芯片的寄存器数据。

示例

读取板卡唯一 ID 并显示(十六进制摘要):

from bibo import *
import machine

uid = machine.unique_id()
# 将前几字节显示为点阵图案(示意)
img = Image(5, 5)
for i in range(min(5, len(uid))):
    img.set_pixel(i, 0, uid[i] % 10)
display.show(img)

可在比卜创造 Python 编辑器中运行;日常项目更推荐使用 microbit 模块的高层 API。