簡體   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