📄 pid.m
字号:
function K=PID(Wn)
delta_t=0.1;
v=0.707;%Wn=2;
S=[1 2*v*Wn Wn^2]; % define desired closed-loop charateristic polynomial s^2+2yWn*s+Wn^2;
r_s=roots(S); % calculate roots
% calculate discrete poles
p1=exp(delta_t*r_s(1)); % convert to discrete poles
p2=exp(delta_t*r_s(2));
p3=0; % the rest of the discrete poles are positioned at 0
p4=0;
P=[p1 p2 p3 p4];
% define r1,r2,r3,r4
T=poly(P); % calculate the coefficients of T(z)
r1=T(2);
r2=T(3);
r3=T(4);
r4=T(5);
% transfer 1/s(s+1) to discrete model
nums=1;
dens=conv([1 1],[1 0]);
Gs=tf(nums,dens); % continuous time
delta_t=0.1;
Gz=C2D(Gs,delta_t); % Gz is the discrete model
[num,den]=c2dm(nums,dens,delta_t);
%we get a1,a2,b1,b2 of G(z)
a1=den(2);
a2=den(3);
b1=num(2);
b2=num(3);
% define four parameters of C(Z)
K=zeros(4,1);
% define A
A=[1 b1 0 0;
a1-1 b2 b1 0;
a2-a1 0 b2 b1;
-a2 0 0 b2];
% define B
B=[r1+1-a1;
r2+a1-a2;
r3+a2;
r4];
%calculate K: B=A*K, then K=inv(A)*B
K=inv(A)*B;
f1=K(1);
k0=K(2);
k1=K(3);
k2=K(4);
%define the PID controller C(z)
num1=[k0 k1 k2];
den1=conv([1 f1],[1 -1]);
Cz=tf(num1,den1,delta_t);
% define the transfer function of the closed-loop PID controller system
S_o=Gz*Cz; % S_o is open-loop transfer funtion
S_c=feedback(S_o,1); % S_c closed-loop transfer function
% transfer to state space model
[A,B,C,D,Ts]=ssdata(S_c);
[n_output,n_state]=size(C);
[n_state,n_input]=size(B);
% initial condition
x=zeros(n_state,1);
Ns=200;
u1=ones(Ns,1);
y1=zeros(Ns,1);
% simulation starts
for i=1:Ns
u=u1(i);
x=A*x+B*u; % x(k+1)=Ax(k)+Bu(k);
y=C*x; % y(k+1)=Cx(k+1);
y1(i)=y;
end
t=0:delta_t:delta_t*(Ns-1);
plot(t,y1);%grid;
xlabel('Time:second');
ylabel('step response');
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -