Python从RS232串行端口编码/解码数据

问题描述 投票:0回答:1

这是我第一次必须通过RS232串行连接到设备以读取/写入数据,而我陷入了编码/解码过程。

我正在使用库[pyserial]在Python 3中进行所有操作。这是我到目前为止所做的:

import serial

ser = serial.Serial()
ser.port = '/dev/ttyUSB0'
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.timeout = 3

ser.open()

device_write = ser.write(0x12)

^^^^这是如何正确传递命令还是我需要b'0x12'

device_read = ser.read_until()

连接/通讯似乎正在按预期方式工作。 device_read的输出是

b'\x04\x91\x02\x00=\xbf\xf1\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xba\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\xff\xff\x00\x00^\xc4S\x00\x00\x00\xdc\x12\xaaU\x017N\x00\x00\x00\x00\x00\xf2%\x00\x00u\x88\xfd\xff\x10\r\x00\x00\xae\xf2\xff\xff\x80\x03\x00\x00\x13\xb6\x04\x00\xa7\x92\x02\x00\x8f\xbe\xf1\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb7\x04\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\xff\xff\x00\x00^\xc4S\x00\x00\x00N\x12\xaaU\x017N\x00\x00\x00\x00\x00\xf2%\x00\x00u\x88\xfd\xff\xcf\xf0\xff\xffe\xec\xff\xff\x11\n'

这就是我被困住的地方。我不知道该怎么解释。随附的是数据表中的图像,该图像解释了输出应表示的内容。

enter image description here

((可能还有一个未在图像中显示的字节)。有人可以帮助我理解将ser.read_until()的输出转换为“人类可读”的形式并表示图像中数据的方法吗?我不需要别人为我编写代码,但是我什至不知道从哪里开始。再次,这是我第一次这样做,所以我对正在发生的事情有点迷茫。

python serial-port pyserial
1个回答
0
投票

[如果您尝试写入一个十六进制值12(十进制18)的单个字节,我相信您需要做的是ser.write(bytes([0x12])),它等效于ser.write(bytes([18]))

看来您的输出是154个字节而不是98个字节,并且其中很多是人类无法读取的。但是,如果您确实有图表中描述的数据,则可以像这样将其分解:

ID_sn = device_read[0:8].decode('ascii')
ID_fw = device_read[8:48].decode('ascii')
Press_Sens = device_read[48]

依此类推。

© www.soinside.com 2019 - 2024. All rights reserved.