%% Matlab script for testing the PI controller for a first-order system.  
%% Written by Philippe Lucidarme
%% http://www.lucidarme.me

close all;
clear all;
clc;


%% Specify the system parameters : Y/Yc=b/(z-a)
a=0.992;
b=0.012;
DeltaT=0.001;


%% Compute time constante (open loop system)
Tau=-DeltaT/log(a);
disp (sprintf ('Open loop time constant = %f s',Tau));
disp (sprintf ('For stability, K must be in ]0 ; %f[',2/b));

% We keep the same time constant as the open loop system
K=(1-a)/b;


%% Initialize the first step of the system
t(1)=0;
input(1)=0;
ol(1)=0;
cl(1)=0;


%% Compute the output of the system (open and close loop)
for i=2:1/DeltaT
    t(i)=t(i-1)+DeltaT;    
    input(i)=1; %input(i-1)+0.1;
    ol(i)=b*input(i-1) + a*ol(i-1);
    cl(i)=K*b*input(i-1) + (1-K*b)*cl(i-1);
    
end


%% Display system output
figure;
plot (t,input,'k');
hold on;
plot (t,ol,'r');
plot (t,cl,'b');
grid on;
xlabel ('Time [s]');
legend ('Input (unit step)','open loop','closed loop');