最近工作需要把單片機讀取的傳感器電壓數據實時在PC上通過曲線顯示出來,剛好在看python, 就試著用了python 與uart端口通訊,并且通過matplotlib.pyplot 模塊實時繪制圖形出來。
1. 廢話少說,上圖

因為沒有UI,運行時需要在提示符下輸入串口相關參數,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) # 添加網格
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次數據后,清除畫布,重新開始,避免數據量過大導致卡頓。
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)
目前功能比較簡單,但是發現一個問題,但單片機送出數據速度很快時, python plot 繪圖會明顯卡頓。
為解決此問題,已經用C# 重新做了個winform UI, 使用chart控件來繪圖。
以上這篇Python 讀取串口數據,動態繪圖的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。