% Example
% Controlling 1st order+time delay system with a PI controller tuned with
% the SIMC method
clear all

tic

% System parameters
K=2; T=30; tau=4;
A=-1/T; B=K/T;

% Def. sampling time and time horizon
dt=0.01;
t=0:dt:180;
N=length(t);

% Define array for programming the delay
nt=tau/dt;       % Size of array to implement time delay
Delay=zeros(nt,1); % arrays to make time delay, hold (nt) samples

% The SIMC PI parameters
Tc=tau;
c=4; %c=2.7;
Ti=min(T,c*(Tc+tau));
Kp=T/(K*(Tc+tau));

% Initial and fixed variables
x=0; z=0; r=1; v=0;
hc=dt*Kp/Ti; % Fixed param. used in the PI algorithm.

X=zeros(N,1); Y=zeros(N,1);
for k=1:N
    
    yp=x;  % Want to delay this variable tau time instants
    
    %%% Implementation of time delay, using array method.
    % programming of time delay for process model, 
    % hold (y) in array of length (nt) samples
    y=Delay(nt); % the delayed process output Y=y(i-nt)
    for id=nt:-1:2;
      Delay(id)=Delay(id-1);
    end
    Delay(1)=yp;
    %%% End implementation of time delay
    
    if k>floor(35/dt); v=1; end  % Disturbance v=1 at t=30
    
    % The PI controller
    % PI controller
    e=r-y;
    u=Kp*e+z;
    z=z+hc*e;
    
    % Sture variables for e.g. plotting
    X(k)=x; Y(k)=y;
    
    % Feed control u to the plant (integrate process model)
    x=x+dt*(A*x+B*(u+v));
end
toc

figure(1)
plot(t,Y), grid
title('Output y')
xlabel('Continuous time')