我有一个通过串行端口适配器连接到USB端口的按钮箱。
按钮框有5个按钮。我正在尝试做的是记录已按下的按钮(以及何时按下)。到目前为止,我将重点介绍什么按钮。该代码将在PsychoPy实验中使用。
到目前为止,我在做什么:
import serial
import serial.tools.list_ports as port_list
ports = list(port_list.comports()) # search for the devices
#for p in ports: print (p)
ser = serial.Serial('/dev/ttyUSB0', 19200, timeout=1)
if(ser.isOpen() == False): #open the serial port only if NOT open yet
ser.open()
ser.flushInput() #erase all info in the box about previous button-presses
print("connected to: " + ser.portstr)
line = ser.read()
print(chr(line))
ser.close()
但是,如果执行此操作,则会出现以下错误:
TypeError: an integer is required
如果在按下按钮后检查line
,则会得到以下值:
'\x02'
该值根据所按下的按钮而变化:'\x02'
,'\x03'
等。因此似乎至少检测到所按下的右按钮。
我试图做的最后一件事是以下内容。为了将字符串转换为整数,我尝试替换'\x0'
:
line
a=str(line)
a.replace('\x0', "")
a
我收到以下错误:
ValueError: invalid \x escape
'\x02'
是包含一个带有(ascii / ansi / unicode)值2的字符的字符串的转义代码。您的行变量的长度为1个字符。试试len(line)
如果要通过提取此字符的值来打印按钮号,请尝试:print(ord(line[0]))