% Function: ex3b_half.m
% Simulating integrator+delay process with PI-controller
% and the Skogestad and some alternative settings

%clear all

v=0;             % Disturbance
r=1;             % reference
kg=1; tau=1;     % slope and time delay, hp=kg*exp(-tau*s)/s;

dt=0.1;          % Sampling time
t=0:dt:80; t=t'; % Simulation time interval
N=length(t);     % Number of discrete time instants

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

itun=3;
if itun == 1
   Kp=1/(2*kg*tau); Ti=8*tau;          % Skogestad setting. SIMC rules.
elseif itun == 3
   Kp=1/(2*kg*tau); Ti=5.83*tau;       % Settings in this note
elseif itun == 2
   Kp=1/(2*kg*tau); Ti=4*tau           % Buttherworth setting
end

x=0; z=-v;
Delay=Delay+x;
for k=1:N
    yp=x;
    %%% 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(40/dt); v=1; end
    
    % PI controller
    e=r-y;
    u=Kp*e+z;
    z=z+dt*Kp*e/Ti;
    
    % Save for plotting
    Y(k,1)=y;
    R(k,1)=r;
    
    % Process
    x=x+dt*kg*(u+v);
end

plot(t,Y,'-k',t,R,'-.'), grid
legend('Output, y','Reference, r')