How to integrate PID controller coded by C with my simulink block?
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to integrate my PID controller code by C into my Simulink model using matlab function block.
I want to initialize the integrator into 0 when the simulation starts and then use the returned integral value, however, I don't know how to initialize the integrator.
My C code and the code in the matlab function block are below.
C code :
void Roll_CTLR(double Roll_CMD, FBData* Data, double* integral, double *Roll_out)
{
double pi = 3.1415926535;
double D2R = pi / 180;
double P_gain = 2.5;
double I_gain = 0.05;
double error = (Roll_CMD - Data->Roll_angle) * D2R;
double p_val = error * P_gain;
double i_val = error * I_gain * 0.01;
*integral = i_val;
*Roll_out = p_val + i_val;
}
Matlab code :
function out = Roll_controller(Roll_CMD, Roll_angle, Roll_rate)
out = 0;
Pitch = 0;
Yaw = 0;
intg = coder.opaque('static double*','0');
s = struct('Roll_rate',Roll_rate,'Pitch_rate',Pitch,'Yaw_rate',Yaw,'Roll_angle',Roll_angle,'Pitch_angle',Pitch,'Heading_angle',Yaw);
coder.cstructname(s,'FBData','extern','HeaderFile','Multicopter_CTLR.h');
coder.ceval('Roll_CTLR', Roll_CMD, coder.ref(s), coder.ref(intg), coder.ref(out));
When I executed the code, there is no error, but the result is different what I thought.
I think this is because the integrator is initialized in every execution, so the integrator doesn't work what I wanted.
How can I modify the code to make the integrator works right?
1 commentaire
Nathan Hardenberg
le 5 Juin 2023
To initialize the Variables only once you can use persistent variables (see example below). But I don't see where you change "out", "Pitch" and "Yaw" in your Code. But maybe I'm missing something
persistent out
persistent Pitch
persistent Yaw
if isempty(out)
out = 0;
Pitch = 0;
Yaw = 0;
end
Réponses (0)
Voir également
Catégories
En savoir plus sur Simulink Environment Fundamentals dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!