API 基础
一页搞定两件事:够用的 Python 语法 + SPIKE 3 模块地图。有 Word Blocks 基础的话,每个概念你其实都见过。
Python 语法速成(对照 Word Blocks)
| Word Blocks | Python |
|---|---|
| 设置 [速度] 为 [50] | speed = 50 |
| 将 [速度] 增加 [10] | speed += 10 |
如果 <...> 那么 / 否则 | if ...: / else: |
| 重复 [10] 次 | for i in range(10): |
| 重复执行 | while True: |
重复执行直到 <条件> | while not 条件: |
<A> 与 <B> / <A> 或 <B> | A and B / A or B |
| 等待 [1] 秒 | await runloop.sleep_ms(1000) |
等待到 <条件> | await runloop.until(条件函数) |
| My Block 定义 | def / async def |
Python 用缩进表示"挂在里面"(4 个空格),相当于积木的包裹关系:
python
for i in range(3):
print(i) # 缩进 = 在循环里面
print("done") # 不缩进 = 循环外面函数可以返回值,这是 My Blocks 做不到的:
python
def is_black(port_id):
return color_sensor.reflection(port_id) < 35
if is_black(port.C):
...SPIKE 3 模块地图
| 模块 | 管什么 | 典型调用 |
|---|---|---|
motor | 单个马达 | motor.run_for_degrees(port.A, 360, 500) |
motor_pair | 底盘双马达 | motor_pair.move_for_degrees(...) |
color_sensor | 颜色传感器 | color_sensor.reflection(port.C) |
distance_sensor | 距离传感器 | distance_sensor.distance(port.D) |
force_sensor | 力传感器 | force_sensor.pressed(port.E) |
hub 包 | hub 本体 | from hub import port, motion_sensor, light_matrix, button, sound |
color | 颜色常量 | color.BLACK, color.RED |
runloop | 异步运行时 | runloop.run(), runloop.sleep_ms(), runloop.until() |
端口写法:port.A 到 port.F(来自 from hub import port)。
单位对照表(最容易踩的坑)
Python API 的单位和 Word Blocks 显示的不一样:
| 量 | Word Blocks | Python |
|---|---|---|
| 马达速度 | % (0-100) | 度/秒(大马达满速约 1050) |
| 距离 | cm | mm,测不到返回 -1 |
| 偏航角 | 度 | 0.1 度(decidegrees),900 = 90 度 |
| 力 | % 或 N | 0.1 牛顿(decinewtons),0-100 |
| 时间 | 秒 | 毫秒 ms |
完整示例:走到黑线停
python
import runloop, motor_pair, color_sensor
from hub import port
motor_pair.pair(motor_pair.PAIR_1, port.A, port.E) # 左轮 A,右轮 E
def on_black():
return color_sensor.reflection(port.C) < 35
async def main():
motor_pair.move(motor_pair.PAIR_1, 0, velocity=300) # 开始直行(不阻塞)
await runloop.until(on_black) # 等条件
motor_pair.stop(motor_pair.PAIR_1) # 停
runloop.run(main())对照 Word Blocks 版本(开始移动 → 等待到 → 停止移动),结构一模一样。
runloop.until() 接收的是函数本身(on_black,没有括号),不是调用结果——runloop 会反复调用它直到返回 True。
练习
- 把 Word Blocks 的"数 3 条线停"翻译成 Python(提示:
while+ 两个runloop.until)。 - 写一个
read_black_white()函数:按左按钮时记录黑值、右按钮记录白值,打印建议阈值。
下一课:马达与传感器完整 API。