%
% PID Controller Design Demos for Matlab and Simulink
%
% Bora Eryilmaz, Jan 16, 2009, The MathWorks, Inc.

%% SLIDE 7
%% A proportional (P) controller
Kp = 2; Cp = tf(Kp, 1)

%% An integral (I) controller
Ki = 3; Ci = tf(Ki, [1 0])

%% A derivative (D) controller
Kd = 5; Cd = tf([Kd 0], [0.01 1])

%% Combine them to get an "ideal" PID controller
Cpid = Cp + Ci + Cd


%% SLIDE 9
%% Desirable first-order process responses
for K = 1:5
  L(:,:,K) = tf(K, [1 0]);
end
% Closed-loop responses
T = feedback(L, 1);
step(T)


%% SLIDE 10
%% Design a PI controller for a first-order plant
% Open-loop plant
Ko = 3.3, vo = 0.2
P = tf(Ko, [vo 1])

% Desired parameter (gain)
K = 20

% Compute PI controller
Kp = vo*K/Ko, Ki = K/Ko
C = tf([Kp Ki], [1 0])

% Check the open- and closed-transfer functions
L = minreal(P*C)
T = minreal(L/(1+L))
step(P,T)

%% Build this PI control system in Simulink
open_system('pid_demo1')


%% SLIDE 11
%% Desirable second-order process responses
a = 0.5;
for K = 1:5
  L(:,:,K) = tf(K, [a 1 0]);
end
% Closed-loop responses
T = feedback(L, 1);
step(T)


%% SLIDE 12
%% Design a PID controller for a second-order plant
% Open-loop plant
Ko = 0.05, zo = 0.1, wo = 0.2
P = tf(Ko, [1 2*zo*wo wo^2])

% Desired parameters
K = 0.1, a = 8

% Compute PID controller
Kp = K/Ko*(2*zo*wo-a*wo^2)
Ki = K/Ko*wo^2
Kd = K/Ko*(1-2*zo*wo*a+a^2*wo^2)
Td = a
C = tf([(Kd+Kp*Td) (Kp+Ki*Td) Ki], [Td 1 0])

% Check the open- and closed-transfer functions
L = minreal(P*C)
T = minreal(L/(1+L))
step(P,T)

%% Build this PID control system in Simulink
open_system('pid_demo1')

%% Using SISOTOOL for PID controller design
sisotool(P)
