一、相关库的安装
pip install pyserial #python 串口库
pip install pyqtgraph #安装pyqtgraph
pip install PyQt5 #安装python QT
二、代码使用步骤:
- 插入ch340,在 设备管理器-端口 看下COM几,然后更改文末代码中大概217行的COM数字
- 如没有外部串口数据,可取消代码中大概276行的注释,并将ch340的tx和rx短接
- 运行代码,暂停按q,开始按s
三、更改串口数据格式
本代码的格式在uart_send_thread线程里可以看到,为:"%1d:%7d,%7d"
即:
x | : | x | x | x | x | x | x | x | , | x | x | x | x | x | x | x |
在uart_read_thread线程里,可以自行更改接受数据的方法,保证将接受到的曲线数据put到各自的队列即可
四、代码如下:
#!/usr/bin/env python
#-*-coding:utf-8 -*-
import sys
import time
import signal
import pyqtgraph as pg
import array
import serial
import numpy as np
from queue import Queue
import _thread
import keyboard
color_list=(
'#F0F8FF',
'#FAEBD7',
'#00FFFF',
'#7FFFD4',
'#F0FFFF',
'#F5F5DC',
'#FFE4C4',
'#000000',
'#FFEBCD',
'#0000FF',
'#8A2BE2',
'#A52A2A',
'#DEB887',
'#5F9EA0',
'#7FFF00',
'#D2691E',
'#FF7F50',
'#6495ED',
'#FFF8DC',
'#DC143C',
'#00FFFF',
'#00008B',
'#008B8B',
'#B8860B',
'#A9A9A9',
'#006400',
'#BDB76B',
'#8B008B',
'#556B2F',
'#FF8C00',
'#9932CC',
'#8B0000',
'#E9967A',
'#8FBC8F',
'#483D8B',
'#2F4F4F',
'#00CED1',
'#9400D3',
'#FF1493',
'#00BFFF',
'#696969',
'#1E90FF',
'#B22222',
'#FFFAF0',
'#228B22',
'#FF00FF',
'#DCDCDC',
'#F8F8FF',
'#FFD700',
'#DAA520',
'#808080',
'#008000',
'#ADFF2F',
'#F0FFF0',
'#FF69B4',
'#CD5C5C',
'#4B0082',
'#FFFFF0',
'#F0E68C',
'#E6E6FA',
'#FFF0F5',
'#7CFC00',
'#FFFACD',
'#ADD8E6',
'#F08080',
'#E0FFFF',
'#FAFAD2',
'#90EE90',
'#D3D3D3',
'#FFB6C1',
'#FFA07A',
'#20B2AA',
'#87CEFA',
'#778899',
'#B0C4DE',
'#FFFFE0',
'#00FF00',
'#32CD32',
'#FAF0E6',
'#FF00FF',
'#800000',
'#66CDAA',
'#0000CD',
'#BA55D3',
'#9370DB',
'#3CB371',
'#7B68EE',
'#00FA9A',
'#48D1CC',
'#C71585',
'#191970',
'#F5FFFA',
'#FFE4E1',
'#FFE4B5',
'#FFDEAD',
'#000080',
'#FDF5E6',
'#808000',
'#6B8E23',
'#FFA500',
'#FF4500',
'#DA70D6',
'#EEE8AA',
'#98FB98',
'#AFEEEE',
'#DB7093',
'#FFEFD5',
'#FFDAB9',
'#CD853F',
'#FFC0CB',
'#DDA0DD',
'#B0E0E6',
'#800080',
'#FF0000',
'#BC8F8F',
'#4169E1',
'#8B4513',
'#FA8072',
'#FAA460',
'#2E8B57',
'#FFF5EE',
'#A0522D',
'#C0C0C0',
'#87CEEB',
'#6A5ACD',
'#708090',
'#FFFAFA',
'#00FF7F',
'#4682B4',
'#D2B48C',
'#008080',
'#D8BFD8',
'#FF6347',
'#40E0D0',
'#EE82EE',
'#F5DEB3',
'#FFFFFF',
'#F5F5F5',
'#FFFF00',
'#9ACD32'
)
print(np.shape(color_list))
#串口绘图类
'''
入口参数:
num:曲线通道数量
historyLength:可保存的历史数据长度,即横坐标长度
'''
class Uart_plot:
stop_flag=0#暂停标志位
historyLength = 1000 #横坐标长度
#窗口
win = pg.GraphicsLayoutWidget(show=True)
win.setWindowTitle(u'pyqtgraph chart tool') #建立窗口
win.resize(900, 600) #窗口大小
#图
p = win.addPlot() #把图p加入到窗口中
p.showGrid(x=True, y=True) #把X和Y的表格打开
#p.setRange(xRange=[0, historyLength], yRange=[-1000, 1000], padding=0) #设置区间
p.setLabel(axis='left', text='y-mag') #设置标签
p.setLabel(axis='bottom', text='x-time') #设置标签
p.setTitle('Serial Chart') #表格的名字
num=0
queue_mags=[]#队列
datas=[]#数据
curves=[]#曲线
#绘图线程
timer = pg.QtCore.QTimer()
def __init__(self,num,historyLength):
self.num=num
self.historyLength=historyLength
for j in range(self.num):
self.queue_mags.append(Queue(maxsize=0))
self.datas.append(array.array('d'))
self.datas[j]=np.zeros(self.historyLength).__array__('d')
self.curves.append(self.p.plot(self.datas[j], pen=color_list[2*j]))
def start(self):
self.timer.timeout.connect(self.plotData) #定时调用plotData函数
self.timer.start(1) #多少ms调用一次
def plotData(self):
if keyboard.is_pressed('q'):
print('q is press')
self.stop_flag=1
if keyboard.is_pressed('s'):
print('s is press')
self.stop_flag=0
for j in range(self.num):
if self.stop_flag:
if self.queue_mags[j].empty():
pass
else:
self.queue_mags[j].get()
else:
if self.queue_mags[j].empty():
pass
else:
self.datas[j][:-1] = self.datas[j][1:]
self.datas[j][-1] = self.queue_mags[j].get()
self.curves[j].setData(self.datas[j])
mSerial = serial.Serial(port="COM4", baudrate=921600)
uart_send_x=[0,0,0,0,0]
uart_send_y=[0,0,0,0,0]
#串口发送线程
def uart_send_thread(threadName,delay):
while True:
try:
uart_send_x[0]+=1
if uart_send_x[0]>999:
uart_send_x[0]=-999
uart_send_x[1]-=1
if uart_send_x[1]<-999:
uart_send_x[1]=999
for i in range(5):
time.sleep(delay)
send_arr=str("%1d:%7d,%7d"%(i,uart_send_x[i],uart_send_y[i])).encode("utf-8")
if mSerial.is_open:
mSerial.write(send_arr)
except:
pass
#串口接受线程
def uart_read_thread(threadName,delay):
uart_read_x=[]
uart_read_y=[]
for i in range(uart_plot_ob.num):
uart_read_x.append(0)
uart_read_y.append(0)
while True:
try:
time.sleep(delay)
uart0_read_array=mSerial.read(17)
str_temp=uart0_read_array.decode('utf-8')
uart_read_x[int(str_temp[0])]=int(str_temp[2:9])
uart_read_y[int(str_temp[0])]=int(str_temp[10:17])
uart_plot_ob.queue_mags[int(str_temp[0])].put(uart_read_x[int(str_temp[0])])#将串口接受的数据put到队列里
#print("uart0_read_array",uart0_read_array)
except:
print("uart_read_x",uart_read_x)
mSerial.close()
time.sleep(0.001)
mSerial.open()
print("uart error")
pass
def sig_handler(signum, frame):
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, sig_handler)#ctrl+c可结束
signal.signal(signal.SIGTERM, sig_handler)
app = pg.mkQApp() #建立app
uart_plot_ob=Uart_plot(20,1000)
#开始绘图
uart_plot_ob.start()
#串口接受
_thread.start_new_thread(uart_read_thread,("uart_read_thread",0))
#串口发送(如没有外部串口数据,可在main里打开此线程,并将ch340的tx和rx短接,查看波形)
_thread.start_new_thread(uart_send_thread,("uart_send_thread",0.01))
app.exec_()