I made a design in simulink to implement PID using embedded matlab function. My function is :
function [u,integral,previous_error] = fcn(Kp,Td,Ti,error,previous_error1,integral1)
dt = 1;
Ki= Kp/Ti;
Kd=Kp*Td;
integral = integral1 + error*dt; % integral term
derivative = (error-previous_error1)/dt; % derivative term
u = Kp*error+Ki*integral+Kd*derivative; % action of control
previous_error=error;
%integral=integral;
end
This is how my model looks:(a part of the entire model)
I am getting the following error :
Simulink cannot solve the algebraic loop containing 'pid_block1/MATLAB Function' at time 2.2250754336053813E-8 using the TrustRegion-based algorithm due to one of the following reasons: the model is ill-defined i.e., the system equations do not have a solution; or the nonlinear equation solver failed to converge due to numerical issues.
To rule out solver convergence as the cause of this error, either
a) switch to LineSearch-based algorithm using
set_param('pid_block1','AlgebraicLoopSolver','LineSearch')
b) reducing the ode45 solver RelTol parameter so that the solver takes smaller time steps.
If the error persists in spite of the above changes, then the model is likely ill-defined and requires modification.
Any idea, why am I getting it?
Should i use global variables for integral
and previous_error
here?
Thanks in advance.
Erm.. Unless there is a specific reason why you need it in this form, I would strongly recommend replacing your MATLAB Function block with Simulink blocks such as:
etc....
I've found that Algebraic loop problems are really hard to get rid of and are usually just best to avoid. The method I suggest above can be used for most any controller type and has worked quite nicely for me in the past.
If the issue is neatness, you can always create your own "PID controller" subsystem or library part.
Let me know if you need some more detail or a diagram on how you might do this.