Generate c function from simulink subsystem

5 views (last 30 days)
NV
NV on 30 Nov 2023
Edited: madhan ravi on 1 Dec 2023
I am trying to compile a single simulink subsystem to a c function.
My goal is to design a simulink/ programming excercise for students. The students would get a template for both simulink and c code. I would like to be able to export a subsystem, made by students, to a c function, that can be imported to the c code.
An example would be: (gain_sys is just a gain for this example)
c code template:
int main(){
int input = 1;
int output = gain_sys(input);
printf("%d\n", output);
}
int gain_sys(int input){
return input*2;
}
To clarify: The students shouldn't have to touch the c code. Ideally the generated code should be in a separate file, but copy-pasting it in the main file is fine.
I have tried using the simulink coder, both for compiling the entire system and a single subsystem. However it generated so many files that I'm a bit lost.

Answers (1)

madhan ravi
madhan ravi on 1 Dec 2023
Edited: madhan ravi on 1 Dec 2023
Make the subsytem that you want to create C code as "Atomic Subsystem".
If you have an atomic subsystem in Simulink and you want to generate code specifically for that atomic subsystem, the process is somewhat different. Atomic subsystems are treated as standalone entities, and you can generate code for them individually. Here are the steps:
1. *Transform subsytem to Atomic Subsystem:*
2. *Subsystem Configuration Parameters:* - Right-click on the atomic subsystem and select "Block Parameters." - Go to the "Code Generation" tab.
3. *Configure Code Generation Settings:* - Set the "System target file" to the appropriate target (e.g., "ert.tlc" for Embedded Coder and grt.tlc for Simulink Coder). - Configure other code generation settings based on your requirements.
4. *Code Generation:* - Once the atomic subsystem's code generation settings are configured, you can generate code: - Select "Tools" > "Coder" > "Build" or use the `rtwbuild` or ( slbuild() )command in MATLAB.
5. *Locate Generated Code:* - After the code generation process is complete, you can find the generated code in the specified code generation folder.
It's worth noting that atomic subsystems are generally treated as standalone units during code generation, and the generated code should be focused on the functionality of that specific subsystem. However, dependencies on the overall model structure might still be present if the subsystem interacts with other parts of the model.

Categories

Find more on Simulink Coder in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!