% ex1_pi_anti.m
% Purpose: Illustrate the implementation of a PI controller for
% controlling the process, h_p(s)=(1-2s)/(s+1)(s+2)
% -Implementation of Anti-Windup
%
clear all

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, SIMC rules
r=1;                        % The reference signal

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

v=0.7; u_max=5; u_min=0;
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(k,1)=z;
        
    if u>u_max          % Handeling constraints and Anti-windup
        u=u_max; 
        z=z;  
        %z=u-Kp*e; 
        %z=z+Dt*Kp*e/Ti +Dt*(u_max-u)/Ti;
    elseif u<u_min;
        u=u_min;
        z=z;
    else        
        z=z+Dt*Kp*e/Ti;     % Updating the controller state
    end
    
    Y(k,1)=y; U(k,1)=u; % Storing variables
    
    up=u+v;
    x=x + Dt*(A*x+B*up); % Puting the control to the process
end

U_max=u_max*ones(size(t'));
subplot(311), plot(t,Y), grid, xlabel('Time'), ylabel('y(t)')
title('Output response of PI controlled system')
subplot(312), plot(t,[U U_max]), grid, xlabel('Time'), ylabel('u(t)')
subplot(313), plot(t,Z), grid, xlabel('Time'), ylabel('z(t)')