matlabderivativeintegralpid-controller

How to get errors from PID?


Need to add PID controller. Can you help me how to get error, integration error and derivative error from PID? I need this values to generate PID parameters by genetic alghorithm.

J = 0.01;
b = 0.1;
K = 0.01;
R = 1;
L = 0.5;

A = [-b/J   K/J
    -K/L   -R/L];
B = [0
    1/L];
C = [1   0];
D = 0;
sys = ss(A, B, C, D); 

Ts = 1/10;
T = 3.5;

sysd = c2d(sys, Ts); 

t = 0:Ts:T; 
nSamples = length(t); 

y = NaN(1, nSamples); 
u = ones(1, nSamples); 
X = [0; 0]; 
for i=1:nSamples       
    y(i) = sysd.C * X + sysd.D * u(i);
    X = sysd.A * X + sysd.B * u(i);
end

figure;
step(sys);

figure;
plot(t, y, 'r')

Solution

  • Thankfully, many people have already designed PID controllers in MATLAB, so you can learn from their examples. Here is a PID controller from the MATLAB File Exchange. The derivative and integral of the error are saved in the variables "Der" and "Int" respectively.

    If you have the Control Systems Toolbox installed with your copy of MATLAB then you already have access to powerful built-in functionality for designing PID controllers. You may want to take advantage of PID tuner.