% Exercise about tuning rules for integrating plus
% time delay process, h_p=k*exp(-tau*s)/s,
% using 
% 1. SIMC tuning rules, Ti=4*(Tc+tau), Kp=1/(k*(Tc+tau))
% 2. Tuning rules deduced in lecture,
% Ti=2*T0, Kp=2/(k*tau)
% for T0 specified.

% Model parameters
k=1;       % The gain velocity, slope of integrator
tau=1;     % The time delay

% Define Laplace operator, s, and model transfer function.
s=tf('s');
hp=k*exp(-tau*s)/s;

% Different PI controller settings.
itun=2;

if itun == 1     % SIMS tuning rules with Tc=tau
    Kp=1/(2*k*tau);
    Ti=8*tau;
elseif itun == 2 % Our deduced tuning rules..
    T0=1.5;   % (Try T0=1.5, 2, 4 and 6)
    Kp=2/(k*T0);
    Ti=2*T0;
end

hc=Kp*(1+Ti*s)/(Ti*s);

% The loop transfer function
h0=hc*hp;

% Calculate the margins
[Gm,Pm,W180,Wc] = margin(h0)

dtau_max=Pm*(pi/180)/Wc   % Maximum time delay error

% Step response from reference, r, to output, y.
% Pade approx for time delay
hp_approx=k*(1-tau*s/2)/(s*(1+tau*s/2));
h0_approx=hc*hp_approx;
h_ry=h0_approx/(1+h0_approx);

step(h_ry)
