使用Python的tkinter和matplotlib模块在GUI界面中绘制PID交互曲线,用以观察各参数对PID控制的影响
最近学PID控制,想要直观的观察PID各部分参数对PID控制的影响,就用Python写了一个界面,总的来说并不复杂,如下:
pid_GUI.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:makang
# Description: 绘制PID交互曲线,可以观察到Kp,Ki,Kd各参数对PID控制的影响
import tkinter as tk
import PID
import matplotlib as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
# 绘图函数
def drawPic():
global r, g, b
# 清空图像,以使得前后两次绘制的图像不会重叠
# drawPic.f.clf()
drawPic.a = drawPic.f.add_subplot(111)
drawPic.a.grid(color='k', linestyle='-.')
TestPID(Kp, Ki, Kd)
# 每次绘图改变线条颜色用以区别----第一种方法
# drawPic.a.plot(PositionalXaxis, PositionalYaxis, color=(r, g, b) ) # 绘制图形
# r -= 0.15; g-=0.15; b-=0.15
# if r < 0: r=0
# if g < 0: g=0
# if b < 0: b=0
# 每次绘图改变线条颜色用以区别----第二种方法
color = ['b', 'r', 'y', 'g', 'grey', 'coral', 'darkgreen', 'c', 'cyan', 'steelblue']
drawPic.a.plot(PositionalXaxis, PositionalYaxis, color=color[np.random.randint(len(color))] ) # 绘制图形
drawPic.canvas.draw()
#每次绘图完毕清空x,y
PositionalXaxis.clear()
PositionalYaxis.clear()
# 测试PID程序
def TestPID(P, I, D):
global PositionalXaxis, PositionalYaxis, fig_num
PositionalPid = PID.PositionalPID(P, I, D)
for i in range(1, 500):
# 位置式
PositionalPid.SetStepSignal(100.2)
PositionalPid.SetInertiaTime(3, 0.1)
PositionalYaxis.append(PositionalPid.SystemOutput)
PositionalXaxis.append(i)
# 改变Kp
def Kp_enlarge():
global Kp, Ki, Kd
Kp += 0.2
var_kp.set('%.2f'%Kp)
drawPic()
return Kp
def Kp_reduce():
global Kp
Kp -= 0.2
if Kp<=0:
Kp=0
var_kp.set('%.2f'%Kp)
drawPic()
return Kp
# 改变Ki
def Ki_enlarge():
global Ki
Ki += 0.2
var_ki.set('