GoPiGo机器人避障程序报错:Event未定义及Ctrl-C停止异常
GoPiGo避障程序问题及修复方案
问题描述
- 初始避障程序可正常运行,但按下
Ctrl-C终止程序时,程序停止但机器人持续移动,需物理关机才能停止。 - 尝试添加键盘事件监听功能时,触发错误:
NameError: name 'Event' is not defined。
错误原因
Event是Python threading模块中的类,出现该错误说明未正确导入threading.Event,或是直接使用Event但未指定模块前缀。
修复方案
方案1:捕获Ctrl-C信号(简洁直接)
无需额外监听键盘事件,直接捕获Ctrl-C触发的SIGINT信号,在信号处理函数中强制停止机器人:
import signal from easygopigo3 import EasyGoPiGo3 # 初始化机器人 gpg = EasyGoPiGo3() def stop_robot(signal_num, frame): print("程序终止,正在停止机器人...") gpg.stop() exit(0) # 注册SIGINT信号处理函数 signal.signal(signal.SIGINT, stop_robot) # 避障逻辑主循环 try: while True: distance = gpg.read_distance_sensor() if distance < 20: gpg.right() else: gpg.forward() except Exception as e: print(f"程序出错: {e}") gpg.stop()
方案2:修复Event未定义问题(线程事件方案)
如果要沿用键盘监听的线程方案,需先正确导入threading.Event:
import threading from easygopigo3 import EasyGoPiGo3 # 初始化线程事件对象 stop_event = threading.Event() def robot_control(): gpg = EasyGoPiGo3() while not stop_event.is_set(): # 执行避障逻辑 distance = gpg.read_distance_sensor() if distance < 20: gpg.right() else: gpg.forward() gpg.stop() def listen_for_keyboard(): try: input("按下Enter或Ctrl-C停止程序...\n") except KeyboardInterrupt: pass stop_event.set() # 启动机器人控制线程 control_thread = threading.Thread(target=robot_control) control_thread.start() # 启动键盘监听 listen_for_keyboard() control_thread.join()
关键说明
- 两种方案的核心都是在程序终止前调用
gpg.stop(),确保机器人电机断电停止。 - 信号捕获方案更适配
Ctrl-C这类强制终止场景,无需额外线程开销。
内容的提问来源于stack exchange,提问作者Jim JR Harris
相关产品推荐
相关产品推荐

