Generate Reusable Code for Unit Testing

An atomic subchart is a graphical object that helps you to create standalone subcomponents in a Stateflow® chart. Atomic subcharts are supported only in Stateflow charts in Simulink® models. For more information, see Create Reusable Subcomponents by Using Atomic Subcharts.

Goal of the Tutorial

Assume that you have the following model, and the chart has two states:

Suppose that you want to generate reusable code so that you can perform unit testing on state A. You can convert that part of the chart to an atomic subchart and then specify a separate file to store the generated code.

Convert a State to an Atomic Subchart

To convert state A to an atomic subchart, right-click the state and select Group & Subchart > Atomic Subchart. State A changes to an atomic subchart:

Specify Code Generation Parameters

Set Up a Standalone C File for the Atomic Subchart

  1. Open the properties dialog box for A.

  2. Set Code generation function packaging to Reusable function.

  3. Set Code generation file name options to User specified.

  4. For Code generation file name, enter saturator as the name of the file.

  5. Click OK.

Set Up the Code Generation Report

  1. Open the Model Configuration Parameters dialog box.

  2. In the Code Generation pane, set System target file to ert.tlc.

  3. In the Code Generation > Report pane, select Create code generation report.

    This step automatically selects Open report automatically and Code-to-model.

  4. Select Model-to-code.

  5. Click Apply.

Customize the Generated Function Names

  1. In the Model Configuration Parameters dialog box, go to the Code Generation > Symbols pane.

  2. Set Subsystem methods to the format scheme $R$N$M$F, where:

    • $R is the root model name.

    • $N is the block name.

    • $M is the mangle token.

    • $F is the type of interface function for the atomic subchart.

    For more information, see Subsystem methods (Simulink Coder).

  3. Click Apply.

Generate Code for Only the Atomic Subchart

To generate code for your model, press Ctrl+B. In the code generation report that appears, you see a separate file that contains the generated code for the atomic subchart.

To inspect the code for saturator.c, click the hyperlink in the report to see the following code:

Line 28 shows that the during function generated for the atomic subchart has the name ex_reuse_states_A_during. This name follows the format scheme $R$N$M$F specified for Subsystem methods:

  • $R is the root model name, ex_reuse_states.

  • $N is the block name, A.

  • $M is the mangle token, which is empty.

  • $F is the type of interface function for the atomic subchart, during.

Note

The line numbers shown can differ from the numbers that appear in your code generation report.