界面如下:
由于代码和文件比较多, 所以这里我就不放代码片段了, 大家可以去GitHub去下载.
添加链接描述
其中涉及到关于一些下位机指令的获取, 编写指令集的同学把指令集放在了excel文件中, 所以涉及到从python中读取excel文件. 代码如下:
import xlrd
import os
class command():
def __init__(self):
super().__init__()
self.fileList=[]
self.sendStrList=[] #指令存储在这个二维数组内
def getCommand(self):
self.XLS='.xls'
# 返回一个列表,其中包含在目录条目的名称
self.Path = r'zhilingji'
self.files = os.listdir(self.Path)
for f in self.files:
if(self.XLS in f):
# 添加文件
f.encode('GBK')
self.fileList.append(f)
for i in self.fileList:
list_i=list(i)
list_i.insert(0,'zhilingji\\')
i=''.join(list_i)
self.readbook = xlrd.open_workbook(i)
self.sheet=self.readbook.sheet_by_index(0)
self.sendStrList.append(self.sheet.col_values(0))
return self.sendStrList
这里需要用到两个python模块, xlrd和os, 通过os进入工程目录中的指令集文件夹, 然后再借助xlrd模块从excel中获取到指令集并存储再二维数组中.
本上位机要求设备连上后, 上位机自动连接上串口, 所以我们先要自动获取已经连接的串口(目前仅限自动连接一个). 代码如下:
import serial
import serial.tools.list_ports
import re
import time
#import threading
class MySerial():
def __init__(self):
super().__init__()
self.receivedata=''
self.initSerial()
def initSerial(self):
self.comnumber = self.getcom()
self.ser=serial.Serial(self.comnumber,9600,timeout=0.8)
#threading.Thread(target=self.ReadData).start()
#系统自动获取当前连接的COM口
def getcom(self):
port_list = list(serial.tools.list_ports.comports())
p1 = re.compile(r'[(](.*?)[)]', re.S)
com=''
if len(port_list) == 1:
for i in range(0,len(port_list)):
com=(re.findall(p1,str(port_list[i]))[0])
print(com)
return com
def ReadData(self):
#while True:
self.ser.flush()
self.ser.flushInput()
#time.sleep(0.8)
self.receivedata = self.ser.readline().decode("UTF-8")
#print(self.receivedata.replace('\r\n',''))
#self.ser.close()
return self.receivedata.replace('\r\n','')
def SendData(self,data):
#32接收到的消息是以\r\n***\r\n格式的
self.ser.flush()
self.ser.flushOutput()
self.ser.write(bytes.fromhex('0D 0A'))
self.ser.write(bytes.fromhex(data))
time.sleep(0.6)
self.ser.write(bytes.fromhex('0D 0A'))
self.ser.flush()
其中借助 getcom 函数可以自动识别windows已经连上的串口.
import matplotlib
matplotlib.use("QT5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
#创建一个matplotlib图形绘制类
class MyFigure(FigureCanvas):
def __init__(self,width=1, height=1, dpi=100):
#第一步:创建一个创建Figure
self.fig = Figure(figsize=(width, height), dpi=dpi)
plt.xlabel('时间/t')
plt.ylabel('温度/℃')
#第二步:在父类中激活Figure窗口
super(MyFigure,self).__init__(self.fig) #此句必不可少,否则不能显示图形
#第三步:创建一个子图,用于绘制图形用,111表示子图编号,如matlab的subplot(1,1,1)
#self.axes = self.fig.add_subplot(111)
#第四步:就是画图,【可以在此类中画,也可以在其它类中画】
def plotsin(self):
self.axes0 = self.fig.add_subplot(111)
# t = np.arange(0.0, 3.0, 0.01)
# s = np.sin(2 * np.pi * t)
# self.axes0.plot(t, s)
x=(0,1,2,3,4,5,6,7,8)
y1=(21,23,22,24,28,27,27,27,25)
self.axes0.plot(x,y1)
由于画图部分我是在网上找的别人的, 很多地方他也没解释, 所以我就只在我原来会的基础上改了一下图像.
由于此部分他们还没有需求再加上快要期末考试了, 所以就还没做.