% ex1_pi.m
% Purpose: Illustrate the implementation of a PI controller for
% controlling the process, h_p(s)=(1-2s)/(s+1)(s+2)
%
h_p=tf([0,-2,1],[1,3,2]);   % Process transfer function
sys=ss(h_p);                % State space model
A=sys.a; B=sys.b; D=sys.c;

Ti=1.25; Kp=0.56;           % PI controller parameters
r=1;                        % The reference signal

Dt=0.1; t=0:Dt:20;          % Time horizon for simulation
N=length(t);

hc=Dt*Kp/Ti;            % Controller param. to save computing time
z=0; x=[0;0];           % Initial values for the states
for k=1:N
    y=D*x;              % The measurement output
    e=r-y;              % The controller input
    
    u=z+Kp*e;           % The controller output
    z=z+hc*e;           % Updating the controller state
            
    Y(k,1)=y; U(k,1)=u; % Storing variables
    
    x=x + Dt*(A*x+B*u); % Puting the control to the process
end

plot(t,Y), grid, xlabel('Time'), ylabel('y(t)')
title('Output response of PI controlled system')