1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import matplotlib.pyplot as plt import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
def limit(a,b): if a>b: return b else: return a
class PID_incremental(): def __init__(self,wantted,Kp,Ki,Kd,delta_time): self.Kp=Kp self.Ki=Ki self.Kd=Kd self.wantted_val=wantted self.time=delta_time self.sum_err = 0 self.now_err = 0 self.last_err = 0 self.TotalMax = 1100 self.last_val = 0 self.last_last_val = 0 self.now_val = 0 self.last_control = 0 self.last_last_control = 0 self.now_control = 0 def iterator(self): '''Z变换后的输出量和控制量之间的关系 Y(k)=133*T^2*U(k-2)+(2-25*T)*Y(k-1)+(25*T-1)*Y(k-2)''' self.now_val = 133*(self.time)**2*self.last_last_control+ (2-25*self.time)*self.last_val+(25*self.time-1)*self.last_last_val self.last_last_err = self.last_err self.last_err = self.now_err self.now_err = self.wantted_val - self.now_val self.change_control = 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_control += self.change_control*self.time self.now_control = limit(self.now_control,self.TotalMax) self.last_last_control = self.last_control self.last_control = self.now_control self.last_last_val = self.last_val self.last_val = self.now_val return self.now_val pid_incremental_bf=PID_incremental(133,300,0.0,0.0,0.01) pid_incremental_af=PID_incremental(133,150,0.015,0.01,0.01) pid_incremental_val_bf=[] pid_incremental_val_af=[] for i in range(100): pid_incremental_val_bf.append(pid_incremental_bf.iterator()) pid_incremental_val_af.append(pid_incremental_af.iterator()) x=np.arange(0,100) plt.title("增量式PID") plt.xlabel('step/s') plt.ylabel('current_value') plt.plot(x,pid_incremental_val_bf) plt.plot(x,pid_incremental_val_af) plt.legend(['Adjust_Before','Adjust_After'])
|