从串口读取十六进制数据

发布于 2025-01-19 04:00:14 字数 829 浏览 5 评论 0 原文

我正在尝试阅读来自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输出?

I am trying to read a hex data from an MCU connected by USB. The MCU is designed to provide output in hex.

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\x00Ch\n'b'\x00^\xd4\x00\x00\xa1\xc7\x97\xbd\x00\x00\x00\x00\x00\x00\x00\x00

I get those characters like \x00Ch\n'b'\x00^ which are not in hex and seems like an error.

how would you suggest me to update the code to get pure hex output?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℡寂寞咖啡 2025-01-26 04:00:14

这只是使您感到困惑的代表。

您从串行中读取的数据实际上是二进制文件,例如,可以显示为十六进制转储,或者您在二进制数据Python提供的默认表示(rep)中所经历的。从 bytes.hex(line)或 binascii 模块。

二进制数据的可能表示形式将是这样的:

>>> d = b'abcd'
>>> bytes.hex(d, ' ')
'61 62 63 64'

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 instance bytes.hex(line) or one of the functions of the binascii module.

A possible representation of binary data would look like this:

>>> d = b'abcd'
>>> bytes.hex(d, ' ')
'61 62 63 64'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文