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

因?yàn)闆]有UI,運(yùn)行時(shí)需要在提示符下輸入串口相關(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ù)速度很快時(shí), python plot 繪圖會明顯卡頓。
為解決此問題,已經(jīng)用C# 重新做了個winform UI, 使用chart控件來繪圖。
以上這篇Python 讀取串口數(shù)據(jù),動態(tài)繪圖的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django中prefetch_related()函數(shù)優(yōu)化實(shí)戰(zhàn)指南
我們可以利用Django框架中select_related和prefetch_related函數(shù)對數(shù)據(jù)庫查詢優(yōu)化,這篇文章主要給大家介紹了關(guān)于Django中prefetch_related()函數(shù)優(yōu)化的相關(guān)資料,需要的朋友可以參考下2022-11-11
python matplotlib中文顯示參數(shù)設(shè)置解析
這篇文章主要介紹了python matplotlib中文顯示參數(shù)設(shè)置解析,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
python列表操作之extend和append的區(qū)別實(shí)例分析
這篇文章主要介紹了python列表操作之extend和append的區(qū)別,實(shí)例分析了extend方法和append方法使用上的區(qū)別,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
Python實(shí)現(xiàn)打印實(shí)心和空心菱形
今天小編就為大家分享一篇Python實(shí)現(xiàn)打印實(shí)心和空心菱形,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

