ano*_*non 5 python serial-port pyserial
我正在尝试使用 pySerial 通过串行读取和写入传感器。我没有软件或硬件流量控制。
我能够向设备发送一串十六进制字符串,但我只收到一个字节,而不是我应该看到的两到十个字节。传感器正在工作——我已经使用 Realterm 验证了这一点。
我尝试过使用 ser.readline() (而不是 inWaiting 循环)和 ser.read(2); 这只会导致程序挂起。我还尝试增加睡眠时间,并尝试不同的波特率(在电脑和传感器上),但似乎没有任何效果。
有人有建议吗?
import time
import serial
# configure the serial connections
ser = serial.Serial(
port='COM1',
baudrate=115200,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
while 1 :
# get keyboard input
data_in = raw_input(">> ")
if data_in == 'exit':
ser.close()
exit()
else:
# send the character to the device
ser.write(data_in.decode('hex') + '\r\n')
out = ''
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + " ".join(hex(ord(n)) for n in out)
Run Code Online (Sandbox Code Playgroud)
(我稍微修改了使用 pySerial 包的完整示例中找到的代码)
您的读取语句明确请求 1 个字节:
ser.read(1)
Run Code Online (Sandbox Code Playgroud)
如果您知道要读取多少字节,可以在此处指定。如果您不确定,可以指定一个更大的数字。例如,做
ser.read(10)
Run Code Online (Sandbox Code Playgroud)
最多可读取 10 个字节。如果只有 8 个可用,那么它只会返回 8 个字节(超时后,见下文)。
还值得设置超时以防止程序挂起。只需向 Serial 构造函数添加一个超时参数即可。以下将为您提供 2 秒超时:
ser = serial.Serial(
port='COM1',
baudrate=115200,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=2
)
Run Code Online (Sandbox Code Playgroud)
文档指出:
read(size=1)size从串行端口读取字节。如果设置了超时,它可能会根据请求返回更少的字符。如果没有超时,它将阻塞,直到读取请求的字节数。
因此,如果您不知道需要多少字节,请设置一个小的超时(如果可能),这样您的代码就不会挂起。
如果您的代码未返回预期的全部字节数,则您连接的设备可能未发送您预期的所有字节。既然您已经验证它应该单独工作,那么您是否验证了您发送的数据是否正确?也许首先使用 struct.pack() 编码为字节。例如,发送十进制值为 33(十六进制 0x21)的字节
import struct
bytes_to_send = struct.pack('B', 33)
Run Code Online (Sandbox Code Playgroud)
我也从未发现有必要在发送之前将行尾字符附加\r\n到消息中
| 归档时间: |
|
| 查看次数: |
23412 次 |
| 最近记录: |