PID程序实现
传统PID(位置式PID控制)调节:
这种算法的缺点是,由于全量输出,每次输出均与过去的状态有关,计算时要对
e(k) 进行累加,计算机运算工作量大。而且,因为计算机输出的 u(k) 对应的是执行机构的实际位置,如计算机出现故障, u(k) 的大幅度变化,会引起执行机构位置的大幅度变化,这种情况往往是生产实践中不允许的,在某些场合,还可能造成重大的生产事故,因而产生了增量式
PID 控制算法。
代码如下:
1 import matplotlib.pyplot as plt 2 class Pid: 3 def __init__(self,set_value = 100,now_value = 0,error_sum = 0,error_value = 0,error_last = 0,kp = 0,ki = 0,kd = 0): 4 self.set_value = set_value 5 self.now_value = now_value 6 self.error_sum = error_sum 7 self.error_value = error_value 8 self.error_last = error_last 9 self.kp = kp 10 self.ki = ki 11 self.kd = kd 12 pid = Pid(100,100,0,0,0,0.7,0.1,0.1) 13 data = [] 14 i = 100 15 while i: 16 pid.error_value = pid.set_value - pid.now_value 17 pid.error_sum += pid.error_value 18 pid.now_value = pid.kp * (pid.error_value + pid.ki * pid.error_sum + pid.kd * (pid.error_value - pid.error_last)) 19 print(pid.now_value) 20 data.append(pid.now_value) 21 pid.error_last = pid.error_value 22 i = i - 1 23 #打印输出图表的部分 24 plt.plot(data) 25 plt.title("kp=" + (str)(pid.kp) + " ki=" + (str)(pid.ki) + " kd=" + (str)(pid.kd)) 26 plt.ylabel('output') 27 plt.xlabel('i') 28 plt.show()
波形如下(kp,ki,kd的参数需自行调节):
增量式PID控制调节:
代码如下:
import matplotlib.pyplot as plt class Pid: def __init__(self,set_value = 100,now_value = 0,add_value = 0,last_value = 0,error_value = 0,error_last = 0,error_last_last = 0,kp = 0,ki = 0,kd = 0): self.set_value = set_value self.now_value = now_value self.add_value = add_value self.last_value = last_value self.error_value = error_value self.error_last = error_last self.error_last_last = error_last_last self.kp = kp self.ki = ki self.kd = kd pid = Pid(100,100,0,0,0,0,0,0.9,0.07,0.02) data = [] i = 100 while i: pid.error_value = pid.set_value - pid.now_value pid.add_value = pid.kp * (pid.error_value - pid.error_last) + pid.ki * pid.error_value + pid.kd * (pid.error_value - 2 * pid.error_last + pid.error_last_last) pid.now_value += pid.add_value print(pid.now_value) data.append(pid.now_value) pid.error_last = pid.error_value pid.error_last_last = pid.error_last i = i - 1 plt.plot(data) plt.title("kp=" + (str)(pid.kp) + " ki=" + (str)(pid.ki) + " kd=" + (str)(pid.kd)) plt.ylabel('output') plt.xlabel('i') plt.show()
波形如下((kp,ki,kd的参数需自行调节)):
本文来自博客园,作者:Air-Liu,转载请注明原文链接:https://www.cnblogs.com/ghost-98210/p/11201569.html