您好,登錄后才能下訂單哦!
最近工作需要把單片機(jī)讀取的傳感器電壓數(shù)據(jù)實時在PC上通過曲線顯示出來,剛好在看python, 就試著用了python 與uart端口通訊,并且通過matplotlib.pyplot 模塊實時繪制圖形出來。
1. 廢話少說,上圖
因為沒有UI,運(yùn)行時需要在提示符下輸入串口相關(guān)參數(shù),com端口,波特率...
代碼如下:
#-*- coding: utf-8 -*- # 串口測試程序 import serial import matplotlib.pyplot as plt import numpy as np import time import re # User input comport and bundrate comport = input('Please input comport (like COM3) for your connected device: ') baudrate = input('Please input baudrate (like 9600) for your connected device: ') bytes = input('Please input bytes type of uart data (1->1 byte, 2->2 bytes): ') bytes = int(bytes) print('You selected %s, baudrate %d, %d byte.' % (comport, int(baudrate), bytes)) serialport = serial.Serial(comport, int(baudrate), timeout=1, parity=serial.PARITY_EVEN, rtscts=1) if serialport.isOpen(): print("open success") else: print("open failed") plt.grid(True) # 添加網(wǎng)格 plt.ion() # interactive mode plt.figure(1) plt.xlabel('times') plt.ylabel('data') plt.title('Diagram of UART data by Python') t = [0] m = [0] i = 0 intdata = 0 data = '' count = 0 while True: if i > 300: # 300次數(shù)據(jù)后,清除畫布,重新開始,避免數(shù)據(jù)量過大導(dǎo)致卡頓。 t = [0] m = [0] i = 0 plt.cla() count = serialport.inWaiting() if count > 0 : if (bytes == 1): data = serialport.read(1) elif (bytes == 2): data = serialport.read(2) if data !='': intdata = int.from_bytes(data, byteorder='big', signed = False) print('%d byte data %d' % (bytes, intdata)) i = i+1 t.append(i) m.append(intdata) plt.plot(t, m, '-r') # plt.scatter(i, intdata) plt.draw() plt.pause(0.002)
目前功能比較簡單,但是發(fā)現(xiàn)一個問題,但單片機(jī)送出數(shù)據(jù)速度很快時, python plot 繪圖會明顯卡頓。
為解決此問題,已經(jīng)用C# 重新做了個winform UI, 使用chart控件來繪圖。
以上這篇Python 讀取串口數(shù)據(jù),動態(tài)繪圖的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。