How to integrate PID controller coded by C with my simulink block?

13 次查看(过去 30 天)
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.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 个评论
Nathan Hardenberg
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;


回答(0 个)


Help CenterFile Exchange 中查找有关 Simulink Environment Fundamentals 的更多信息




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by