# PID控制的MATLAB仿真（1）

## 1. 简介

PID控制应用广泛，说起来PID特别的简单，在比例负反馈的基础上加入微分项实现快速调节，加入积分项实现无静差。MATLAB强大的功能让学习变得非常简单。在学习智能控制这门课的时候，老师推荐了刘金琨老师的先进PID控制一书，边看边学边调程序。下文程序选自此书。

## 2. 模拟PID

%S-function for continuous state equation
function [sys,x0,str,ts]=s_function(t,x,u,flag)
switch flag,
%Initialization
case 0,
[sys,x0,str,ts]=mdlInitializeSizes;
%Outputs
case 3,
sys=mdlOutputs(t,x,u);
%Unhandled flags
case {2, 4, 9 }
sys = [];
%Unexpected flags
otherwise
error(['Unhandled flag = ',num2str(flag)]);
end
%mdlInitializeSizes
function [sys,x0,str,ts]=mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates  = 0;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 1;
sizes.NumInputs      = 3;
sizes.DirFeedthrough = 1;
sizes.NumSampleTimes = 0;
sys=simsizes(sizes);
x0=[];
str=[];
ts=[];
function sys=mdlOutputs(t,x,u)
error=u(1);
derror=u(2);
errori=u(3);

kp=60;
ki=1;
kd=3;
ut=kp*error+kd*derror+ki*errori;
sys(1)=ut;

## 3. 离散系统PID

1/(1+s)

%Discrete PID control for continuous plant
clear all;
close all;

ts=0.001;  %Sampling time
xk=zeros(2,1);
e_1=0;
u_1=0;

for k=1:1:2000
time(k) = k*ts;

yd(k)=0.50*sin(1*2*pi*k*ts);

para=u_1;
tSpan=[0 ts];
[tt,xx]=ode45('chap1_6plant',tSpan,xk,[],para);
xk = xx(length(xx),:);
y(k)=xk(1);

e(k)=yd(k)-y(k);
de(k)=(e(k)-e_1)/ts;

u(k)=20.0*e(k)+0.50*de(k);
%Control limit
if u(k)>10.0
u(k)=10.0;
end
if u(k)<-10.0
u(k)=-10.0;
end

u_1=u(k);
e_1=e(k);

D=1;
if D==1  %Dynamic Simulation Display
plot(time,yd,'b',time,y,'r');
pause(0.00000000000000000);
end
end
figure(1);
plot(time,yd,'r',time,y,'k:','linewidth',2);
xlabel('time(s)');ylabel('yd,y');
legend('Ideal position signal','Position tracking');
figure(2);
plot(time,yd-y,'r','linewidth',2);
xlabel('time(s)'),ylabel('error');