PID主要位置式和增量式两种
前提你得装上matplotlib这个库,这个库可以非常清楚的绘制数据的曲线图。如果不装的话可以返回一个列表
import matplotlib.pyplot as plt
class Pid():
"""这里定义了一个关于PID的类"""
def __init__(self, exp_val, kp, ki, kd):
self.KP = kp
self.KI = ki
self.KD = kd
self.exp_val = exp_val
self.now_val = 0
self.sum_err = 0
self.now_err = 0
self.last_err = 0
def cmd_pid(self):
self.last_err = self.now_err
self.now_err = self.exp_val - self.now_val
self.sum_err += self.now_err
# 这一块是严格按照公式来写的
self.now_val = self.KP * (self.exp_val - self.now_val) \
+ self.KI * self.sum_err + self.KD * (self.now_err - self.last_err)
return self.now_val
pid_val = []
#对pid进行初始化,目标值是1000 ,p=0.1 ,i=0.15, d=0.1
my_Pid = Pid(1000, 0.1, 0.15, 0.1)
# 然后循环100次把数存进数组中去
for i in range(0, 100):
pid_val.append(my_Pid.cmd_pid())
plt.plot(pid_val)
plt.show()
这就是离散化 PID 的增量式表示方式,由公式可以看出,增量式的表达结果和最近三次的偏差有关,这样就大大提高了系统的稳定性。需要注意的是最终的输出结果应该为 u(K)+增量调节值;
import matplotlib.pyplot as plt
class Pid():
def __init__(self, exp_val, kp, ki, kd):
self.KP = kp
self.KI = ki
self.KD = kd
self.exp_val = exp_val
self.now_val = 0
self.now_err = 0
self.last_err = 0
self.last_last_err = 0
self.change_val = 0
def cmd_pid(self):
self.last_last_err = self.last_err
self.last_err = self.now_err
self.now_err = self.exp_val - self.now_val
self.change_val = self.KP * (self.now_err - self.last_err) + self.KI * \
self.now_err + self.KD * (self.now_err - 2 * self.last_err
+ self.last_last_err)
self.now_val += self.change_val
return self.now_val
pid_val = []
my_Pid = Pid(1000000, 0.1, 0.15, 0.1)
for i in range(0, 30):
pid_val.append(my_Pid.cmd_pid())
plt.plot(pid_val)
plt.show()