繁体   English   中英

python串口通信

[英]python serial port communication

这是我的串口通信代码

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style


import serial
MCU = serial.Serial('COM35', 115200, timeout=.1)


import time
time.sleep(1) #give the connection a second to settle

while True:
     data = MCU.readline()
print(str(data))

但我正在输出

b'\\x0b\\x16 )6\\x06\\x07\\x08X\\x02\\x16,' (Hex+Ascii 值)

这是我的输入数据

uint8_t myBuf[]={11,22,32,41,54,6,7,8,88,2,22,44};

有人知道我在这里做错了什么吗?

你想要什么格式的输出? 正如您所建议的,您拥有的是正确的数据,但采用字节格式。 例如,您可以将其作为 Python 整数列表获取,如下所示(Python 3):

>>> list(data)
[11, 22, 32, 41, 54, 6, 7, 8, 88, 2, 22, 44]

struct模块也可能对您解码字节数据很有用。

(我不能发表评论,抱歉。)

当您编写 str(data) 时,您请求 python 将二进制数据转换为可读字符串(在可读的 fromat 中)。

由于大多数字节没有可读的表示,python 只是将它们转换为它们的十六进制表示(作为字符串)。

如果您想将它们打印为列表,只需:list(data)。

也许尝试解码它是个好主意?

就像想法一样

while ser.isOpen():
    for s in ser.read():
        s = ser.readline().decode('utf-8') #reading data from the port with decoding from UTF-8
        com = str(s).replace('\n','') #cutting out second pass to the new line
        print(s)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM