You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FLL SPIKE机器人Python编程:如何同时执行两个任务?

在乐高SPIKE Python中实现多任务并发执行

针对FLL机器人需要同时执行多项任务(如行驶+抬起附件)的需求,有两种直接可行的实现方式:

方法1:利用SPIKE电机API的非阻塞参数

SPIKE Python SDK的电机控制方法内置了wait参数,默认值为True(调用后阻塞直到任务完成),将其设为False即可让函数立即返回,实现多任务并行。

示例代码:

from spike import Motor, MotorPair
import time

# 初始化硬件:驱动轮组与附件电机
drive_base = MotorPair('A', 'B')
attachment_motor = Motor('C')

# 启动前进(非阻塞,无需等待完成)
drive_base.run(speed=50, wait=False)
# 同时启动附件抬起(非阻塞)
attachment_motor.run_to_position(90, speed=30, wait=False)

# 执行其他逻辑或等待任务结束
time.sleep(3)
# 停止所有电机
drive_base.stop()
attachment_motor.stop()

方法2:使用Python threading模块实现自定义多线程

如果需要更复杂的并发逻辑(比如自定义函数并行),可以借助Python标准库的threading模块,将不同任务分配到独立线程中运行。

示例代码:

from spike import Motor, MotorPair
import threading
import time

drive_base = MotorPair('A', 'B')
attachment_motor = Motor('C')

def drive_forward():
    """控制机器人前进3秒后停止"""
    drive_base.run(speed=50)
    time.sleep(3)
    drive_base.stop()

def lift_attachment():
    """控制附件抬起到指定位置后停止"""
    attachment_motor.run_to_position(90, speed=30)
    time.sleep(2)
    attachment_motor.stop()

# 创建线程实例
drive_thread = threading.Thread(target=drive_forward)
lift_thread = threading.Thread(target=lift_attachment)

# 启动线程
drive_thread.start()
lift_thread.start()

# 等待所有线程执行完毕
drive_thread.join()
lift_thread.join()

注意事项

  • 避免多个线程同时控制同一个电机,防止指令冲突导致的异常
  • 调试时需关注线程生命周期,可通过time.sleep或状态检测控制任务时长
  • SPIKE的Python环境对线程支持稳定,但不要创建过多线程,避免占用硬件资源

内容的提问来源于stack exchange,提问作者J7seaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:35:29