0% found this document useful (0 votes)
24 views54 pages

Simulink CG Guidelines

The document provides modeling guidelines for code generation in Simulink, aimed at optimizing models for embedded systems. It includes recommendations on block usage, configuration settings, and modeling patterns to enhance code efficiency and execution speed. The guidelines also emphasize the importance of precalculating signals and parameters to reduce memory usage and improve performance.

Uploaded by

林子筠
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views54 pages

Simulink CG Guidelines

The document provides modeling guidelines for code generation in Simulink, aimed at optimizing models for embedded systems. It includes recommendations on block usage, configuration settings, and modeling patterns to enhance code efficiency and execution speed. The guidelines also emphasize the importance of precalculating signals and parameters to reduce memory usage and improve performance.

Uploaded by

林子筠
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Simulink®

Modeling Guidelines for Code Generation

R2024b
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
Modeling Guidelines for Code Generation
© COPYRIGHT 2010–2024 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied
only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form
without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through
the federal government of the United States. By accepting delivery of the Program or Documentation, the government
hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer
software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014.
Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain
to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government) and shall
supersede any conflicting contractual terms or conditions. If this License fails to meet the government's needs or is
inconsistent in any respect with federal procurement law, the government agrees to return the Program and
Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand names may be
trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see www.mathworks.com/patents for
more information.
Revision History
September 2010 Online only New for Version 1.0 (Release 2010b)
April 2011 Online only Revised for Version 1.1 (Release 2011a)
September 2011 Online only Revised for Version 1.2 (Release 2011b)
March 2012 Online only Revised for Version 1.3 (Release 2012a)
September 2012 Online only Revised for Version 1.4 (Release 2012b)
March 2013 Online only Revised for Version 1.5 (Release 2013a)
September 2013 Online only Revised for Version 1.6 (Release 2013b)
March 2014 Online only Revised for Version 1.7 (Release 2014a)
October 2014 Online only Revised for Version 1.8 (Release 2014b)
March 2015 Online only Revised for Version 1.9 (Release 2015a)
September 2015 Online only Revised for Version 1.10 (Release 2015b)
March 2016 Online only Revised for Version 1.11 (Release 2016a)
September 2016 Online only Revised for Version 1.12 (Release 2016b)
March 2017 Online only Revised for Version 1.13 (Release 2017a)
September 2017 Online only Revised for Version 1.14 (Release 2017b)
March 2018 Online only Revised for Version 1.15 (Release 2018a)
September 2018 Online only Revised for Version 1.16 (Release 2018b)
March 2019 Online only Revised for Version 1.17 (Release 2019a)
September 2019 Online only Revised for Version 1.18 (Release 2019b)
March 2020 Online only Revised for Version 1.19 (Release 2020a)
September 2020 Online only Revised for Version 1.20 (Release 2020b)
March 2021 Online only Revised for Version 1.21 (Release 2021a)
September 2021 Online only Revised for Version 1.22 (Release 2021b)
March 2022 Online only Revised for Version 1.23 (Release 2022a)
September 2022 Online only Revised for Version 1.24 (Release 2022b)
March 2023 Online only Revised for Version 1.25 (Release 2023a)
September 2023 Online only Revised for Version 23.2 (R2023b)
March 2024 Online only Revised for Version 24.1 (R2024a)
September 2024 Online only Revised for Version 24.2 (R2024b)
Contents

Introduction
1
Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Guideline Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Block Considerations
2
cgsl_0102: Evenly spaced breakpoints in lookup tables . . . . . . . . . . . . . . . 2-2

cgsl_0103: Precalculated signals and parameters . . . . . . . . . . . . . . . . . . . 2-3

Modeling Pattern Considerations


3
cgsl_0201: Redundant Unit Delay and Memory blocks . . . . . . . . . . . . . . . 3-2

cgsl_0202: Usage of For, While, and For Each subsystems with vector
signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

cgsl_0204: Vector and bus signals crossing into atomic subsystems or


Model blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

Configuration Parameter Considerations


4
cgsl_0301: Prioritization of code generation objectives for code efficiency
.......................................................... 4-2

v
Component Deployment Using Service Interface Configuration
5
cgsl_0401: Modeling styles for component deployment . . . . . . . . . . . . . . . 5-2

cgsl_0402: Signal interfaces for component deployment . . . . . . . . . . . . . . 5-4

cgsl_0404: Model startup and shutdown events by using Initialize


Function and Terminate Function blocks for component deployment
.......................................................... 5-7

cgsl_0405: Data receive for component deployment . . . . . . . . . . . . . . . . . 5-9

cgsl_0406: Data send for component deployment . . . . . . . . . . . . . . . . . . 5-12

cgsl_0408: Partial data send for component deployment . . . . . . . . . . . . . 5-15

cgsl_0409: Data transfer for component deployment . . . . . . . . . . . . . . . . 5-17

cgsl_0410: Timer service for component deployment . . . . . . . . . . . . . . . 5-20

cgsl_0411: Access nonvolatile memory by using Initialize Function and


Terminate Function blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23

cgsl_0413: Reuse memory between component state and output for


component deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-26

cgsl_0414: Configure service interface for component model . . . . . . . . . 5-29

vi Contents
1

Introduction

• “Motivation” on page 1-2


• “Guideline Template” on page 1-3
1 Introduction

Motivation
Code generation modeling guidelines provide recommendations that you can use when developing
models and generating code that is intended for use in embedded systems. The guidelines, which take
into consideration the potential impact to simulation behavior, code generation, and component
model deployment, include information about configuration settings, block usage and parameters,
and modeling patterns.

The guidelines do not address model style or compliance with industry standards. For additional
information, see:

• “MAB Modeling Guidelines” — Modeling guidelines that address model consistency, clarity, and
readability.
• “High-Integrity System Modeling” — Modeling guidelines that address compliance with industry
standards.

For information about qualifying software development and verification tools that are used to develop
embedded system for projects that must comply with an industry standard, see:

• IEC Certification Kit — Guidance on certifying your embedded systems for use in projects that
must comply with ISO 26262, IEC 61508, EN 50128, EN 50657, ISO 25119, and related
functional-safety standards such as IEC 62304.
• “DO Qualification Kit (for DO-178)” — Guidance on qualifying your software verification tools for
use in projects involving the DO-178C and DO-254 standards.

Disclaimer While adhering to the recommendations in the guidelines will reduce the risk that an
error is introduced during development and not be detected, it is not a guarantee that the system
being developed will be safe. Conversely, if some of the recommendations in the guidelines are not
followed, it does not mean that the system being developed will be unsafe.

1-2
Guideline Template

Guideline Template
Guideline descriptions are documented, using the following template. Companies that want to create
additional guidelines are encouraged to use the same template.

ID: Title XX_nnnn: Title of the guideline (unique, short)


Description Description of the guideline
Prerequisites Links to guidelines that are prerequisites to this guideline (ID: Title)
Notes Notes for using the guideline
Rationale Rationale for providing the guideline
Model Title of and link to the corresponding Model Advisor check, if a check exists
Advisor
Check
References References to standards that apply to guideline
See Also Links to additional information
Last Changed Version number of last change
Examples Guideline examples

1-3
2

Block Considerations

• “cgsl_0102: Evenly spaced breakpoints in lookup tables” on page 2-2


• “cgsl_0103: Precalculated signals and parameters” on page 2-3
2 Block Considerations

cgsl_0102: Evenly spaced breakpoints in lookup tables


ID: Title cgsl_0102: Evenly spaced breakpoints in lookup tables
Description When you use Lookup Table and Prelookup blocks,
A With non-fixed-point data types, use evenly spaced data breakpoints for the
input axis
B With fixed-point data types, use power of two spaced breakpoints for the input
axis
Notes Evenly spaced breakpoints can prevent generated code from including division
operations, resulting in faster execution.
Rationale A Improve ROM usage and execution speed.
B Improve execution speed.

When compared to unevenly spaced data, power-of-two data can

• Increase data RAM usage if you require a finer step size


• Reduce accuracy if you use a coarser step size

Compared to an evenly spaced data set, there should be minimal cost in


memory or accuracy.
Model Advisor Checks By Product > Embedded Coder > Identify questionable fixed-point operations

For check details, see “Identify questionable fixed-point operations” (Embedded Coder).
See Also “Formulation of Evenly Spaced Breakpoints”
Last Changed R2010b

2-2
cgsl_0103: Precalculated signals and parameters

cgsl_0103: Precalculated signals and parameters


ID: Title cgsl_0103: Precalculated signals and parameters
Description Precalculate invariant parameters and signals by doing one of the
following:
A Manually precalculate the values
B Set these configuration parameters:

• Set Default parameter behavior to Inlined


• Select Inline invariant signals
Notes Precalculating variables can reduce local and global memory usage and
improve execution speed. If you set Default parameter behavior to
Inlined and enable Inline invariant signals, the code generator
minimizes the number of run-time calculations by maximizing the
number calculations completed before run time. In some cases, this can
lead to a reduction in the number of parameters stored. However, the
algorithms the code generator uses have limitations. In some cases, the
code is more compact if you calculate the values outside of the Simulink
environment. This can improve model efficiency, but can reduce model
readability.
Rationale A, B Precalculate data, outside of the Simulink environment, to
reduce memory requirements of a system and improve run-time
execution.
Last Changed R2012b

2-3
2 Block Considerations

ID: Title cgsl_0103: Precalculated signals and parameters


Examples In the following model, the four paths are mathematically equivalent.
However, due to algorithm limitations, the number of run-time
calculations for the paths differs.

Path_1 = InputSignal * -3.0 * 3.0;

/* Product: '<Root>/Product4' incorporates:


* Inport: '<Root>/In1'
*/
Path_2 = InputSignal * -9.0;

/* Product: '<Root>/Product2' incorporates:


* Constant: '<Root>/Constant2'
* Inport: '<Root>/In1'
*/
Path_3 = -9.0 * InputSignal;

/* Product: '<Root>/Product5' incorporates:


* Constant: '<Root>/Constant2'
* Inport: '<Root>/In1'
*/
Path_4 = -3.0 * InputSignal * 3.0;

/* Product: '<Root>/Product6' incorporates:


* Constant: '<Root>/Constant3'
* Inport: '<Root>/In1'
*/
Pre_Calc_1 = -9.0 * InputSignal;

To maximize automatic precalculation, add signals at the end of the set


of equations.

Inlining data reduces the ability to tune model parameters. You should
define parameters that require calibration to allow calibration. For more
information, see “Create Tunable Calibration Parameter in the
Generated Code” (Simulink Coder).

2-4
3

Modeling Pattern Considerations

• “cgsl_0201: Redundant Unit Delay and Memory blocks” on page 3-2


• “cgsl_0202: Usage of For, While, and For Each subsystems with vector signals” on page 3-6
• “cgsl_0204: Vector and bus signals crossing into atomic subsystems or Model blocks”
on page 3-7
3 Modeling Pattern Considerations

cgsl_0201: Redundant Unit Delay and Memory blocks


ID: Title cgsl_0201: Redundant Unit Delay and Memory blocks
Description When preparing a model for code generation,
A Remove redundant Unit Delay and Memory blocks.
Rationale A Redundant Unit Delay and Memory blocks use additional global memory. Removing
the redundancies from a model reduces memory usage without impacting model
behavior.
Last Changed R2013a
Example

Recommended: Consolidated Unit Delays


void Reduced(void)
{
ConsolidatedState_2 = Matrix_UD_Test - (Cal_1 * DWork.UD_3_DSTATE + Cal_2 *
DWork.UD_3_DSTATE);
DWork.UD_3_DSTATE = ConsolidatedState_2;
}

Not Recommended: Redundant Unit Delays


void Redundant(void)
{
RedundantState = (Matrix_UD_Test - Cal_2 * DWork.UD_1B_DSTATE) - Cal_1 *
DWork.UD_1A_DSTATE;
DWork.UD_1B_DSTATE = RedundantState;
DWork.UD_1A_DSTATE = RedundantState;
}

3-2
cgsl_0201: Redundant Unit Delay and Memory blocks

ID: Title cgsl_0201: Redundant Unit Delay and Memory blocks


Unit Delay and Memory blocks exhibit commutative and distributive algebraic properties.
When the blocks are part of an equation with one driving signal, you can move the Unit
Delay and Memory blocks to a new position in the equation without changing the result.

For the top path in the preceding example, the equations for the blocks are:

1 Out_1(t) = UD_1(t)
2 UD_1(t) = In_1(t-1) * Cal_1

For the bottom path, the equations are:

1 Out_2(t) = UD_2(t) * Cal_1


2 UD_2(t) = In_2(t-1)

In contrast, if you add a secondary signal to the equations, the location of the Unit Delay
block impacts the result. As the following example shows, the location of the Unit Delay
block impacts the results due to the skewing of the time sample between the top and
bottom paths.

In cases with a single source and multiple destinations, the comparison is more complex.
For example, in the following model, you can refactor the two Unit Delay blocks into a
single unit delay.

3-3
3 Modeling Pattern Considerations

ID: Title cgsl_0201: Redundant Unit Delay and Memory blocks

From a black box perspective, the two models are equivalent. However, from a memory and
computation perspective, differences exist between the two models.

{
real_T rtb_Gain4;
rtb_Gain4 = Cal_1 * Redundant;
Y.Redundant_Gain = Cal_2 * rtb_Gain4;
Y.Redundant_Int = DWork.Int_A;
Y.Redundant_Int_UD = DWork.UD_A;
Y.Redundant_Gain_UD = DWork.UD_B;
DWork.Int_A = 0.01 * rtb_Gain4 + DWork.Int_A;
DWork.UD_A = Y.Redundant_Int;
DWork.UD_B = Y.Redundant_Gain;
}

{
real_T rtb_Gain1;
real_T rtb_UD_C;
rtb_Gain1 = Cal_1 * Reduced;
rtb_UD_C = DWork.UD_C;
Y.Reduced_Gain_UD = Cal_2 * DWork.UD_C;
Y.Reduced_Gain = Cal_2 * rtb_Gain1;
Y.Reduced_Int = DWork.Int_B;
Y.Reduced_Int_UD = DWork.Int_C;
DWork.UD_C = rtb_Gain1;
DWork.Int_B = 0.01 * rtb_Gain1 + DWork.Int_B;
DWork.Int_C = 0.01 * rtb_UD_C + DWork.Int_C;
}

In this case, the original model is more efficient. In the first code example, there are three
global variables, two from the Unit Delay blocks (DWork.UD_A and DWork.UD_B) and one
from the discrete time integrator (DWork.Int_A). The second code example shows a
reduction to one global variable generated by the unit delays (Dwork.UD_C), but there are
two global variables due to the redundant Discrete Time Integrator blocks (DWork.Int_B
and DWork.Int_C). The Discrete Time Integrator block path introduces an additional local
variable (rtb_UD_C) and two additional computations.

By contrast, the refactored model (second) below is more efficient.

3-4
cgsl_0201: Redundant Unit Delay and Memory blocks

ID: Title cgsl_0201: Redundant Unit Delay and Memory blocks

{
real_T rtb_Gain4_f:
real_T rtb_Int_D;
rtb_Gain4_f = Cal_1 * U.Input;
rtb_Int_D = DWork.Int_D;
Y.R_Int_Out = DWork.UD_D;
Y.R_Gain_Out = DWork.UD_E;
DWork.Int_D = 0.01 * rtb_Gain4_f + DWork.Int_D;
DWork.UD_D = rtb_Int_D;
DWork.UD_E = Cal_2 * rtb_Gain4_f;
}

{
real_T rtb_UD_F;
rtb_UD_F = DWork.UD_F;
Y.Gain_Out = Cal_2 * DWork.UD_F;
Y.Int_Out = DWork.Int_E;
DWork.UD_F = Cal_1 * U.Input;
DWork.Int_E = 0.01 * rtb_UD_F + DWork.Int_E;
}

The code for the refactored model is more efficient because the branches from the root
signal do not have a redundant unit delay.

3-5
3 Modeling Pattern Considerations

cgsl_0202: Usage of For, While, and For Each subsystems with


vector signals
ID: Title cgsl_0202: Usage of For, While, and For Each subsystems with vector signals
Description When developing a model for code generation,
A Use For, While, and For Each subsystems for calculations that require iterative
behavior or operate on a subset (frame) of data.
B Avoid using For, While, or For Each subsystems for basic vector operations.
Rationale A, B Avoid redundant loops.
See Also • Loop unrolling threshold (Simulink Coder) in the Simulink documentation
Last Changed R2010b
Examples The recommended method for preceding calculation is to place the Gain block outside
the For Subsystem. If the calculations are required as part of a larger algorithm, you
can avoid the nesting of for loops by using Index Vector and Assignment blocks.

Recommended

for (s1_iter = 0; s1_iter < 10; s1_iter++) {


RecommendedOut[s1_iter] = 2.3 * vectorInput[s1_iter];
}

A common mistake is to embed basic vector operations in a For, While, or For Each
subsystem. The following example includes a simple vector gain inside a For
subsystem, which results in unnecessary nested for loops.

Not Recommended

for (s1_iter = 0; s1_iter < 10; s1_iter++) {


for (i = 0; i < 10; i++) {
NotRecommendedOut[i] = 2.3 * vectorInput[i];
}
}

3-6
cgsl_0204: Vector and bus signals crossing into atomic subsystems or Model blocks

cgsl_0204: Vector and bus signals crossing into atomic


subsystems or Model blocks
ID: Title cgsl_0204: Vector and bus signals crossing into atomic subsystems or
Model blocks
Description When working with vector or buses and some of the signal elements are in a
referenced model, use the following information to determine how to select signal
elements to minimize memory usage.

Signals selected outside Signal selected inside


Model block results in... Model block results
in...
Virtual Bus No data copies. Only If Inport block parameter
selected signals are passed Output as nonvirtual
to the function. bus is selected, then
there are no data copies.
Only the selected signals
are passed to the
function.

If Inport block parameter


Output as nonvirtual
bus is cleared, then a
copy of the whole bus is
passed to the function.
Nonvirtual Bus No data copies. Only the If Inport block parameter
selected signals are passed Output as nonvirtual
to the function. bus is selected, then
there are no data copies.
Only the selected signals
are passed to the
function.

If Inport block parameter


Output as nonvirtual
bus is cleared, then a
copy of the whole bus is
passed to the function.
See example 2.
Vector A copy of the selected No data copies. The
signals in a local variable whole vector is passed to
that is passed to the the function.
function.
Notes • Depending on Embedded Coder® settings (e.g. optimizations), predecessor
blocks and signal storage classes, actual results might differ from the tables.
• Virtual buses do not support global data.
• If the subsystem is set to Inline, data copies do not occur.
Rationale Minimize RAM, ROM, and stack usage

3-7
3 Modeling Pattern Considerations

ID: Title cgsl_0204: Vector and bus signals crossing into atomic subsystems or
Model blocks
Last Changed R2023b
Examples Nonvirtual bus entering a model block:

• The Total number of instances allowed per top model is Multiple


• Subsignal is selected inside the referenced model

There are no data copies in the code for the main model. The whole bus is passed to
the model reference function.

Code for the model reference function:

3-8
4

Configuration Parameter Considerations


4 Configuration Parameter Considerations

cgsl_0301: Prioritization of code generation objectives for code


efficiency
ID: Title cgsl_0301: Prioritization of code generation objectives for code efficiency
Description Prioritize code generation objectives for code efficiency by using the Code Generation
Advisor.
A Assign priorities to code (ROM, RAM, and Execution efficiency) efficiency
objectives.
B Select the relative order of ROM, RAM, and Execution efficiency based on
application requirements.
C Configure the Code Generation Advisor to run before generating code by
setting the Check model before generating code configuration parameter to
On (proceed with warnings) or On (stop for warnings).
Notes A model's configuration parameters provide control over many aspects of generated
code. The prioritization of objectives specifies how configuration parameters are set
when conflicts between objectives occur.

Prioritizing code efficiency objectives above safety objectives may remove initialization
or run-time protection code (for example, saturation range checking for signals out of
representable range). Review the resulting parameter configurations to verify that
safety requirements are met.
Rationale A, B, C When you use the Code Generation Advisor, configuration parameters conform
to the objectives that you want and they are consistently enforced.
See also • “Application Objectives Using Code Generation Advisor” (Simulink Coder)
• “Manage Configuration Sets for a Model”
Last Changed R2015b

4-2
5

Component Deployment Using Service


Interface Configuration

• “cgsl_0401: Modeling styles for component deployment” on page 5-2


• “cgsl_0402: Signal interfaces for component deployment” on page 5-4
• “cgsl_0404: Model startup and shutdown events by using Initialize Function and Terminate
Function blocks for component deployment” on page 5-7
• “cgsl_0405: Data receive for component deployment” on page 5-9
• “cgsl_0406: Data send for component deployment” on page 5-12
• “cgsl_0408: Partial data send for component deployment” on page 5-15
• “cgsl_0409: Data transfer for component deployment” on page 5-17
• “cgsl_0410: Timer service for component deployment” on page 5-20
• “cgsl_0411: Access nonvolatile memory by using Initialize Function and Terminate Function
blocks” on page 5-23
• “cgsl_0413: Reuse memory between component state and output for component deployment”
on page 5-26
• “cgsl_0414: Configure service interface for component model” on page 5-29
5 Component Deployment Using Service Interface Configuration

cgsl_0401: Modeling styles for component deployment

ID: Title cgsl_0401: Modeling styles for component deployment


Description A model intended for component deployment with a service interface shall be
designed by using one of the following modeling styles:
A Export-function modeling

This modeling style supports single and multiple rates.


B Rate-based modeling

This modeling style supports only a single rate.


Notes For export-function models, the code generator produces initialize and
terminate entry-point functions and an entry-point function for each callable
function represented in the model.

For rate-based models, the code generator produces initialize and terminate
entry-point functions and an entry-point function for the rate of the model.
Rationale Support generation of callable entry-point functions in a component modeling
architecture.
Model Advisor Check Verify this guideline by using Model Advisor check “Check modeling style for
component deployment” (Embedded Coder)
Examples Export-Function Modeling Style

Rate-Based Modeling Style

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Periodic and Aperiodic Function Interfaces” (Embedded Coder)

5-2
Version History

“Export-Function Models Overview”

“Schedule Components to Avoid Data Dependency Issues”

“Create a Service Interface Configuration” (Embedded Coder)

“What Is Sample Time?”

“Specify Sample Time”

Version History

5-3
5 Component Deployment Using Service Interface Configuration

cgsl_0402: Signal interfaces for component deployment

ID: Title cgsl_0402: Signal interfaces for component deployment


Description At the root level of a component, signal interfaces shall be modeled by using
only one type of ports:

• Name-based ports — In Bus Element and Out Bus Element blocks


• Index-based ports — Inport and Outport blocks

Using name-based ports:

• Improves model clarity by reducing wiring and complexity.


• Avoids issues caused by port reordering with index-based ports.
A For structured signals that use In Bus Element and Out Bus
Element blocks, set block parameters as follows:

• Set Data type to Bus: <object name>.


• Set Bus virtuality to nonvirtual.

Configure the interface for each name-based port individually.


B For structured signals that use Inport and Outport blocks, set
block parameters as follows:

• Set Data type to Bus: <object name>.


• Specify that the output bus is nonvirtual at the root level by
selecting Outport block parameter Output as nonvirtual
bus in parent model.
• Specify that the output for a top-level Inport block used to
load bus data is nonvirtual by selecting Inport block
parameter Output as nonvirtual bus.

5-4
cgsl_0402: Signal interfaces for component deployment

ID: Title cgsl_0402: Signal interfaces for component deployment


C To select signal elements in a way that minimizes memory usage,
reduce the number of data copies by passing an entire virtual or
nonvirtual bus into an atomic subsystem, even when the
subsystem uses only a subset of the bus. To select an element of
the bus from the interface, use anIn Bus Element block.

A data copy is created when an atomic subsystem interface


receives only part of a bus. For example, a data copy is created
when a bus element is selected from the bus, then that bus
element is passed into the subsystem.

This table describes the data copy creation when an atomic


subsystem receives a bus element instead of the entire bus.

Function Function Interface Data Copy


Packaging
Non-reusable void_void In the global block
function I/O structure that
the function uses,
the software creates
a copy of the input
bus element.
Non-reusable Allow arguments In a local variable
function (Optimized) that is passed to the
function, the
software creates a
copy of the input
bus element.
Reusable N/A In a local variable
function that is passed to the
function, the
software creates a
copy of the input
bus element.
Notes • Do not use datastore memory for signal interfaces.
• Depending on Embedded Coder settings (for example, optimizations),
predecessor blocks, signal storage classes, and actual results might differ
from the tables.
• Virtual buses do not support global data.
• If Function packaging is set to Inline for the subsystem, data copies do
not occur.
Rationale Using In Bus Element and Out Bus Element blocks reduces wiring and the
name-based approach avoids issues with port reordering.

Reduces complexity and provides model clarity.


Model Advisor Check Verify this guideline by using Model Advisor check “Check signal interfaces”
(Embedded Coder).

5-5
5 Component Deployment Using Service Interface Configuration

ID: Title cgsl_0402: Signal interfaces for component deployment


Last Changed R2023b
Example In this model, an In Bus Element block selects a vector from a nonvirtual bus.
The selected vector enters an atomic subsystem that has function packaging
set to Reusable function.

Only the selected vector is passed to the function because the vector is
selected before the subsystem interface. The function requires a data copy of
the vector independent of the nonvirtual bus.

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Create Nonvirtual Buses”

“Specify Bus Properties with Bus Objects”

“Composite Interface Guidelines”

In Bus Element

Out Bus Element

Inport

Outport

Version History

5-6
cgsl_0404: Model startup and shutdown events by using Initialize Function and Terminate Function blocks for component deployment

cgsl_0404: Model startup and shutdown events by using


Initialize Function and Terminate Function blocks for
component deployment

ID: Title cgsl_0404: Model startup and shutdown events by using Initialize Function and
Terminate Function blocks for component deployment
Description To model startup and shutdown behavior, use Initialize Function and Terminate Function
blocks.
Notes By following this guideline, the code generator produces one initialize function and one
terminate function.

When a Terminate Function block is not needed in the model, clear model configuration
parameter Terminate function required (IncludeMdlTerminateFcn).
Rationale Decouples the execution order of component initialize and terminate functions from the
execution order across components.

Separates component startup and shutdown functionality from periodic and aperiodic
algorithm function code.
Model Advisor Verify this guideline by using Model Advisor check “Check Startup and Shutdown Event”
Check (Embedded Coder).
Examples

void CD_initialize(void)
{
.
.
.
}

void CD_terminate(void)
{
.
.
.
}

See Also
“Startup, Reset, and Shutdown Function Interfaces” (Embedded Coder)

“Periodic and Aperiodic Function Interfaces” (Embedded Coder)

“Code Interfaces and Code Interface Specification” (Embedded Coder)

Initialize Function

Terminate Function

5-7
5 Component Deployment Using Service Interface Configuration

“Using Initialize, Reinitialize, Reset, and Terminate Functions”

Version History

5-8
cgsl_0405: Data receive for component deployment

cgsl_0405: Data receive for component deployment

ID: Title cgsl_0405: Data receive for component deployment


Description A To model a call to the target platform receiver service, use
an In Bus Element or Inport block.
B To safeguard data for concurrent access, map the component
inports to a service interface that is configured to use the
During Execution or Outside Execution communication
method.

• During Execution — The generated callable function


that implements the algorithm safeguards data access for
concurrency.

• Outside Execution —The target platform service


safeguards data access for concurrency.
C When concurrent access to data is not a concern, map
component inports to a service interface that is configured to
use the Direct Access communication method. In this case,
no safeguard for data access is provided.
Rationale The generated code aligns with the data communication method that is
required by the target platform environment.
Model Advisor Check A Model Advisor check is not necessary for this guideline because a service
interface for a receiver service must be configured to use one of the three
data communication methods.

5-9
5 Component Deployment Using Service Interface Configuration

ID: Title cgsl_0405: Data receive for component deployment


Example Specifying the Data Communication Method for Calling the Target
Platform Data Receiver Service

In this example, the data communication method is set to Outside


Execution.
void CD_integrator(void)
{
.
.
.
for (i = 0; i < 10; i++) {
.
.
.
rtDWork.DiscreteTimeIntegrator_PREV_U[i] = (get_CD_integrator_input())[i];
}
.
.
.
}

In this example, the data communication method is set to During


Execution.

void CD_integrator(void)
{
.
.
.
real_T tmp[10];
.
.
.
get_CD_integrator_input(&tmp[0]);
.
.
.
for (i = 0; i < 10; i++) {

5-10
Version History

ID: Title cgsl_0405: Data receive for component deployment


.
.
.
rtDWork.DiscreteTimeIntegrator_PREV_U[i] = tmp[i]
}
.
.
.
}

In this example, the data communication method is set to Direct Access.

void CD_integrator(void)
{
.
.
.
for (i = 0; i < 10; i++) {
.
.
.
... = CD_sig.In[i];
}
.
.
.
}

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Receiver and Sender Service Interfaces” (Embedded Coder)

“Data Communication Methods” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

“Select Code Generation Output for Target Platform Deployment” (Embedded Coder)

In Bus Element block

Inport block

get (Embedded Coder) function

Version History

5-11
5 Component Deployment Using Service Interface Configuration

cgsl_0406: Data send for component deployment

ID: Title cgsl_0406: Data send for component deployment


Description A To model a call to the target platform sender service, use an Out Bus
Element or Outport block.
B To safeguard data for concurrent access, map the component
outports to a service interface that is configured to use the During
Execution or Outside execution communication method.

• During Execution —The generated callable function that


implements the algorithm safeguards data access for
concurrency.

• Outside Execution — The target platform service safeguards


data access for concurrency.
C When concurrent access to data is not a concern, map component
outports to a service interface that is configured to use the Direct
Access communication method. In this case, no safeguard for data
access is provided.
Rationale The generated code aligns with the data communication method that is required by
the target platform environment.
Model Advisor Check A Model Advisor check is not necessary for this guideline because a service interface
for a sender service must be configured to use one of the three data communication
methods.

5-12
cgsl_0406: Data send for component deployment

ID: Title cgsl_0406: Data send for component deployment


Example Specifying the Data Communication Method for Calling the Target Platform
Data Sender Service

In this example, the data communication method is set to Outside Execution.

void CD_accumulator(void)
{
.
.
.
for (i = 0; i < 10; i++) {
.
(set_CD_accumulator_out())[i] = CD_param.tunable_gain * CD_sig.delay[i];
}
}

In this example, the data communication method is set to During Execution.

void CD_accumulator(void)
{
real_T out[10];
.
.
.
for (i = 0; i < 10; i++) {
.
out[i] = CD_param.tunable_gain * CD_sig.delay[i];
}
set_CD_accumulator_out(&out[0]);
}

In this example, the data communication method is set to Direct Access.


void CD_accumulator(void)
{
.
.

5-13
5 Component Deployment Using Service Interface Configuration

ID: Title cgsl_0406: Data send for component deployment


.
for (i = 0; i < 10; i++) {
.
.
.
CD_sig.out[i] = CD_param.tunable_gain * CD_sig.delay[i];
}
}

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Receiver and Sender Service Interfaces” (Embedded Coder)

“Data Communication Methods” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

“Select Code Generation Output for Target Platform Deployment” (Embedded Coder)

Out Bus Element

Outport

set (Embedded Coder)

Version History

5-14
cgsl_0408: Partial data send for component deployment

cgsl_0408: Partial data send for component deployment

ID: Title cgsl_0408: Partial data send for component deployment


Description To model a partial data send, set the data communication method to Direct Access and:
A Use an Assignment block to model mutually-exclusive partial write operations.
B Use a Merge block when writing data from multiple functions.
C Configure the outports on the signal path of the component root-level outport for
the partial data send as virtual. To do so, select Outport block parameter Ensure
outport is virtual.
D Map the root-level outport for the partial data send to a service interface that is
configured for direct-access data communication. The signal data is not
safeguarded for concurrent access.
Notes This guideline is only applicable for the export-function modeling style. An Out Bus
Element block cannot be used when modeling partial data write.
Rationale Promotes efficient code by avoiding data copies.
Model Advisor Verify this guideline by using Model Advisor check “Check usage of partial data send”
Check (Embedded Coder).
Examples

void Run1(void)
{
Out[1] = In + 1.0;
}

void Run2(void)
{
Out[0] = In;
}

5-15
5 Component Deployment Using Service Interface Configuration

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Data Communication Methods” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

“Target Environment Services” (Embedded Coder)

Assignment

“Ensure Output Port Is Virtual”

Version History

5-16
cgsl_0409: Data transfer for component deployment

cgsl_0409: Data transfer for component deployment

ID: Title cgsl_0409: Data transfer for component deployment


Description To model data transfers:
A Use signals between callable functions.
B When branching or merging transfer signals, in the Embedded Coder
dictionary, add $X to the Function Naming Rule fields. Compliance with this
rule is enforced during code generation.
C Do not branch data transfer signals to the root-level output port. Compliance
with this rule is enforced during code generation.
Notes When merging data transfer signals, ensure that both signals are mutually exclusive.
Rationale The generated code aligns with the data communication method required by the platform
environment for concurrent execution.
Model Advisor A Model Advisor check is not provided for this guideline.
Check

5-17
5 Component Deployment Using Service Interface Configuration

ID: Title cgsl_0409: Data transfer for component deployment


Examples

void CD_accumulator(void)
.
.
.
tmpIrvIRead = get_CD_accumulator_DataTransfer();
.
.
.

void CD_integrator(void)
.
.
.
tmp = set_CD_integrator_DataTransfer();
.
.
.

void CD_Aperiodic2(void)
.
.
tmp = set_CD_Aperiodic2_DataTransfer();
.
.
.

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Data Transfer Service Interfaces” (Embedded Coder)

“Data Communication Methods” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

“Target Environment Services” (Embedded Coder)

“Select Code Generation Output for Target Platform Deployment” (Embedded Coder)

5-18
Version History

“Configure Signal Data for C Code Generation” (Embedded Coder)

get (Embedded Coder)

set (Embedded Coder)

Version History

5-19
5 Component Deployment Using Service Interface Configuration

cgsl_0410: Timer service for component deployment

ID: Title cgsl_0410: Timer service for component deployment


Description To model the timer service code interface, at the root level of the component:
A Set model configuration parameters:

• Set System target file to ert.tlc


• Set solver parameter Type to Fixed-step
• Set solver parameter Clock resolution to a scalar value of
type double
B To safeguard data for concurrent access, map to a service
interface that is configured to use the During Execution or
Outside Execution data communication method.

• During Execution — The generated callable function that


implements the algorithm safeguards data access for
concurrency.

• Outside Execution —The target platform service safeguards


data access for concurrency.
Notes When a clock resolution is not specified, the code generator uses these default
values for the clock resolution:

• For aperiodic functions, the model fixed-step size (fundamental sample


time)
• For periodic functions, the function sample time

When using S-function to set the timer, for aperiodic functions that are driven
by an S-function that specifies the SS_OPTION_ASYNCHRONOUS option and a
clock resolution, the clock resolution that the S-function specifies overrides the
setting of the Clock resolution parameter.
Rationale Robust handling of data access by functions that execute concurrently.
Model Advisor Check A Model Advisor check is not provided for this guideline.

5-20
cgsl_0410: Timer service for component deployment

ID: Title cgsl_0410: Timer service for component deployment


Examples This example shows the generated code for the header file.

#Header File ComponentDeploymentFcn.h


#include "services.h"
.
.
.
typedef struct {
real_T DataTransfer_WriteBuf[10];
real_T DiscreteTimeIntegrator_PREV_U[10];
uint32_T Interator_PREV_T;
uint8_T DiscreteTimeIntegrator_SYSTEM_E;
boolean_T Integrator_RESET_ELAPS_T;
} D_Work;

typedef struct {
real_T delay[10];
real_T dti[10];
} CD_measured_T;
.
.
.
extern void CD_integrator(void);

In this source code example, the data communication method is set to


Outside-Execution.

CD_measured_T CD_measured;
.
.
.
void CD_integrator(void)
{
real_T tmp;
real_T *tmp_0;
int32_T i;
uint32_T Integrator_ELAPS_T;
tmp_0 = set_CD_integrator_DataTransfer();
if (rtDwork.Integrator_RESET_ELAPS_T) {
Integrator_ELAPS_T = 0U;
} else {
Integrator_ELAPS_T = (uint32_T)(get_tick_outside_CD_integrator() -
rtDWork.Integrator_PREV_T);
}

rtDWork.Integrator_PREV_T = get_tick_outside_CD_integrator();
rtDwork.Integrator_RESET_ELAPS_T = false;
tmp = 1.25 * (real_T)Integrator_ELAPS_T;
for (i = 0; i < 10; i++) {
if ((int32_T)rtDWork.DiscreteTimeIntegrator_SYSTEM_E == 0) {
CD_measured.dti[i] += tmp * rtDWork.DiscreteTimeIntegrator_PREV_U[i];
}

rtDWork.DiscreteTimeIntegrator_PREV_U[i] = (get_CD_
integrator_InBus_u())[i];
}

5-21
5 Component Deployment Using Service Interface Configuration

ID: Title cgsl_0410: Timer service for component deployment

rtDWork.DiscreteTimeIntegrator_SYSTEM_E = 0U;
memcpy(&tmp_0[0], &CD_measured.dti[0], (uint32_T)(10U * sizeof(real_T)));
}

In this source code example, the data communication method is set to During-
Execution.

void CD_integrator(void)
{
real_T tmp[10];
real_T tmp_0;
int32_T i;
uint32_T Integrator_ELAPS_T;
rtM->Timing.clockTick2 = get_tick_during_CD_integrator();
if (rtDWork.Interator_RESET_ELAPS_T) {
Integrator_ELAPS_T = 0U;
} else {
Integrator_ELAPS_T = (uint32_T)(rtM->Timing.clockTick2 -
rtDWork.Integrator_PREV_T);
}

get_CD_integrator_input_(&tmp[0]);
rtDWork.Integrator_PREV_T = rtM->Timing.clockTick2;
rtDWork.Integrator_RESET_ELAPS_T = false;
tmp_0 = 1.25 * (real_T)Integrator_ELAPS_T;
for (i = 0; i < 10; i++) {
if ((int32_T)rtDWork.DiscreteTimeIntegrator_SYSTEM_E == 0) {
CD_measured.dti[i] += tmp_0 * rtDWork.DiscreteTimeIntegrator_PREV_U[i];
}

rtDWork.discreteTimeIntegrator_PREV_U[i] = tmp[i];
}

rtDWork.DiscreteTimeIntegrator_SYSTEM_E = 0U;
set_CD_integrator_DataTransfer(CD_measured.dti);
}

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Create a Service Interface Configuration” (Embedded Coder)

“Data Communication Methods” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

“Generate C Timer Service Interface Code for Component Deployment” (Embedded Coder)

Version History

5-22
cgsl_0411: Access nonvolatile memory by using Initialize Function and Terminate Function blocks

cgsl_0411: Access nonvolatile memory by using Initialize


Function and Terminate Function blocks

ID: Title 0411: Access nonvolatile memory by using Initialize Function and Terminate
Function blocks
Description To model the Direct Access data communication method to target platform nonvolatile
memory:
A At the root-level of the component, use the Initialize Function block to read
data and the Terminate Function block to write data.
B Configure the root-level ports to use the Direct Access data communication
method.
Notes When accessing nonvolatile memory during function execution, see guideline “cgsl_0406:
Data send for component deployment” on page 5-12 and “cgsl_0405: Data receive for
component deployment” on page 5-9.

When you need to access nonvolatile memory by using a service provided by the target
environment, use a client-server interface approach for modeling the interface. With that
approach you represent the target environment service that provides access to nonvolatile
memory by using a Simulink Function block and access the service by using the Function
Caller block. For more information, see “Nonvolatile Memory Interfaces” (Embedded
Coder).
Rationale • Robust handling of data access by functions that execute concurrently.
• Supports multiple instances of components.
Model Advisor A Model Advisor check is not provided for this guideline.
Check

5-23
5 Component Deployment Using Service Interface Configuration

ID: Title 0411: Access nonvolatile memory by using Initialize Function and Terminate
Function blocks
Examples

void CD_initialize(void)
.
.
.
&(get_CD_initialize_input[))[0]
.
.
.
void CD_terminate(void)
{
memcpy[&(getref_CD_terminate_OutBus_NVM[))[0]...
}

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Service Interfaces” (Embedded Coder)

“Client-Server Interface” (Embedded Coder)

Initialize Function

Terminate Function

Reset Function

“Using Initialize, Reinitialize, Reset, and Terminate Functions”

5-24
Version History

Version History

5-25
5 Component Deployment Using Service Interface Configuration

cgsl_0413: Reuse memory between component state and


output for component deployment

ID: Title cgsl_0413: Reuse memory between component state and output for component
deployment
Description To optimize component memory usage by reusing memory for state and output data, use
one of these methods:
A Use a function loopback pattern to model the state variable as a signal.
B Use a Delay block to model the state variable explicitly. Set the state of the
Delay block and the function output port to the same literal initial condition
value.
Notes This approach is applicable for data communication methods Outside Execution and
Direct Access because these methods can access persistent memory.

For method B, the code generator makes a best effort to optimize memory usage. Under
some conditions, such as when initialization is done dynamically by using a signal rather
than a parameter, the code generator might not apply the optimization. If the optimization
does not occur, consider using method A. Regardless of whether you use approach A or B,
the code generator implements robust handling of data access by functions that execute
concurrently.
Rationale A Reuse of memory for state and output data.

Optimization survives dynamic initialization.


B Reuse of memory for state and output data.
Model Advisor A Model Advisor check is not provided for this guideline.
Check

5-26
cgsl_0413: Reuse memory between component state and output for component deployment

ID: Title cgsl_0413: Reuse memory between component state and output for component
deployment
Examples

In this example, the data communication method is set to "Direct Access".

void CD_accumulator(void)
{
int32_T i;
for (i=0; i<10; i++) {
Out[i] += In[i];
}
}

In this example, the data communication method is set to "Outside Execution".

void CD_accumulator(void)
{
real_T tmpIrvRead[10];
int32_T i;
tmp = set_CD_accumulator_her_out_y();
for (i=0; i<10; i++) {
tmp[i] = (get_CD_accumulator_DataTransfer(tmpIrvRead))[i] + tmp[i];
}
}

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Service Interfaces” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

5-27
5 Component Deployment Using Service Interface Configuration

“Data Communication Methods” (Embedded Coder)

Delay

Use dynamic memory allocation for model initialization (Embedded Coder)

Version History

5-28
cgsl_0414: Configure service interface for component model

cgsl_0414: Configure service interface for component model

ID: Title cgsl_0414: Configure service interface for component model


Description The following configuration shall be applied:
A Link the model to an Embedded Coder dictionary that defines a service code
interface.
B Configure deployment types as:

• Component for the top model


• Subcomponent for the submodel (referenced model)
C Use the Code Mappings editor or code mappings programming interface to
map model elements that represent interfaces to service interfaces that are
defined in the linked coder dictionary.
Rationale Deploy models as components that include comprehensive service interface support,
including support for concurrent data access.

Generate component model code intended to interact with service implementations of a


target platform.
Model Advisor Verify this guideline by using Model Advisor check “Check configuration for component
Check deployment” (Embedded Coder)

See Also
“Code Interfaces and Code Interface Specification” (Embedded Coder)

“Create a Service Interface Configuration” (Embedded Coder)

Embedded Coder Dictionary (Embedded Coder)

Version History

5-29

You might also like