Embedded C Code Generation
Generate embedded C from a control-system model. Inspect the generated source and headers, integrate callbacks with your scheduler, and test the compiled C.
Embedded C code generation turns a discrete-time control model into C source and headers with entry points for initialization and scheduled execution. Modeloop writes C for review against MISRA C:2012 and can also generate Python for host environments. You can test the compiled C against model behavior using the same inputs and timing. See software-in-the-loop testing.
With verification enabled, the compiler checks supported behavior before C lowering. After generation, test the compiled source with your scenarios. Make algorithm changes in the model and regenerate the source. See checks and traceability.
What gets generated
The model hierarchy maps directly onto the generated C:
| In the model | In the generated C |
|---|---|
| Model | <Model>.h and <Model>.c, with one <Model>_Init() that initializes every callback of the model. |
| Callback | One function, void <Callback>(void), named exactly as the callback. |
| Model without callbacks | One function named after the model, void <Model>(void). |
| Container | A private function in <Model>.c, named after the container. |
| State chart | A private function, plus an enum type that names its states. |
A callback function takes no arguments and returns nothing. It reads model inputs from variables, writes model outputs to variables, and keeps its state in static variables of the model. You call it from your own scheduler or RTOS, so you can integrate a single model into an existing project without adopting anything else. C Symbols lists every exported name and how it is chosen.
The header also defines <Callback>_DT_S, the sample interval in seconds that the callback’s time-dependent blocks assume, such as integrators, derivatives and signal sources. For a periodic callback it equals the period, so call the function at exactly that rate.
Containers and state charts stay separate functions instead of being flattened into one long body. A container receives its inputs by value and writes its outputs through pointers, so you can review the code with the diagram open next to it.
Files in a C build
| File | Content |
|---|---|
<Model>.h, <Model>.c |
Interface and implementation of one model. |
<Model>_data.h, <Model>_data.c |
Definitions of the calibration parameters the model uses. Only generated when it uses one. |
modeloop_calibration.h |
One declaration of every calibration parameter in the build. |
modeloop_types.h |
The float32_t and float64_t type names, defined once per build. |
modeloop_lookup.h, modeloop_lookup.c |
Lookup routines shared by all models. Only generated when a model uses a lookup table. |
codegen_manifest.json |
Machine-readable description of every generated file and of each model’s interface, for build systems and test tools. |
<Model>_<Callback>.trace.json |
Traceability map of one callback (see below). |
Compile every .c file of the build together. A file shared by several models is generated once.
The C target
Generated C is written for review against MISRA C:2012:
- Explicit conversions. Every type conversion is a cast in the code, and numeric literals carry the suffix of their type. A
float32literal uses the shortest spelling that reproduces its exact value. - Explicit precedence. Parentheses make operator precedence visible wherever a reader would otherwise need to know it.
- Sized type names. Floating-point data uses
float32_tandfloat64_t, and integers use the<stdint.h>types. - Static memory only. All state lives in statically allocated variables. There’s no dynamic memory and no recursion, so the memory footprint is fixed at compile time.
- Fixed-bound loops. Vector and matrix operations use loops with constant bounds. Single-element signals need no loop, and constant tables are
static constarrays. - Complete
switchstatements. State charts and selections on an enum signal use aswitchwith onecaseper value and an explicitdefault. - Distinct external names. Two names visible outside their file must differ within their first 31 characters, the length every C compiler is required to distinguish. Generation stops if they don’t, and never shortens a name you chose to make it fit.
Data types in generated code
The data types you declare in the model are the types in the code:
- Integer arithmetic stays integer. An operation on integer signals produces an integer result instead of switching to floating point.
- Mixed types are converted explicitly. When the operands of a block have different types, each operand is converted to a common type that can hold both, and the conversion appears in the code. C and Python apply the same conversions.
- Edge cases are defined. Abs of the most negative value of a signed integer type returns the largest positive value of that type instead of overflowing.
- Vectors and matrices have a fixed size. Their elements keep their type, including user-defined enums and type aliases, through routing, state blocks and data passed between callbacks.
- Buses become C
structtypes, one field per bus element. - User-defined enums become C enum types, declared once and shared by every model of the build. State chart outputs and local data can use them too.
Parameters and calibration
- A parameter referenced by a block becomes a
static constvariable with the parameter’s name, so the value stays readable in the code. - A parameter marked calibration becomes a
volatilevariable that calibration tools can find and overwrite at run time. Each calibration is defined once per build, even when several models use it, and only the calibrations a model actually uses are generated. - A callback reads each calibration once, at the start of its execution, and uses that value until it returns. A value written by a calibration tool during an execution takes effect from the next one.
Data between callbacks
Data passed between two callbacks of the same model is stored in one variable owned by the model, initialized by <Model>_Init(). The producing callback writes it, and each consuming callback copies it once at the start of its execution, so the value can’t change halfway through a callback. The variable keeps the type of the block that produces it.
The Python target
The Python target generates one module per callback. Each module contains a class named after the callback with three methods:
| Method | Purpose |
|---|---|
init() |
Reset state and outputs to their initial values. |
step(**inputs) |
Run the callback once. It takes the model inputs as keyword arguments and returns the outputs. |
terminate() |
End the run. |
The code depends only on NumPy. It follows the same execution order, state handling, initial values and type rules as the C target, including integer arithmetic and explicit conversions. Use it to run a model inside a Python application or test bench, or as a readable reference of the behavior.
Checks and traceability
Generated code is evidence you can use in your own review:
- Equivalence. With verification enabled, Modeloop compares the model with the final optimized high-level intermediate representation (HLIR) for supported outputs, initialization, and state updates. A counterexample blocks generation. C lowering, target-specific optimization, and C emission happen after this check. Use SIL to exercise the compiled C with the same scenarios as MIL. See formal verification.
- Numerical safety. Generation also checks the model for division by zero, math domain violations and overflow. A problem that occurs for every input is an error. A problem that depends on input values, or that cannot be decided, is a warning. Declared input ranges are taken into account, and every finding links to its block on the canvas.
- Traceability. The traceability map of each callback links every generated variable and function to the block or container it comes from. It also records, for every block, whether it appears in the code, was merged into another expression, was replaced by a constant or was removed because it had no effect.
- Integrity. Each generated file starts with a header that records a fingerprint of the model inputs and of the file itself. A manual edit changes the file fingerprint and is detected.
To inspect the code in the app, select View Code in the toolbar. It shows the last generated sources, read-only. After a SIL run it shows exactly the C sources that were compiled for that run.
Integrating the C code
- Generate from the build configuration: open Generate, choose C (MISRA) and select Generate code, then download the sources.
- Compile every generated
.cfile together with your project. - Initialize by calling
<Model>_Init()once for every model, before any callback runs. Calling it again later resets every callback of that model, outputs included. - Schedule each periodic callback at its period (
<Callback>_DT_S) and each event callback when its event occurs. Don’t start a callback while a previous call of the same callback is still running. - Connect your I/O by writing model inputs before calling a callback and reading model outputs after it returns.
- Keep the model as the source of truth. Every change goes through the model, followed by a new generation.