Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Code Generation

Simulink Code Generation: Workflow, Simulink Coder and Embedded Coder

Generate C code from a Simulink model: prepare the model, set a fixed-step solver and target, build, read the generated files, call the step function and trace code to blocks.

A big reason companies use Simulink is that the same model that you simulate can be turned into C or C++ code for a microcontroller, a real-time computer or a PC. That removes a hand-translation step, keeps model and code consistent and lets you test the logic early. This lesson explains the workflow, the settings that matter and what the generated code looks like.

Simulink Coder and Embedded Coder are commercial MathWorks products and cannot run on this site. We describe the settings and files exactly, and we use a tiny Python code generator (labelled as a stand-in) to show how a block diagram becomes C. The C snippets that look like generated code are illustrative, written by us, not captured from the product.

Which product does what

Product Purpose
Simulink Coder Generates C/C++ from Simulink models and runs them on a host or real-time target (generic real-time target grt.tlc).
Embedded Coder Adds production-quality features: compact readable code (ert.tlc), a code interface you control, data dictionary mapping, traceability reports, MISRA C checks, SIL and PIL testing, AUTOSAR, and code metrics.
MATLAB Coder Generates C from MATLAB code (not from models).
HDL Coder Generates Verilog/VHDL for FPGAs.
Simulink PLC Coder Generates IEC 61131-3 structured text for PLCs.

You need MATLAB, Simulink and Simulink Coder as a minimum, and Embedded Coder for production embedded work, plus a C compiler on the machine (a MinGW or Visual Studio setup configured with mex -setup).

Prepare the model

A model that generates good code:

  1. Uses a fixed-step solver (Model Settings > Solver > Type: Fixed-step; Solver: discrete (no continuous states) when the controller is purely discrete, and a Fixed-step size such as 0.001). Variable-step solvers cannot run in a real-time loop.
  2. Contains only blocks that support code generation (the block's documentation page has an Extended Capabilities section listing C/C++ Code Generation). Scopes and To Workspace are ignored on the target; they do not break the build.
  3. Has sample times that fit the base rate (multiples of the fixed step); multi-rate models generate several tasks.
  4. Defines data types explicitly (single, int16...), not everything as double, because embedded targets are often 32-bit and have no double-precision FPU.
  5. Has named signals and parameters that you want to keep readable in the code.

Separate the controller (the part you generate) from the plant model (simulation only) with a subsystem or, better, a model reference, so only the controller goes into the build.

Configure code generation

Open Modeling > Model Settings (Ctrl+E) and go to Code Generation:

  • System target file: grt.tlc (Generic Real-Time Target, a runnable executable on the host), ert.tlc (Embedded Real-Time, with Embedded Coder), or a hardware-specific target.
  • Language: C or C++.
  • Build process: Generate code only (checked) to produce files without compiling, or leave unchecked to also build an executable.
  • Interface: Code interface packaging (nonreusable function, reusable function, or C++ class), data exchange, Support: continuous time (leave off for embedded).
  • Optimization: Default parameter behavior (Inlined makes parameters constants in code, Tunable keeps them as variables), Remove code from floating-point to integer conversions, Use division for fixed-point net slope computation.
  • Report: Generate code generation report and Static code metrics report.
  • Hardware Implementation: the Device vendor and Device type (for example ARM Cortex-M), word lengths and endianness. This controls data type sizes in the generated code, so set it correctly.

Then press Ctrl+B (or the Build button in the Apps > Embedded Coder tab). From the command line:

MATLAB
set_param('controller', 'SystemTargetFile', 'ert.tlc');
set_param('controller', 'GenCodeOnly', 'on');
set_param('controller', 'SolverType', 'Fixed-step');
rtwbuild('controller');

What gets generated

The build creates a folder controller_ert_rtw next to the model. Typical contents:

File Contents
controller.c The algorithm: controller_step, controller_initialize, controller_terminate
controller.h Declarations of the model data structures and function prototypes
controller_data.c Constant and parameter data
controller_types.h, rtwtypes.h Type definitions, such as real_T, uint8_T
ert_main.c An example main program (a scheduler skeleton), not production code
html/controller_codegen_rpt.html The code generation report with traceability

The standard data structures (names vary with settings) are:

  • rtU (ExtU_controller_T): the model's inputs.
  • rtY (ExtY_controller_T): the outputs.
  • rtDW (DW_controller_T): states and internal data (discrete states, unit delays).
  • rtP: tunable parameters (only if the parameters are tunable).

Your hand-written application fills rtU, calls controller_step() at the base rate and reads rtY. The generated code never starts timers: your OS or interrupt does.

A stand-in: how a block diagram becomes C

The Python below takes a tiny diagram (a Gain, a Unit Delay and a Sum) and writes a step function in the same shape as the generated code. It is a teaching toy that shows the idea of ordering blocks by data dependency and keeping state in a structure; the real coder is far more capable and its output differs.

Python Stand-in: a toy code generator for a small block diagram

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed C has the same three parts you will see in the real output: local values computed in dependency order, an update of the stored state at the end of the step, and inputs and outputs accessed through structures.

Reading the real report

Open the code generation report (a link appears when the build ends, or View Report in the Apps tab). It contains:

  • A Summary (version, target, solver, warnings).
  • Subsystem Report that lists which model parts became which functions.
  • Code Interface Report: inputs, outputs, parameters and function prototypes.
  • Traceability: click a code line to highlight the block, and the other way round (right-click a block > C/C++ Code > Navigate to C/C++ Code). Generated comments name the block path.
  • Static Code Metrics: lines, global variables, stack size estimates.

Calling the generated code

In a hand-written main.c for a microcontroller (illustrative):

C
#include "controller.h"

void timer_isr(void)           /* called every 1 ms */
{
    controller_U.u = read_adc();
    controller_step();
    write_pwm(controller_Y.y);
}

int main(void)
{
    controller_initialize();
    start_timer_1ms();
    for (;;) { /* idle */ }
}

For multi-rate models Embedded Coder generates one function per rate (controller_step0, controller_step1) so each rate can run in its own task. For reuse in several instances choose Reusable function packaging so that state is passed in as an argument.

Common mistakes

  • A variable-step solver or continuous states: the build either fails or needs a numerical integration in the target.
  • Wrong hardware settings: int is 16-bit on one chip and 32-bit on another, so data types in the code differ.
  • Plant and controller in the same build when only the controller should be on the target.
  • Using the example ert_main.c in production without writing your own scheduler.
  • Everything is double on a chip with no double FPU, which is slow and large.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which solver setting is required to generate code for a real-time target?

    A real-time loop needs a fixed base rate, so the model uses a fixed-step (often discrete) solver.
  2. 2. Which System target file selects Embedded Coder's embedded real-time target?

    ert.tlc is the Embedded Real-Time target; grt.tlc is the generic real-time target of Simulink Coder.
  3. 3. What are the three standard generated functions?

    model_initialize, model_step and model_terminate are called by your application.
  4. 4. What is ert_main.c?

    It is only an example; the real scheduling comes from your application or RTOS.

Summary

  • Use Simulink Coder (grt.tlc) or Embedded Coder (ert.tlc) to turn a fixed-step model into C or C++.
  • Prepare the model (fixed-step solver, explicit data types, controller separated from the plant) and set hardware implementation correctly.
  • Build with Ctrl+B or rtwbuild; the output includes model.c, model.h, data and type files and a report with traceability.
  • Your application calls initialize, step and terminate and exchanges data through the generated input and output structures.
  • The Python generator is a stand-in that teaches the idea; real output comes from the product.

Next: Fixed-point and data types