最近工作需要把單片機(jī)讀取的傳感器電壓數(shù)據(jù)實(shí)時(shí)在PC上通過(guò)曲線(xiàn)顯示出來(lái),剛好在看python, 就試著用了python 與uart端口通訊,并且通過(guò)matplotlib.pyplot 模塊實(shí)時(shí)繪制圖形出來(lái)。
創(chuàng)新互聯(lián)建站主營(yíng)漠河網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都APP應(yīng)用開(kāi)發(fā),漠河h5成都微信小程序搭建,漠河網(wǎng)站營(yíng)銷(xiāo)推廣歡迎漠河等地區(qū)企業(yè)咨詢(xún)1. 廢話(huà)少說(shuō),上圖
因?yàn)闆](méi)有UI,運(yùn)行時(shí)需要在提示符下輸入串口相關(guān)參數(shù),com端口,波特率...
代碼如下:
#-*- coding: utf-8 -*- # 串口測(cè)試程序 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ù)后,清除畫(huà)布,重新開(kāi)始,避免數(shù)據(jù)量過(guò)大導(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)