Pybricks平台Omnibot代码逻辑错误排查求助
代码逻辑问题排查与修复
以下是你的orbit2函数中存在的核心逻辑问题及对应修复方案:
1. 外层循环完全失效
外层while ir_dis >= 65循环末尾直接调用break,导致循环仅执行一轮就强制退出,彻底失去了循环监测红外距离的设计意义。
修复:移除末尾的break,并在循环末尾重新读取传感器数据更新ir_dis,让循环能根据实时距离判断是否继续执行。
2. 方向对齐循环逻辑错误
while not direction == 12循环中,new_direction是进入循环前计算的固定值,机器人会一直朝着这个固定方向移动,不会根据实时读取的direction调整路径,永远无法对齐到12方向,直接导致死循环。
修复:将new_direction的计算逻辑移到内层循环内部,每次根据最新的direction动态调整移动方向:
while not direction == 12: current_angle = hub.imu.heading() values = ir_seeker.read(5) direction = values[1] ir_dis = values[0] # 实时计算调整方向 orbitdir = 2 if 0 < direction <= 6 else -2 new_direction = (direction + orbitdir) % 12 # 处理模运算后得到0的情况,转为合法的12方向 new_direction = 12 if new_direction == 0 else new_direction orbit1(new_direction, current_angle, score_speed) wait(15) print("orbiting in", direction)
3. 接近目标时的死循环风险
在if direction == 12的嵌套循环中,while not ir_dis >= 80内部没有重新读取红外传感器数据,ir_dis会一直保持旧值,如果初始值小于80,就会无限循环调用orbit1。
修复:在循环内部重新读取传感器数据,实时更新ir_dis:
if direction == 12: while movetoball == False: values = ir_seeker.read(5) ir_dis = values[0] while not ir_dis >= 80: orbit1(direction, current_angle, 100) values = ir_seeker.read(5) ir_dis = values[0] movetoball = True
4. 方向参数越界问题
(direction + orbitdir) % 12会出现结果为0的情况(比如direction=10、orbitdir=2时,12%12=0),但orbit1要求接收1-12的方向参数,导致参数非法。
修复:如修复方案2中所示,将模运算结果为0的情况转为12,保证参数符合orbit1的要求。
修正后的完整代码
def orbit2(): global current_angle, aligned, new_direction, movetoball values = ir_seeker.read(5) direction = values[1] ir_dis = values[0] while ir_dis >= 65: aligned = False values = ir_seeker.read(5) direction = values[1] ir_dis = values[0] print(str(new_direction)) while not direction == 12: current_angle = hub.imu.heading() values = ir_seeker.read(5) direction = values[1] ir_dis = values[0] # 实时计算调整方向 orbitdir = 2 if 0 < direction <= 6 else -2 new_direction = (direction + orbitdir) % 12 new_direction = 12 if new_direction == 0 else new_direction orbit1(new_direction, current_angle, score_speed) wait(15) print("orbiting in", direction) if direction == 12: while movetoball == False: values = ir_seeker.read(5) ir_dis = values[0] while not ir_dis >= 80: orbit1(direction, current_angle, 100) values = ir_seeker.read(5) ir_dis = values[0] movetoball = True print("aligned to 12, now calculating angles") aligned = True # 更新循环条件用的传感器数据 values = ir_seeker.read(5) ir_dis = values[0]
内容的提问来源于stack exchange,提问作者unilarity
相关产品推荐
相关产品推荐

