%% PID Controller Design
% Use this script to design a PID controller for a linear plant model using the Tune PID Controller Live Editor task. The Tune PID Controller task lets you interactively refine the performance of the controller to adjust loop bandwidth and phase margin, or to favor setpoint tracking or disturbance. The task generates a response plot that lets you monitor controller performance while you adjust the tuning parameters. The task also generates code for performing the controller design.
% Create an LTI model for your plant.

G = zpk(-5,[-1 -2 -3 -4],6);

%
% Use the Tune PID Controller task to design a controller for this plant, assuming  assuming the standard unit-feedback control configuration of the following diagram.
%
% Using the task, experiment with different controller settings, performance goals, and other parameters and observe the effect on the closed-loop system response.
%
%

% Convert Response Time to Bandwidth
% Bandwidth is equivalent to 2 divided by the Response Time
wc = 2/2.43564;

% PID tuning algorithm for linear plant model
[C,pidInfo] = pidtune(G,'PI',wc);

% Clear Temporary Variables
clear wc

% Get desired loop response
Response = getPIDLoopResponse(C,G,'closed-loop');

% Plot the result
stepplot(Response)
title('Step Plot: Reference tracking')
grid on

% Display system response characteristics
disp(stepinfo(Response))

% Clear Temporary Variables
clear Response

%
% Tune PID Controller automatically writes the tuned controller to the MATLAB® workspace as a pid, pidstd, pid2, or pidstd2 model object, whichever is appropriate for your controller settings. The task stores the controller using the variable name specified in the task summary line. You can use the controller as you would use any other PID model object for control design and analysis. For instance, examine the controller performance against a slightly different plant model, to get a sense of the robustness of the closed-loop system against parameter variation.

G1 = zpk(-5,[-0.75 -2 -3 -4],8);
CL1 = getPIDLoopResponse(C,G1,'closed-loop');
CL = getPIDLoopResponse(C,G,'closed-loop');
step(CL,CL1)

%
% Copyright 2019 The MathWorks, Inc.