% main_exercise2b.m
% Purpose
% Simulation for exercise 2b. PI control of 1st order process
% using simple method for tuning Kp and Ti in PI controller

clear

% Specify parameters in process model, h_p(s)
T=5;
k=0.5;

% Specify reference and time constant for closed loop setpoint reference
r=1;
Tc=2;

% Specify state space model parameters of process model
A=-1/T; B=k/T;

% Specify PI controller paramerers
Kp=T/(k*Tc); 
Ti=T;

% Specify simulation horizon
N=100;
h=T/10;   % step length

% Initial values for the states
x=0;   % system state
z=0;   % controller state

% Main simulation loop
for k=1:N
    y=x;               % Measurement
    
    % PI controller
    e=r-y;
    u=Kp*e+z;
    z=z+h*Kp*e/Ti;
    
    % Store process variables for plotting purposes
    Y(k,1)=y;
    U(k,1)=u;
   
    % Updtate (integrate) process model
    f=A*x+B*u;
    x=x+h*f;
end
figure(1)
subplot(211), plot(U), grid, title('Control input u')
subplot(212), plot(Y), grid, title('Process output y')