乐高Spike编程车仅后退约1秒后停止,故障排查求助
问题分析与修复方案
核心问题
你的代码中forward方法被定义为async异步方法,但调用时没有使用await关键字,导致程序不会等待前进动作完成就直接执行后续的后退指令,进而引发执行时序混乱,出现后退仅1秒左右就停止的异常。
修复步骤
修正异步方法调用
乐高Spike的Python环境中,异步方法必须通过await等待执行完成,否则会导致任务调度异常。需将主逻辑包装在异步函数中,并通过asyncio.run()启动。统一方法的异步/同步特性
为保证动作顺序执行,将所有电机动作方法改为异步,避免混合使用导致的时序问题。优化代码结构
移除motorWheels类中未实际使用的__init__参数(speed和time),简化类结构。
修复后的完整代码
from hub import port import motor_pair, motor, color_sensor, color import asyncio class motorWheels: def pairMotors(self): motor_pair.pair(motor_pair.PAIR_1, port.A, port.B) async def forward(self, speed, time): await motor_pair.move_for_time(motor_pair.PAIR_1, time, speed) async def reverse(self, speed, time): await motor_pair.move_for_time(motor_pair.PAIR_1, time, -1*speed) async def turnDegrees(self, degrees): # 并行执行两个电机转向,保证同步性 await asyncio.gather( motor.run_for_degrees(port.A, degrees, 400), motor.run_for_degrees(port.B, -1*degrees, 400) ) async def runUntilColor(self, num): if num == 1: while color_sensor.color(port.C) != color.RED: await motor_pair.move_for_time(motor_pair.PAIR_1, 1000, 1000) elif num == 2: while color_sensor.color(port.C) != color.BLUE: await motor_pair.move_for_time(motor_pair.PAIR_1, 1000, 1000) elif num == 3: while color_sensor.color(port.C) != color.GREEN: await motor_pair.move_for_time(motor_pair.PAIR_1, 1000, 1000) class Crane: def __init__(self, height): self.height = height async def crane(self, speed, time): await motor.run_for_time(port.D, time, speed) async def main(): drive = motorWheels() drive.pairMotors() await drive.forward(1000, 3000) await drive.reverse(1000, 3000) await drive.turnDegrees(360) asyncio.run(main())
额外说明
asyncio.gather用于并行执行两个电机的转向动作,保证转向同步性,避免车辆偏移。- 所有涉及电机动作的方法均改为异步并使用
await,确保动作按预期顺序执行。
内容的提问来源于stack exchange,提问作者PetterJY
相关产品推荐
相关产品推荐

