从串口读取十六进制数据
我正在尝试阅读来自USB连接的MCU的十六进制数据。 MCU旨在提供十六进制的输出。
This is a simple code I wrote using pyserial:
import serial
import time
ser = serial.Serial()
ser.port = '/dev/ttyUSB1'
ser.baudrate = 921600
ser.open()
bytesize = serial.EIGHTBITS
parity = serial.PARITY_NONE
stopbits = serial.STOPBITS_ONE
f = open('dataFile.txt','a')
for i in range(50):
line = ser.readline()
print(line)
line=str(line)
f.write(line)
Most of the output is in hex and seems fine but there are parts like this:
\x02\x01\x04\x03\x06\x05\x08\x07\x03\x00\x03\ x03@\ x00 \ x00 \ x00 \ x00ch \ n'b'\ x00^\ xd4 \ x00 \ x00 \ x00 \ x00 \ xa1 \ xc7 \ xc7 \ x97 \ x97 \ xbd \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \
x00像\ x00ch \ n'b'\ x00^一样,它不在十六进制中,似乎是一个错误。
您如何建议我更新代码以获取纯HEX输出?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是使您感到困惑的代表。
您从串行中读取的数据实际上是二进制文件,例如,可以显示为十六进制转储,或者您在二进制数据Python提供的默认表示(rep)中所经历的。从 bytes.hex(line)或 binascii 模块。
二进制数据的可能表示形式将是这样的:
It's just the representation that confuses you.
The data you read from serial is actually binary, which can be shown – for example – as a hex dump or as you experienced it in the default representation (rep) of binary data Python provides. To get a hexadecimal dump from
bytes
, you can use for instancebytes.hex(line)
or one of the functions of the binascii module.A possible representation of binary data would look like this: