micro:bit Micropython API

微比特模块

与硬件交互直接相关的一切都存在于microbit模块中。为了便于使用,建议您使用以下命令启动所有脚本:

from microbit import *

以下文档假定您已完成此操作。

有几个函数可以直接使用:

# sleep for the given number of milliseconds.
sleep(ms)
# returns the number of milliseconds since the micro:bit was last switched on.
running_time()
# makes the micro:bit enter panic mode (this usually happens when the DAL runs
# out of memory, and causes a sad face to be drawn on the display). The error
# code can be any arbitrary integer value.
panic(error_code)
# resets the micro:bit.
reset()
# sets the output volume (0-255) of the micro:bit speaker **V2** and
# external speaker or headphones connected to the edge connector pins.
set_volume(128)    # V2

其余功能由 microbit 模块中的对象和类提供,如下所述。

请注意,API 仅公开整数(即不需要浮点数,但可以接受它们)。因此,我们使用毫秒作为标准时间单位

笔记

您可以通过编写help('modules') REPL来查看所有可用模块的列表。

纽扣

有2个按钮:

button_a
button_b

它们都是对象并具有以下方法:

# returns True or False to indicate if the button is pressed at the time of
# the method call.
button.is_pressed()
# returns True or False to indicate if the button was pressed since the device
# started or the last time this method was called.
button.was_pressed()
# returns the running total of button presses, and resets this counter to zero
button.get_presses()

展示

LED显示屏通过显示对象暴露:

# gets the brightness of the pixel (x,y). Brightness can be from 0 (the pixel
# is off) to 9 (the pixel is at maximum brightness).
display.get_pixel(x, y)
# sets the brightness of the pixel (x,y) to val (between 0 [off] and 9 [max
# brightness], inclusive).
display.set_pixel(x, y, val)
# clears the display.
display.clear()
# shows the image.
display.show(image, delay=0, wait=True, loop=False, clear=False)
# shows each image or letter in the iterable, with delay ms. in between each.
display.show(iterable, delay=400, wait=True, loop=False, clear=False)
# scrolls a string across the display (more exciting than display.show for
# written messages).
display.scroll(string, delay=400)

声音事件V2

声音事件描述了麦克风听到的声音的变化:

# Value to represent the transition of sound events, from `quiet` to `loud`
# like clapping or shouting.
SoundEvent.LOUD = SoundEvent('loud')
# Value to represent the transition of sound events, from `loud` to `quiet`
# like speaking or background music.
SoundEvent.QUIET = SoundEvent('quiet')

话筒 V2

麦克风是通过麦克风对象访问的:

# Returns the name of the last recorded sound event.
current_event()
# A sound event,  such as `SoundEvent.LOUD` or `SoundEvent.QUIET`.
# Returns`true` if sound was heard at least once since the last
# call, otherwise `false`.
was_event(event)
# Returns a tuple of the event history. The most recent is listed last.
# Also clears the sound event history before returning.
get_events()
# The threshold level in the range 0-255. For example,
# `set_threshold(SoundEvent.LOUD, 250)` will only trigger if the
# sound is very loud (>= 250).
set_threshold(128)
# Returns a representation of the sound pressure level in the range 0 to 255.
sound_level()

引脚

为连接器中的引脚、 V2徽标和V2 扬声器提供数字和模拟输入和输出功能。一些引脚在内部连接到驱动 LED 矩阵和按钮的 I/O。

每个引脚都直接作为microbit模块中的对象提供。这使 API 保持相对平坦,使其非常易于使用:

  • 引脚0
  • 引脚1
  • 引脚15
  • 引脚16
  • 警告:P17-P18(含)不可用。
  • 引脚19
  • 引脚20
  • pin_logo V2
  • pin_speaker V2

这些引脚中的每一个都是 MicroBitPin 该类的实例,它提供以下 API:

# value can be 0, 1, False, True
pin.write_digital(value)
# returns either 1 or 0
pin.read_digital()
# value is between 0 and 1023
pin.write_analog(value)
# returns an integer between 0 and 1023
pin.read_analog()
# sets the period of the PWM output of the pin in milliseconds
# (see https://en.wikipedia.org/wiki/Pulse-width_modulation)
pin.set_analog_period(int)
# sets the period of the PWM output of the pin in microseconds
# (see https://en.wikipedia.org/wiki/Pulse-width_modulation)
pin.set_analog_period_microseconds(int)
# Only available for touch pins 0, 1, and 2. Returns boolean if the pin
# is touched
pin.is_touched()
# Only available for touch pins 0, 1, 2 and on micro:bit V2 also the logo.
# Sets the touch mode. Value can be either RESISTIVE or CAPACITIVE
pin.set_touch_mode(value)

除了标记为 V2的引脚,它提供以下 API:

pin_logo:

# returns boolean for logo touch pin
pin_logo.is_touched()
# Sets the touch mode. Value can be either RESISTIVE or CAPACITIVE
pin.set_touch_mode(value)

pin_speaker:

同上 MicroBitPin 类,但不包括pin.is_touched().

图片

笔记

您并不总是需要自己创建其中之一 - 您可以使用display.image直接访问显示器上显示的图像。display.image 只是Image 的一个实例,因此您可以使用所有相同的方法。

图像API:

# creates an empty 5x5 image
image = Image()
# create an image from a string - each character in the string represents an
# LED - 0 (or space) is off and 9 is maximum brightness. The colon ":"
# indicates the end of a line.
image = Image('90009:09090:00900:09090:90009:')
# create an empty image of given size
image = Image(width, height)
# initialises an Image with the specified width and height. The buffer
# should be an array of length width * height
image = Image(width, height, buffer)

# methods
# returns the image's width (most often 5)
image.width()
# returns the image's height (most often 5)
image.height()
# sets the pixel at the specified position (between 0 and 9). May fail for
# constant images.
image.set_pixel(x, y, value)
# gets the pixel at the specified position (between 0 and 9)
image.get_pixel(x, y)
# returns a new image created by shifting the picture left 'n' times.
image.shift_left(n)
# returns a new image created by shifting the picture right 'n' times.
image.shift_right(n)
# returns a new image created by shifting the picture up 'n' times.
image.shift_up(n)
# returns a new image created by shifting the picture down 'n' times.
image.shift_down(n)
# get a compact string representation of the image
repr(image)
# get a more readable string representation of the image
str(image)

#operators
# returns a new image created by superimposing the two images
image + image
# returns a new image created by multiplying the brightness of each pixel by n
image * n

内置图像

Image.HEART Image.HEART_SMALL Image.HAPPY Image.SMILE Image.SAD Image.CONFUSED Image.ANGRY Image.ASLEEP Image.SURPRISED Image.SILLY Image.FABULOUS Image.MEH Image.YES Image.NO Image.TRIANGLE Image.TRIANGLE_LEFT Image.CHESSBOARD Image.DIAMOND Image.DIAMOND_SMALL Image.SQUARE Image.SQUARE_SMALL Image.RABBIT Image.COW Image.MUSIC_CROTCHET Image.MUSIC_QUAVER Image.MUSIC_QUAVERS Image.PITCHFORK Image.XMAS Image.PACMAN Image.TARGET Image.TSHIRT Image.ROLLERSKATE Image.DUCK Image.HOUSE Image.TORTOISE Image.BUTTERFLY Image.STICKFIGURE Image.GHOST Image.SWORD Image.GIRAFFE Image.SKULL Image.UMBRELLA Image.SNAKE

时钟:

Image.CLOCK1 Image.CLOCK2 Image.CLOCK3 Image.CLOCK4 Image.CLOCK5 Image.CLOCK6 Image.CLOCK7 Image.CLOCK8 Image.CLOCK9 Image.CLOCK10 Image.CLOCK11 Image.CLOCK12

箭头:

Image.ARROW_N Image.ARROW_NE Image.ARROW_E Image.ARROW_SE Image.ARROW_S Image.ARROW_SW Image.ARROW_W Image.ARROW_NW

以下是 Python 图像列表,可用于自动显示动画或手动遍历它们。

Image.ALL_CLOCKS Image.ALL_ARROWS

加速度计

加速度计通过accelerometer 对象访问:

# read the X axis of the device. Measured in milli-g.
accelerometer.get_x()
# read the Y axis of the device. Measured in milli-g.
accelerometer.get_y()
# read the Z axis of the device. Measured in milli-g.
accelerometer.get_z()
# get tuple of all three X, Y and Z readings (listed in that order).
accelerometer.get_values()
# return the name of the current gesture.
accelerometer.current_gesture()
# return True or False to indicate if the named gesture is currently active.
accelerometer.is_gesture(name)
# return True or False to indicate if the named gesture was active since the
# last call.
accelerometer.was_gesture(name)
# return a tuple of the gesture history. The most recent is listed last.
accelerometer.get_gestures()

识别的手势是: up, down, left, right, face up, face down, freefall, 3g, 6g, 8g, shake.

罗盘

指南针是通过指南针对象访问的:

# calibrate the compass (this is needed to get accurate readings).
compass.calibrate()
# return a numeric indication of degrees offset from "north".
compass.heading()
# return an numeric indication of the strength of magnetic field around
# the micro:bit.
compass.get_field_strength()
# returns True or False to indicate if the compass is calibrated.
compass.is_calibrated()
# resets the compass to a pre-calibration state.
compass.clear_calibration()

I2C总线

micro:bit 上有一个 I2C 总线,通过i2c对象公开。它有以下方法:

# read n bytes from device with addr; repeat=True means a stop bit won't
# be sent.
i2c.read(addr, n, repeat=False)
# write buf to device with addr; repeat=True means a stop bit won't be sent.
i2c.write(addr, buf, repeat=False)

声音V2

micro:bitV2提供了一组富有表现力的声音。它们可以通过microbit模块访问并使用 音频模块播放。

内置声音

Sound.GIGGLE Sound.HAPPY Sound.HELLO Sound.MYSTERIOUS Sound.SAD Sound.SLIDE Sound.SOARING Sound.SPRING Sound.TWINKLE Sound.YAWN

扬声器 V2

扬声器默认启用,可以使用 speaker 对象访问。它可以关闭或打开:

# disable the built-in speaker
speaker.off()
# enable the built-in speaker
speaker.on()
# returns True or False to indicate if the speaker is on or off
speaker.is_on()

串口

用于 uart与连接到设备 I/O 引脚的串行设备通信:

# set up communication (use pins 0 [TX] and 1 [RX]) with a baud rate of 9600.
uart.init()
# return True or False to indicate if there are incoming characters waiting to
# be read.
uart.any()
# return (read) n incoming characters.
uart.read(n)
# return (read) as much incoming data as possible.
uart.read()
# return (read) all the characters to a newline character is reached.
uart.readline()
# read bytes into the referenced buffer.
uart.readinto(buffer)
# write bytes from the buffer to the connected device.
uart.write(buffer)