Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

Embedded Coder Overview

Embedded Coder Code Generation Pipeline
  Simulink Model (.slx)
      |
  Embedded Coder (slbuild / Ctrl+B)
      |
      +-- Code Generation Report (HTML)
      |     - Traceability: block <-> code line
      |     - Model coverage integration
      |     - Code metrics (ROM, RAM, complexity)
      |
      +-- Generated Files
            model.c          -- step function, init, terminate
            model.h          -- types, signals, parameters (extern)
            model_data.c     -- parameter initial values
            model_private.h  -- internal types
            model_types.h    -- bus types, enum definitions
            rtwtypes.h       -- platform type aliases
            ert_main.c       -- example main (reference only)

Code Generation Configuration

MATLABembedded_coder_cfg.m
% Embedded Coder configuration for production ECU target
% (Config Params > Code Generation)

% System target file -- ERT (Embedded Real-Time) for most automotive
set_param(model, "SystemTargetFile",    "ert.tlc");
% For AUTOSAR: set_param(model, "SystemTargetFile", "autosar.tlc");

% Language
set_param(model, "TargetLang",          "C");

% Optimisation
set_param(model, "InlineInvariantSignals",       "on");  % ROM constants
set_param(model, "OptimizeBlockIOStorage",       "on");  % reduce RAM
set_param(model, "LocalBlockOutputs",            "on");  % local vars
set_param(model, "BufferReusableNonTerminalBlocks","on");% reduce RAM
set_param(model, "BooleanDataType",              "on");  % bool not int

% Code style
set_param(model, "PreserveStaticInFcnDeclarations", "on");
set_param(model, "InsertBlockDesc",      "off"); % reduce comment noise
set_param(model, "GenerateComments",     "on");  % traceable comments

% MISRA-C compliance
set_param(model, "MisraC3Version",       "MISRA C:2012");
% Enable MISRA checking in code gen report

% Build
slbuild(model);  % generates and compiles
fprintf("Code gen complete. Open report: %s_ert_rtw/html/index.html\n", model);

Generated File Structure

FileContentsWho Uses It
model.cstep() function, init(), terminate(), internal stateCompiler; integration
model.hExternal signal/parameter declarations (extern); typesCallers; IoHwAb; Calibration
model_data.cParameter default values; const arrays for lookup tablesCompiler; flash section
model_types.hBus typedefs, enum definitionsAll files that use bus types
rtwtypes.huint8_T, int16_T etc. typedefs for the targetAll generated files
ert_main.cExample task scheduling (reference, not for production use)Reference only; OS integrator

Summary

The Embedded Coder configuration is where simulation artefacts become production code artefacts. The most impactful settings for code quality are the optimisation flags: OptimizeBlockIOStorage reduces RAM by reusing temporary buffers; LocalBlockOutputs keeps intermediate calculations as stack variables rather than global state. Together these can reduce RAM consumption by 30-50% compared to default settings on a complex model. The ERT target (ert.tlc) is the standard for automotive ECU code generation; the AUTOSAR target (autosar.tlc) generates additional ARXML artefacts required for AUTOSAR integration. Always use ERT for non-AUTOSAR targets (bare-metal, OSEK/VDX) and AUTOSAR for AUTOSAR CP or AP projects.

🔬 Embedded Coder Configuration — Key Options Explained

Embedded Coder (EC) configuration has hundreds of options. These are the ones that most affect code quality, MISRA compliance, and AUTOSAR integration:

  • System Target File: Determines the code generation framework. ert.tlc = Embedded Real-Time (generic embedded), autosar.tlc = AUTOSAR CP code generation (generates ARXML + C). Wrong selection generates non-AUTOSAR function signatures — fixing requires regenerating from scratch.
  • Data Placement: 'Default' puts all data in a single global struct. 'Hierarchical' creates per-model Data Stores aligned to AUTOSAR MemMap sections. For AUTOSAR CP, all storage classes must be set to AUTOSAR-defined types (AUTOSAR_Global, AUTOSAR_PerInstance) to generate correct MemMap.h section includes.
  • Integer overflow handling: Saturate on integer overflow adds clamping logic. Required for MISRA C:2012 Rule 10.1 compliance (no implicit conversion that changes sign). Without it, wraparound arithmetic in fixed-point code produces undefined behaviour per the C standard.
  • Non-inlined subsystem generation: Atomic subsystems with Function packaging = Nonreusable function generate a separate C function. This is mandatory for AUTOSAR SWC runnables — each runnable must be its own function. Inlined subsystems generate code inline in the parent step function — no separate runnable is possible.
  • Traceability: Enable Traceability comments to generate /* ModelName:45 SignalName */ comments in every generated line. These comments are required by ISO 26262 Part 6 for software unit → model traceability evidence.

🏭 Embedded Coder in Production MBD Projects

  • Bosch GmbH Powertrain MBD: All combustion engine control software uses Embedded Coder with AUTOSAR code generation. The ARXML output from EC is imported into DaVinci Developer for port mapping, then integrated into the BSW project. The EC configuration is change-controlled — any EC version or config change requires a full back-to-back (B2B) test campaign before release.
  • Code size optimisation: An unoptimised Embedded Coder model for a 200-block anti-lock brake algorithm may generate 150 KB of code. With proper storage class configuration, struct elimination, and lookup table sharing, this reduces to ~60 KB. ROM budget management is a key MBD engineering discipline.
  • Tool qualification: ISO 26262 Part 8.11 requires that code generators used for ASIL C/D software development are either qualified (Tool Confidence Level 1, 2, or 3) or the generated code is manually reviewed. MathWorks provides a Tool Qualification Kit (TQK) for Embedded Coder that generates qualification evidence artefacts — essential for ASIL D projects.

⚠️ Embedded Coder Configuration Pitfalls

  1. Floating-point operations in fixed-point model: Using a double-precision constant in a model targeting fixed-point arithmetic causes the code generator to emit a float operation — introducing an implicit type conversion that violates MISRA C:2012 Rule 10.5 and may exceed the MCU's FPU capabilities. Use fi() fixed-point constants throughout.
  2. Inconsistent sample time in multi-rate model: A subsystem running at 1 ms calling a signal from a 10 ms subsystem without a Rate Transition block causes code generation to fail (or worse, generate incorrect scheduling code). Always add explicit Rate Transition blocks at sample time boundaries.
  3. Generated code not regenerated after model change: If a model is modified but code is not regenerated, the ARXML and C code are out of sync. AUTOSAR port names in the ARXML may not match the generated C stub — causing DaVinci Developer import errors. Always regenerate immediately after any model change.
  4. Default storage class used for AUTOSAR SWC data: Using Auto/Default storage class for inter-runnable variables generates compiler-global variables without MemMap section markers. This violates the AUTOSAR software architecture requirement that all inter-runnable variables use AUTOSAR_Global storage class with proper section wrapping.

📊 Industry Note

Model-Based Design productivity depends heavily on a well-configured code generation environment. Projects that invest in a standardised EC configuration template (shared across all model developers) and automated post-generation checks (model advisor, code inspection) typically achieve 40–60% lower integration effort compared to ad-hoc per-engineer configurations.

🧠 Knowledge Check — Click each question to reveal the answer

❓ What is the purpose of the System Target File in Embedded Coder, and what is the consequence of selecting the wrong one?

✅ The System Target File (TLC) defines the overall code generation framework: function naming conventions, file structure, generated APIs, and post-processing hooks. For AUTOSAR CP, autosar.tlc generates AUTOSAR-compliant code including ARXML port definitions, MemMap section markers, and AUTOSAR-typed function signatures. Using ert.tlc instead generates generic embedded code with non-AUTOSAR signatures — the ARXML will be missing port information and cannot be imported into DaVinci Developer. All downstream AUTOSAR integration steps fail, and the model must be reconfigured from scratch.

❓ Why is back-to-back (B2B) testing required after a code generator version update?

✅ Changing Embedded Coder versions (even minor updates like R2024a → R2024b) can alter code generation behaviour: numerical optimisations, rounding modes, storage class handling, or MISRA compliance checks may change. B2B testing runs the same test cases on both the old and new generated code (in SIL mode) and compares outputs numerically. Any deviation in the output signals indicates a code generation change that must be manually reviewed for safety impact. ISO 26262 Tool Qualification requirements mandate this evidence.

❓ A model has a persistent state variable that must be read by two runnables in AUTOSAR. How should this be modelled?

✅ The persistent state should be modelled as an AUTOSAR Inter-Runnable Variable (IRV) — a data store with AUTOSAR_PerInstance storage class. In Simulink, use a Data Store Memory block with the storage class set to AUTOSAR_PerInstance. The first runnable (which writes the state) uses a Data Store Write block; the second runnable uses a Data Store Read. The RTE generator will create a properly typed IRV buffer and generate ExclusiveArea protection if both runnables are in the same OS task. Using a simple persistent (global) variable instead violates the AUTOSAR software architecture and bypasses the RTE's data consistency management.
← PreviousHands-On: Guideline-Compliant ModelNext →Storage Classes and Code Optimization