How to generate code that accepts Simulink block parameters as an argument to the model step function?

23 views (last 30 days)
I have a complex project that I am generating code for. The Simulink model uses block paramters that are defined in the matlab workspace by configuration files. The config files look like the following:
config.param1 = 1
config.param2 = 2
assignin('caller','config',config)
The generated C++ code declare these param1 and param2 as global variables and the step function has the following declaration:
void Model_step(void);
The parameters are declared in Model_private.h like this:
/* Imported (extern) block paramters */
extern real_T param1;
extern real_T param2;
I want the code generated so that I can pass param1 and param2 to the step function so that the declaration looks like this:
struct {
param1
param2
} param_type
void Model_step(param_type);
How can I do that?

Answers (1)

Abhas
Abhas on 16 Nov 2024 at 6:00
Hi @Mohammed Afandi,
To modify the generated C++ code so that parameters are passed to the "Model_step" function as a structured type using Simulink and Embedded Coder, follow these steps:
Part 1: Environment Setup
  • Open your Simulink model.
  • In the Apps gallery, select "Embedded Coder".
  • On the "C++" Code tab, choose "Embedded Code - C++".
Part 2: Configure Code Mappings
  • Go to "Code Interface > Code Mappings".
  • In the "Functions" tab, find "model_step".
  • Click the hyperlink in "Function Preview" to edit the function signature.
  • Define a "param_type" struct with your parameters and set it as the input argument for "model_step".
You may also refer the below documentation to Configure Parameters for C++ Interface Code Generation: https://www.mathworks.com/help/ecoder/ug/configure-parameters-for-c-code-generation.html
Part 3: Define Parameter Structure
  • Create a header file (model.h) and define the struct:
typedef struct {
real_T param1;
real_T param2;
} param_type;
  • Ensure "model.h" is included in relevant files.
Part 4: Generate and Verify Code
  1. Click "Generate Code" in the Embedded Coder app.
  2. Check "model.cpp" to confirm "Model_step" uses "param_type":
void Model_step(param_type params) {
// Use params.param1 and params.param2
}
This approach ensures parameters are passed as a structured type, enhancing code clarity and organization.
You may refer to the below MathWorks documentation links to know more about the same:
  1. https://www.mathworks.com/help/ecoder/ref/codemappingsceditor.html
  2. https://www.mathworks.com/help/rtw/ref/model_step.html
I hope this helps!

Community Treasure Hunt

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

Start Hunting!