【问题标题】:Reading serial port input读取串口输入
【发布时间】:2020-02-25 10:51:56
【问题描述】:

我有一个通过串行端口适配器连接到 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

【问题讨论】:

    标签: python python-2.7 psychopy


    【解决方案1】:

    '\x02' 是包含 ONE 字符且 (ascii/ansi/unicode) 值为 2 的字符串的转义代码。您的 line 变量是 1 个字符长。试试len(line)

    如果您想通过提取此字符的值来打印按钮编号,请尝试:print(ord(line[0]))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-26
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      相关资源
      最近更新 更多