%
%  Script for finding the effective delay approximation
%                                   writen by: Chriss Grimholt

global gc gp y t

    simtime = 200;

    steptime = 1;
    disturbancetime = 1;
    stepvalue = 1;          % setpoint response
    disturbancevalue = 0;

    gfeedback = tf(1);  % Closed-loop
    
    res = [];
    
    s = tf('s');

    simnum = [0.1:0.1:1,2:1:100]; % different FOPTD lag constants
    
for tp = simnum

gp = 1/(tp*s+1);  % giving the FOPTD model
gp.outputd=1;

kc0=0.5*tp/gp.outputd;  % calculating initial controller gain


[kc fval]= fsolve(@(kc) fun(kc),kc0);  % Finding controller gain that gives
                                       % overshoot = 0.3

gc = controller (0,kc,0);   % porpotional controller

sim('model_approx')

[pks,locs] = findpeaks(y);      % Finding peaks

t_yp = t(locs(1))-steptime;     % time to first peak

y_max = pks(1);                 

y_inf = y(end);

D = (y_max-y_inf)/y_inf;           % overshoot

theta_t_yp = gp.outputd/t_yp;       % delay/time til first peak

tp_theta = tp/gp.outputd;           % lag constants / delay

res =  [res; tp_theta theta_t_yp D];

end
