RPi B3驱动Devastator坦克遇setupterm找不到键盘错误求助
问题描述
我使用树莓派B3、PiHut MotorShield电机驱动板和迷你WiFi键盘远程控制Devastator坦克,运行控制代码时遭遇setupterm cannot find keyboard错误。此前曾成功用curses库搭配该迷你键盘实现控制,附上代码请求解决。
控制代码
import curses import PiMotor import time import curses import os # added so we can shutdown OK #Name of Individual MOTORS m1 = PiMotor.Motor("MOTOR1",1) m2 = PiMotor.Motor("MOTOR2",1) #To drive all motors together motorAll = PiMotor.LinkedMotors(m1,m2) #Names for Individual Arrows ab = PiMotor.Arrow(1) al = PiMotor.Arrow(2) af = PiMotor.Arrow(3) ar = PiMotor.Arrow(4) # Get the curses window, turn off echoing of keyboard to screen, turn off # instant (no waiting) key response, and use special values for curser keys screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(True) ##This segment drives the motors in the direction listed below: ## forward and reverse takes speed in percentage(0-100) try: while True: char = screen.getch() if char == ord('q'): break if char == ord('S'): # Added for shutdown on capital S os.system ('sudo shutdown now') # shutdown right now! elif char == curses.KEY_UP: af.on() motorAll.forward(100) elif char == curses.KEY_DOWN: af.off() ab.on() motorAll.reverse(100) elif char == curses.KEY_RIGHT: ar.on() ab.off() m1.reverse(100) m2.forward(100) elif char == curses.KEY_LEFT: ar.off() al.on() m1.forward(100) m2.reverse(100) elif char == 10: motorALL.stop() except KeyboardInterupt: #Close down curses properly, inc turn echo back on! curses.nobreak(); screen.keypad(0); curses.echo(0) curses.endwin()
解决方案
- 修正终端环境配置:远程运行代码时,必须确保终端为交互式tty环境。执行
echo $TERM检查终端类型,若输出为空或无效值,手动设置:export TERM=xterm后再运行代码。避免使用后台运行(如nohup)或非交互式SSH连接,这类场景下curses无法识别键盘。 - 修复代码拼写错误:
except KeyboardInterupt:拼写错误,改为except KeyboardInterrupt:motorALL.stop()中的变量名错误,改为motorAll.stop()(与前面定义的变量名一致)
- 手动指定终端类型:在
curses.initscr()前添加以下代码,强制设置终端环境,避免系统无法找到终端配置:os.environ.setdefault('TERM', 'xterm') - 验证键盘输入映射:在终端中先测试迷你WiFi键盘的按键输入,确认方向键、字母键能被正确识别。若远程连接时按键映射异常,可尝试更换SSH客户端,或调整远程桌面的键盘输入设置。
内容的提问来源于stack exchange,提问作者jrrobb
相关产品推荐
相关产品推荐

