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 MathW orks, 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
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
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 Docu mentation, 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
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Embedded Coder™ User’s Guide
Page 3
Revision History
July 2002Online onlyVersion 3.0 (Release 13)
December 2003Online onlyRevised for Version 3.2 (Release 13SP1+)
June 2004Online onlyRevised for Version 4.0 (Release 14)
October 2004Online onlyRevised for Version 4.1 (Release 14SP1)
March 2005Online onlyRevised for Version 4.2 (Release 14SP2)
September 2005 O nline onlyRevised for Version 4.3 (Release 14SP3)
March 2006Online onlyRevised for Version 4.4 (Release 2006a)
September 2006 O nline onlyRevised for Version 4.5 (Release 2006b)
March 2007Online onlyRevised for Version 4.6 (Release 2007a)
September 2007 O nline onlyRevised for Version 5.0 (Release 2007b)
March 2008Online onlyRevised for Version 5.1 (Release 2008a)
October 2008Online onlyRevised for Version 5.2 (Release 2008b)
March 2009Online onlyRevised for Version 5.3 (Release 2009a)
September 2009 O nline onlyRevised for Version 5.4 (Release 2009b)
March 2010Online onlyRevised for Version 5.5 (Release 2010a)
Page 4
Page 5
Contents
Introduction to the Real-Time Workshop
®
Embedded Coder Product
1
Developing Models for Code Generation
Setting Up Your Modeling Environment
2
Architecture Considerations
3
Generating Code Variants for Variant Models ........3-2
Prerequisites
Why Generate Code Variants?
How to Generate Code Variations for Model Variants
Reviewing Code V ariants in the Code Generation
Report
Example of Variants in the Generated Code
Demo for Code Variants Using Model B locks
.....................................3-2
.......................3-2
....3-3
........................................3-5
............3-6
...........3-8
Creating and Using Host-Based Shared Librar ie s
Overview
Generating a Shared Library Version of Your Model
Code
Creating Application Code to Load and Use Your S hared
Using Discrete and Continuous Time ................4-2
Generating Code for Discrete and Continuous Time
Blocks
Generating Code that Supports Continuous Solvers
Generating Code that Honors a Stop Time
Optimizing Task Scheduling for Multirate Multitasking
Models on RTOS Targets
Overview
Using rtmStepTask
Task Scheduling Code for Multirate Multitasking Model on
Wind River Systems VxWorks Target
Suppressing Redundant Scheduling Calls
Developing Model Patterns that Generate
........................................4-2
.............4-3
.........................4-4
........................................4-4
................................4-5
...............4-5
..............4-6
Specific C Constructs
.....4-2
viContents
5
About Modeling Patterns ...........................5-2
Standard Methods to Prepare a Model for Code
Generation
Configuring a Signal
Configuring Input and Output Ports
Initializing States
Setting Up Configuration Parameters for Code
Generation
Setting Up an Example Model With a Stateflow Chart
SettingUpanExampleModelWithanEmbeddedMATLAB
Block
Types, Operators, and Expressions
Data Declaration
Data Type Conversion
Type Qualifiers
......................................5-3
...............................5-3
..................5-4
.................................5-4
.....................................5-4
.........................................5-7
..................5-8
..................................5-8
.............................. 5-11
...................................5-15
...5-5
Page 7
Relational and Logical Operators ..................... 5-17
Bitwise O perations
................................5-21
Control Flow
If-Else
Switch
For loop
While loop
Do While loop
Functions
Function Call
Function Prototyping
External C Functions
......................................5-25
........................................... 5-25
..........................................5-32
.........................................5-38
.......................................5-46
.....................................5-57
.........................................5-64
.....................................5-64
.............................. 5-66
.............................. 5-69
Defining Data Representation and Storage
for Code Generation
Using mpt Data Objects
6
Creating and Using Custom Storage Classes
7
Introduction to Custom Storage Classes .............7-2
Custom Sto rage Class Memory Sections
Registering Custom Storage Classes
Custom Sto rage Class Demos
Resources for Defining Custom Storage Classes
Simulink Package Custom Storage Classes
Creating Packages that Support CSC Definitions
........................7-4
...............7-3
..................7-3
......7-5
...........7-6
.....7-8
vii
Page 8
Designing Custom Storage Classes and Memory
Sections
Using the Custom Storage Class Designer
Editing Custom Storage Class Properties
Using Custom Storage Class References
Creating and Editing Memory Section Definitions
Using Memory Section References
........................................7-12
............. 7-12
.............. 7-19
............... 7-26
.................... 7-34
....... 7-31
Applying CSCs to Parameters and Signals
About Applying Custom Storage Classes
Applying a Custom Storage Class to a Parameter
Applying a Custom Storage Class to a Signal
Applying a CSC Using a Base Workspace Signal Object
Applying a CSC Using an Embedded Signal Object
Specifying a Custom Storage Class Using the GUI
Specifying a Custom Storage Class Using the API
Generating Code with Custom Storage Classes
Code Generation Prerequisites
Code Generation Example
Defining Advanced Custom Storage Class Types
Introduction
Create Your Own Parameter and Signal Classes
Create a Custom Attributes Class for Your CSC
(Optional)
WriteTLCCodeforYourCSC
Register Custom Storage Class Definitions
GetSet Custom Storage Class for Data Store Memory
Overview
GetSet CSC Properties
Using the GetSet CSC
GetSet CSC Restrictions
GetSet Custom Storage Class Example
......................................7-62
......................................7-62
........................................7-66
............................. 7-66
.............................. 7-67
....................... 7-58
.......................... 7-58
....................... 7-63
............................ 7-67
........... 7-37
............... 7-37
....... 7-38
........... 7-40
...... 7-43
...... 7-50
....... 7-53
....... 7-58
...... 7-62
........ 7-62
............. 7-63
................ 7-68
.. 7-41
.. 7-66
viiiContents
Custom Storage Class Implementation
Custom Storage Class Limitations
Custom Storage Classes Prior to R2009a
................... 7-72
.............. 7-70
............. 7-73
Page 9
Custom Storage Classes Prior to Release 14 .......... 7-74
Introduction
Simulink.CustomParameter Class
Simulink.CustomSignal Class
Instance-Specific Attributes for Older Storage Classes
Assigning a Custom Storage Class to Data
Code Generation with Older Custom Storage Classes
Compatibility Issues for Older Custom Storage Classes
......................................7-74
.................... 7-74
....................... 7-75
............. 7-79
.... 7-80
Inserting Comments and Pragmas in Generated
8
Introduction to Memory Sections ...................8-2
Overview
Memory Sections Demo
Additional Information
........................................8-2
.............................8-2
.............................8-2
... 7-78
.. 7-81
Code
Requirements for Defining Memory Sections
Defining Mem ory Sections
Editing Me mory Section Proper ties
Specifying the Memory Section Name
Specifying a Qualifier for Custom Storage Class Data
Definitions
Specifying Comment and Pragma Text
Surrounding Individual Definitions with Pragmas
Including Identifier Names in Pragmas
Configuring Memory Sections
Applying M em ory Sections
Assigning Me m ory Sections to Custom Storage Classes
Applying Memory Sections to Model-Level Functions and
Internal Data
Applying Memory Sections to Atomic Subsystems
Examples of Generated Code with Memory Sections
.....................................8-9
..................................8-14
..........................8-7
...................8-7
.................8-9
................8-9
............... 8-10
...................... 8-11
......................... 8-12
.........8-4
......8-9
....... 8-16
.. 8-12
.. 8-20
ix
Page 10
Sample ERT-Based Model with Subsystem ............. 8-20
Saving and Loading Data Objects ................... 11-29
Applying Naming Rules to Identifiers Globally
Overview
Changing Names of Identifiers
Specifying Simulink Data Object Naming Rules
Defining Rules That Change All Signal Names
Defining Rules That Change All Parameter Names
Defining Rules That Change All #defines
Creating User Data Types
Overview
Registering User Data Types Using sl_customization.m
Example User Data Type Customization Using
sl_customization.m
Selecting User Data Types for Signals and
Parameters
Preparing U se r Data Typ es
Selecting the User Data Types
Registering mpt User Object Types
Introduction
Registering mpt User Object Types Using
sl_customization.m
Example mpt User Object Type Customization Using
sl_customization.m
........................................ 11-30
....................... 11-31
.............. 11-36
.......................... 11-38
........................................ 11-38
.............................. 11-41
..................................... 11-43
......................... 11-43
....................... 11-45
.................. 11-48
...................................... 11-48
.............................. 11-48
.............................. 11-50
....... 11-30
........ 11-34
......... 11-35
...... 11-35
.. 11-39
xiiContents
Replacing Built-In Data Type Names in Generated
Code
Replacing Built-In Data Type Names
Replacing
Data Type Replacement Limitations
Customizing Data Object Wizard User Packages
Introduction
Registering Data Object Wizard User Packages Using
Example Data Object Wizard User Package Customization
........................................... 11-52
................. 11-52
boolean with an Integer Data Type .......... 11-58
.................. 11-60
...... 11-61
...................................... 11-61
sl_customization.m
Using sl_customization.m
.............................. 11-61
......................... 11-63
Page 13
12
Managing Placement of Data Definitions and
Declarations
Overview of Data Placement ........................ 12-2
Priority and Usage
Overview
Read-Write Priority
Global Priority
Definition File, Header File, and Ownership Priorities
Ownership Settings
Memory Section Settings
Data Placement Rules
Example Settings
Introduction
Read-Write Example
Ownership Example
Header File Example
Definition File Example
Data Placem ent Rules and Effects
Effects of Ownership Settings
Example Settings and Resulting Generated Files
Data Placement Rules
........................................12-3
.................................12-3
................................12-5
....................................12-7
................................ 12-10
........................... 12-11
.............................. 12-12
.................................. 12-13
...................................... 12-13
............................... 12-15
............................... 12-17
.............................. 12-18
............................ 12-20
................... 12-22
....................... 12-22
.............................. 12-25
... 12-9
....... 12-23
xiii
Page 14
13
Specifying the Persistence Level for Signals and
Parameters
Preparing Mode
Mapping Applicati on Objectives to Model
14
Considerations When Mapping Application
Objectives
Defining High-Level Code Generation Objectives
Determining Whether the Model is Configured for
Specified Objectives
Specifying Code Generation Objectives Using the GUI
Specifying Code Generation Objectives at the Command
Line
Reviewing O bjectives in Referenced Models
Reviewing the Model Without Generating Code
Reviewing the Model During Code Generation
Creating Custom Objectives
Specifying Parameters in Custom Objectives
Specifying Checks in Custom Objectives
Determining Checks and Parameters in Existing
Customizing Comments in Generated Code .......... 16-2
Adding Custom Comments to Generated Code
Adding Global Comments
Configuring the Appearance of Generated
Identifiers
Customizing G enerated Identifiers
Configuring Symbols
...................................... 16-11
........................... 16-5
................... 16-11
............................... 16-12
.......... 16-2
Controlling Code Style
Configuring Templates for Customizing Code
Organization and Format
Overview
Custom F ile Processing Components
Custom F ile Processing User Interface Options
Code Generation Template (CGT) Files
Using Custom File Processing (CFP) Templates
........................................ 16-23
............................. 16-21
........................ 16-22
.................. 16-24
................ 16-26
......... 16-24
......... 16-30
xv
Page 16
Custom F ile Processing (CFP) Template Structure ...... 16-30
Changing the Organization of a Generated File
Generating Source and Header Files with a Custom File
Processing (CFP) Template
Comparison of a Template and Its Generated File
Code Template API Summary
Generating Custom File and Function Banners
Template Symbols and Rules
Introduction
Generated C ode Modules
User-Written Code Modules
Customizing G enerated Code Modules
......................................18-2
........................... 18-2
......................... 18-5
................ 18-5
xviContents
Page 17
19
Generating Reports for Code Reviews and
Traceability Analysis
About HTM L Code G eneration Report Extensions .... 19-2
20
Generating an HTML Code Generation Report
UsingtheCodeInterfaceReporttoAnalyzethe
Generated Code Interface
Code Interface Report Overview
Generating a Code Interface Report
Navigating Code Interface Report Subsections
Interpreting the Entry Point Functions Subsection
Interpreting the Inports and Outports Subsections
Interpreting the Interface Parameters Subsection
Interpreting the Data Stores Subsection
Code Interface Report Limitations
........................ 19-6
..................... 19-6
.................. 19-7
............... 19-16
.................... 19-17
....... 19-4
.......... 19-9
...... 19-10
...... 19-13
....... 19-14
Optimizing Generated Code
Configuring Production Code Optimizations .........20-2
Optimization Depen den cies
........................ 20-4
Optimizing Your Model with Configuration Wizard
Blocks and Scripts
Overview
Adding a Configuration Wizard Block to Your Model
Using Configuration Wizard Blocks
Creating a Custom Configuration Wizard Block
Tips for Optimizing the Generated Code
Introduction
Using Configuration Wizard Blocks
........................................20-6
...................................... 20-19
............................... 20-6
................... 20-11
......... 20-11
............. 20-19
................... 20-19
..... 20-8
xvii
Page 18
21
Setting H ard ware Implem en ta t ion Parameters
Correctly
Removing Unnecessary Initialization Code
Generating Pure Integer Code If Possible
Disabling MAT-File Logging
Using Virtualized Output Ports Optimization
Controlling Signal Storage
Using External Mode with the ERT Target
...................................... 20-20
............. 20-22
.............. 20-23
........................ 20-23
.......... 20-24
.......................... 20-25
............. 20-26
Developing Models and Code That Comply with
Industry Standards and Guidelines
What Are the Standards and Guidelines? ............ 21-2
Developing M odels and Code That Comply with MAAB
Guidelines
Developing Models and Code That Comply with MISRA
C Guidelines
......................................21-4
....................................21-5
xviiiContents
Developing Models and Code That Comply with the IEC
61508 Standard
Applying Simulink and Real-Time Workshop Technology to
the IEC 61508 Standard
Checking for IEC 61508 Standard Compliance Using the
Model Advisor
Validating Traceability
Developing Models and Code That Comply with the
DO-178B Standard
Applying Simulink and Real-Time Workshop Technology to
the DO-178B Standard
Checking for Standard Compliance Using the Model
Advisor
Validating Traceability
........................................21-8
..................................21-6
.......................... 21-6
..................................21-6
............................. 21-7
............................... 21-8
........................... 21-8
............................. 21-9
Page 19
22
Generating Code for AUTOSAR Software
Components
Overview of AUTOSAR Support ..................... 22-2
Simulink M odeling Patterns for AUTOSAR
AUTOSAR Software Components
AUTOSAR Communication
Calibration Parameters
Inter-Runnable Variables
Data Types
AUTOSAR Terminology
Workflow for AUTOSAR
Importing an AUTOSAR Software Component
Using the C onfigure AUTOSAR Interface D i alog Box
Configuring Ports for Basic Software and Error Status
Receivers
Configuring Client-Server Communication
Configuring a Server Operation
Configuring the Invoke AUTOSAR Server Operation
Block
Creating Configurable Subsystems from a Client-Server
Interface
Simulating and Generating Code for Client-Server
Communication
....................................... 22-20
....................................... 22-37
......................................... 22-43
...................................... 22-45
............................ 22-19
........................... 22-19
............................ 22-25
........................... 22-28
................................. 22-46
.................... 22-3
......................... 22-11
...................... 22-40
.......... 22-3
....... 22-30
.. 22-32
.......... 22-39
Configuring Calibration Parameters
Modifying and Validating an Existing AUTOSAR
Interface
Exporting a Single Runnable AUTOSAR Software
Component
........................................ 22-49
..................................... 22-50
................ 22-48
xix
Page 20
Selecting an AUTOSAR Schema ..................... 22-51
Generating AUT OSA R Compiler Abstraction Macros
.... 22-52
Configuring Multiple Runnables
Configuring AUTOSAR Options Programmatically
Verifying the AUTOSAR Code with SIL and PIL
Simulations
Overview
Using the SIL and PIL Simulation Modes
Using a SIL Block for AUTOSAR Verification
Information
Error If No Default Configuration
Server Operation Model with Reusable Function
Subsystems
Invoke AUTOSAR Server Operation Block in Referenced
Model
Server Operation and Model Block with States
Cannot Save Importer Objects in MAT-Files
Using the Merge Block for Inter-Runnable Variables
AUTOSAR Compiler Abstraction Macros
Intrinsic Fixed-Point Types for Model Configured as
Server
Server Operation Model with Tunable Parameters
Migrating AUTOSAR Development Kit Models
..................................... 22-59
........................................ 22-59
............................... 22-62
.................................... 22-62
.................................... 22-63
......................................... 22-63
........................................ 22-64
.................... 22-55
.............. 22-59
.......... 22-60
.................... 22-62
.................... 22-63
......... 22-63
........... 22-63
.............. 22-64
......... 22-65
... 22-58
.... 22-63
...... 22-65
xxContents
Demos and Further Reading
AUTOSAR Demos
Further Reading
................................. 22-66
.................................. 22-67
........................ 22-66
Page 21
Integrating External Code and Generated
CandC++Code
About External Code Integration Extensions
23
Generating S-Function Wrappers
24
About S-Function Wrapper Generation .............. 24-2
Launching the Model Interface D ialog Boxes
Default Model Initialize and Step Functions View
............. 27-4
........... 27-4
....... 27-4
Page 23
Model Specific C Prototypes View .................... 27-5
Configuring Function Prototypes for Nonvirtual
Subsystems
....................................27-9
28
Model Fu nction Prototypes Example
Configuring Model Function Prototypes
Programmatically
Sample Script for Configuring Model Function
Prototypes
Verifying Generated Code for Customized Functions
Model Fu nction Prototype Control Limitations
...................................... 27-22
............................... 27-18
................ 27-12
.. 27-23
....... 27-24
Controlling Generation of Encapsulated C++
Model Interfaces
Overview of C++ Encapsulation ..................... 28-2
C++ Encapsulation Quick-Start Example
Generating and Configuring C++ Encapsulation
Interfaces to Model Code
Selecting the C++ (Encapsulated) Option
Configuring Code Interface Options
Configuring the Step Method for Your Model Class
Configuring C++ Encapsulation Interfaces for Nonvirtual
Subsystems
Configuring C++ Encapsulation Interfaces
Programmatically
.................................... 28-20
............................... 28-22
......................... 28-12
............. 28-4
.............. 28-12
.................. 28-13
...... 28-15
xxiii
Page 24
Sample Script for Configuring the Step Method for a
Model Class
..................................... 28-25
29
C++ Encapsulation Interface Control Limitations
.... 28-27
Replacing Math Functions and Operators Using
Target Function Libraries
Introduction to Target Function Libraries ........... 29-2
Overview o f Target Function Libraries
Target Function Libraries General Workflow
Target Function Libraries Quick-Start Example
Creating Function Replacement Tables
Overview o f Function Replacement Table Creation
Creating Table Entries
Example: Mapping Math Functions to Target-Specific
Implementations
Example: Mapping the memcpy Function to a
Target-Specific Implementation
Example: Mapping Nonfinite Support Utility Functions to
Target-Specific Implementations
Example: Map p ing Scalar Operators to Target-Specific
Implementations
Mapping Nonscalar Operators to Target-Specific
Implementations
Mapping Fixed-Point Operators to Target-Specific
Implementations
Remapping Operator Outputs to Implementation Function
Input Positions
Refining TFL Matching and Replacement Using Custom
TFL Table Entries
Specifying Build Information for Function
Replacements
Adding Target Function Library Reserved Identifiers
............................. 29-20
................................ 29-27
................................ 29-44
................................ 29-50
................................ 29-80
................................. 29-115
.............................. 29-117
.................................. 29-134
................ 29-2
........... 29-7
........ 29-9
.............. 29-16
...... 29-16
.................... 29-34
................... 29-39
.... 29-137
xxivContents
Examining and Validating Function Replacement
Tables
.......................................... 29-140
Page 25
Overview o f Function Replacement Table Validation ..... 29-140
Invoking the Table Definition File
Using the Target Function Library Viewer to Examine Your
Table
Using the Target Function Library Viewer to Examine
Registered TFLs
Tracing Code Generated Using Your Target Function
Library
Examining TFL Cache Hits and Misses
......................................... 29-141
................................ 29-142
........................................ 29-144
.................... 29-140
............... 29-145
Registering Target Function Libraries
Overview of TFL Registration
Using the sl_customization API to Register a TFL with
Simulink Software
Using the rtwTargetInfo API to Register a TFL with
Embedded MATLAB Coder Software
Registering Multiple TFLs
Target Function Library Limitations
.............................. 29-150
....................... 29-149
.......................... 29-156
.............. 29-149
............... 29-154
................ 29-158
Setting Up Generated Code To Interface
With Components in the Run-Time
Environment
Configuring the Target Hardware Environment
30
guring Support for N um eric Data
Confi
..............
30-2
iguring Support for Time Values
Conf
ting Up Support for Non-Inlined S-Functions
Set
figuring Model Function Generation and Argument
Con
Pa
ssing
.........................................
...............
.....
30-3
30-
-5
30
4
xxv
Page 26
Setting Up Support for Code Reuse................. 30-7
31
Configuring Target Function Libraries
.............. 30-8
Interfacing With Hardware That is Not Running
an Operating System (Bare Board)
About Standalone Program Execution ............... 31-2
Generating a Standalone Program
Standalone Program Components
Main Program
Overview of Operation
Guidelines for Modifying the Main Program
rt_OneStep and Scheduling Considerations
Overview of Operation
Single-Rate Single-tasking Operation
Multirate Multitasking Operation
Multirate Single-Tasking Operation
Guidelines for Modifying rt_OneStep
.....................................31-5
............................. 31-5
............................. 31-7
.................. 31-3
................... 31-4
............ 31-5
.......... 31-7
................. 31-8
.................... 31-9
.................. 31-12
................. 31-12
xxviContents
Model Entry Points
Static Main Program Module
Overview
Rate Grouping and the Static Main Program
Modifying the Static Main Program
Rate Grouping Compliance and Compatibility
Issues
Main Program Compatibility
Making Your S-Functions Rate Grouping Compliant
About Checking Code Correctness
How To Check Code Correctness
PolySpace Analysis Option s
.................... 34-11
..................... 34-11
......................... 34-12
Rapid Prototyping On a Target System
About On-Target Rapid Prototyping ................. 35-2
36
Goals of On-Target Rapid Prototyping
Optimizing Generated Code for an Embedded Processor
With On-Target Rapid Prototyping
............... 35-3
................ 35-4
Verifying Generated Source Code With
Software-in-the-Loop Simulation
About Software-in-the-Loop Simulation ............. 36-2
VerifyingCodeUsingtheSILSimulationMode
About SIL Simulation Mode
ComparisonofSILandPILSimulation
Choosing a SIL Approach
About Choosing a SIL Simulation
When to Use Top-Mo de l SIL
When to Use Model Block SIL
When to Use the SIL Block
......................... 36-3
................ 36-3
.......................... 36-5
.................... 36-5
......................... 36-5
....................... 36-6
.......................... 36-10
....... 36-3
xxviiiContents
Running a Complete Model as a SIL Simulation
Running a Referenced Model as a SIL Simulation
...... 36-12
.... 36-14
Page 29
Verifying Internal Signals of a Component ............. 36-14
Simulation Mode Override Behavior in Model Reference
Hierarchy
...................................... 36-15
SIL Code Interfaces
Code Interface for Top-Mode l SIL
Code Interface for Model Block SIL
Configuring a SIL Simulation
Configuring a Top-Model SIL Simulation
Configuring a Model Block SIL Simulation
Using a Code Coverage Tool in a SIL Simulation
Verifying a SIL or PIL Configuration
Compatible Models
Verifying Code Using a SIL Block
Configuring H ardware Implementation Settings
Compiling Generated Code That Supports Portable Word
Sizes
.......................................... 36-33
Portable Word Sizes Limitation
SIL Support and Limitations
................................ 36-16
.................... 36-16
................... 36-16
....................... 36-18
.............. 36-18
............. 36-20
........ 36-22
................. 36-26
................................ 36-28
................... 36-30
...................... 36-33
....................... 36-34
..... 36-31
37
Verifying a Component in the Target
Environment
About Component Verification in the Target
Environment
Goals of Component Verification in the Target
Environment
Maximizing Code Portability and Configurability
....................................37-2
....................................37-3
.... 37-4
xxix
Page 30
38
Simplifying Code Integration and Maximizing Code
Efficiency
Running Component Tests in the Target
Environment
.......................................37-5
....................................37-7
Verifying a Component byBuildingaComplete
Real-Time Target Environment
About Component Verification With a Complete
Real-Time Target Environment
Goals of Component Verification With a Complete
Real-Time Target Environment
Testing a Component as Part of a Complete Real-Time
Target Environment
............................. 38-5
................... 38-2
................... 38-4
xxxContents
39
Verifying Compiled Object Code with
Processor-in-the-Loop Simulation
About Processor-In-the-Loop Simulation ............ 39-2
What Is Processor-in-the-Loop Simulation?
Why Use PIL Simulation?
Problems That PIL Simulation Can Detect
How PIL Simulation Works
Choosing a PIL Approach
Comparing Methods for Applying PIL Simulations
Modeling Scenarios with the PIL Block
.......................... 39-2
......................... 39-3
.......................... 39-5
............ 39-2
............. 39-3
...... 39-5
................ 39-5
Page 31
Programming PIL Support for Third-Party Tools and
Target Hardware
................................39-8
PIL Code Interfaces
Setting Up PIL Simulations With the Embedded IDE
Link Product PIL Block
Configuring a PIL Simulation
Configuring a Top-Model PIL Simulation
Configuring PIL Mode in the Model Block
Code Coverage for a PIL Simulation
Creating a Connectivity Configuration for a Target
What Is a PIL Connectivity Configuration?
Overview o f the Target Connectivity API
Creating a Connectivity API Implementation
Registering a Connectivity API Implementation
Demos of the Target Connectivity API
SIL a nd PIL S imulation Support and Limitations
SIL and PIL Simulation Support
Code Source Support
Block Support
Configuration Parameters Support
I/O Support
Hardware Implementation Support
Other Feature Support
PIL Block Limitations
...................................... 39-33
................................39-9
.......................... 39-10
...................... 39-14
.............. 39-14
............. 39-16
.................. 39-16
............ 39-18
.............. 39-19
........... 39-22
........ 39-22
................ 39-22
..... 39-24
..................... 39-25
............................... 39-26
.................................... 39-27
................... 39-29
.................. 39-42
............................. 39-46
.............................. 39-46
... 39-18
40
Verifying Numerical Equivalence of Results
with Code Generation Verification API
Verifying Numerical Equivalence with Code Generation
Verification
Code Generation Verification API Overview
Verifying Numerical Equivalence with CGV Workflow
.....................................40-2
............ 40-2
... 40-2
xxxi
Page 32
Example of Verifying Numerical Equivalence Between Two
Modes of Execution of a Model
Example of Plotting Output Signals
The Real-Time Workshop®Embedded Coder™ product extends the Real-Time
Workshop
development. Using the Real-Time Workshop Embedded Coder add-on
product, you gain access to all aspects of Real-Time Workshop technology
and can generate code that has the clarity and efficiency of professional
handwritten code. For example, you can
• Generate code that is compact and fast, which is essential f or real-time
simulators, on-target rapid prototyping boards, microprocessors used in
mass production, and embedded systems
• Customize the appearance of the generated code
• Optimize the generated code for a specific target environment
• Integrate existing (legacy) applications, functions, and data
• Enable tracin g, reporting, and t estin g options that facilitate code
verification activities
For detailed information on how the Real-Time Workshop Embedded Coder
product fits into the complete Real-Time Workshop technology picture, see
“Getting Started with Real-Time Workshop Technology” in the Real-Time
Workshop documentation. That topic positions the Real-T im e Workshop
Embedded Coder in terms of what you can accomplish with it, how it can fit
intoyourdevelopmentprocess,howyoumightapplyittotheV-modelfor
system development, and how you might apply it to relevant use cases.
®
product w ith features that are important for embedded software
Page 34
1 Introduction to the Real-Time Workshop
Because Real-Time Workshop Embedded Coder extends Real-Time Workshop
for code generation, to use the Real-Time Workshop Embedded Coder
product effectively, you should be familiar with inform ati o n in parts of the
Real-Time Workshop documentation that align with corresponding parts in
the Real-Time Workshop Embedded Coder documentation.
• “Introduction to Real-Time Workshop Technology”
• “Developing Models for Code Generation”
• “Defining Data Representation and Storage for Code Generation”
• “Preparing Models for C ode Generation”
• “Generating Code and Building Executables”
• “Integrating External Code With Generated C and C++ Code”
• “Setting Up Generated Code To Interface With Components in the
Run-Time Environment”
• “Verifying Generated Code Applications”
®
Embedded Coder™ Product
1-2
Page 35
DevelopingModelsforCode
Generation
• Chapter 2, “Setting Up Your Modeling Environment”
• Chapter 3, “Architecture Considerations”
• Chapter 4, “Scheduling Considerations”
• Chapter 5, “Developing Model Patterns that Generate Specific C
Constructs”
Page 36
Page 37
Setting Up Your Modeling
Environment
When developing a system, it is important to use the correct combination of
products to model each system component based on the domain to which it
applies.
The following table guides you to information and demos that pertain to
use of the Real-Time Workshop Embedded Coder product to meet goals for
specific domains.
2
GoalsRelated Product
Information
Generate a
software design
description
Trace model
requirements to
generated code
Simulink®Report
Generator™
Simulink Report
Generator
documentation
Simulink
Verification and
Validation™
“Including
Requirements
Information with
Generated Code”
in the Simulink
Verification
and Validation
documentation
®
Demos
rtwdemo_codegenrpt
rtwdemo_requirements
Page 38
2 Setting Up Your Modeling Environment
GoalsRelated Product
Information
Implement
application
on fixed-point
processors
Simulink
Point™
“Data Types and
Scaling” and “Code
®
Fixed
Generation” in the
Simulink Fixed Point
documentation
Use an
integrated
development
environment
(IDE) to
integrate an
application on a
target processor
automatically
See help for Embedded IDE
Link and Target Support
Package products
2-2
Page 39
3
Architecture Considerations
• “Generating Code Variants for Variant Models” on page 3-2
• “Creating and Using Host-Based Shared Libraries” on page 3-9
Page 40
3 Architecture Considerations
Generating Code Variants for Variant Models
In this section...
“Prerequisites” on page 3-2
“Why Generate Code Variants?” on page 3-2
“How to Generate Code Variations for Model Variants” on page 3-3
“Reviewing Code Variants in the Code Generation Report” on page 3-5
“Example of Variants in the Generated C ode” on page 3-6
“Demo for Code Variants Using Model Blocks” on page 3-8
Prerequisites
The R eal-Time Worksho p Embedded C oder software generates code variants
from a Simulink
how to create a model containing model reference variants, see “Using
Model Reference Variants” in the Simulink documentation. The Real-Time
Workshop Embedded Coder software generates code for all variants of a
referenced model. In the generated code, variants are preprocessor conditional
directives that determine theactivevariantandthesectionsofcodetoexecute.
®
model containing model refere nce variants. To learn
3-2
Note You cannot generate code variants for models with continuous states.
Why Generate Code Variants?
When you implement variants in the generated code, you can:
• Reuse generated code from a set of application models that share
functionality with minor variations.
• Share generated code with a third party that activates one of the variants
in the code.
• Validate all of the supported variants for a model and then choose to
activate one variant for a particular application, without regenerating
and revalidating the code.
Page 41
Generating Code Variants for Variant Models
How to Generate Code Variations for Model Variants
Defining Variant Control Variables and Variant Objects for
Generating Code
To learn about variant control variables and variant objects see Implementing
Model Reference Variants in the Simulink documentation. Variant control
variables used for code generation have different requirements than variant
control variables used for simulation. Perform the following steps to define
variant control variables for generating code.
1 Open the Model Explorer and click the Base Workspace.
2 A variant control variable can be a Simulink.Parameter object or a
mpt.Parameter object. In the Model Explorer, select Add and choose either
Simulink Parameter or MPT Parameter.Specifyanameforthenew
parameter.
3 On the Simulink.Parameter or mpt.Parameter property dialog box, specify
the Storage class parameter by choosing one of the following:
•
ImportedDefine(Custom) custom storage class.
CompilerFlag(Custom) custom storage class.
•
• A user-defined storage class created using the Custom Storage Class
Designer. Your storage class must have the Data initialization
parameter set to
Macro and the Data scope parameter set to Imported.
See “Using the Custom Storage Class Designer” on page 7-12 for more
information.
Note If the storage class is CompilerFlag(Custom) then the makefile
options (for example,
4 If the storage class is either ImportedDefine(Custom) or a user-defined
OPTOPTS) must specify the macro and its value.
custom storage class, specify the Header File parameter as an external
header file in the Custom Attributes section of the
Simulink.Parameter
property dialog box.
3-3
Page 42
3 Architecture Considerations
5 Supply the values of the variant control variables in the external
header file. The generated code refers to a variant control variable as a
user-defined macro. The generated code does not contain the value of the
macro. The value of the variant control variable determines the active
variant in the compiled code. You can use a MATLAB
6 Follow the instructions for “Implementing Variant Objects” for model
reference variants to implement variant objects for code generation.
Ensure that only one variant object is active in the generated code by
implementing the condition expressions of the variant objects such that
only one evaluates to
true. The generated code includes a test of the
variant objects to determine that there is only one active variant. If this
test fails, your code might not compile.
Note You can define the variant object condition values using
Simulink.Parameter object of enumerated type. This provides meaningful
names and improves the readability of the conditions. The generated
code includes preprocessorconditionalstocheckthat the variant object
condition contains valid values of the enumerated type.
3-4
Generating Preprocessor Conditional Directives
In order to ge nerate preprocessor conditional directives configure your model
as follows:
1 On the Optimization pane of the Configuration Parameters dialog box,
select Inline parameters.
2 On the Real-Time Workshop pane of the Configuration Parameter
dialog box, clear “Ignore custom storage classes”. In order to generate
preprocessor conditionals, you must use custom storage classes.
3 On the Interface pane of the Configuration Parameter dialog box,
select the
conditionals parameter. This parameter is a global setting for the parent
model. This setting enables the Generate preprocessor conditionals
parameter located in the M odel block parameters dialog box. See “Generate
preprocessor conditionals” for more information.
Use Local Settings option of the Generate preprocessor
Page 43
Generating Code Variants for Variant Models
4 Open the Model block parameters dialog box for a variant model block.
Select the Generate preprocessor conditionals parameter.
5 In the Model block parameters dialog box, clear the Override variant
conditions and use following variant parameter.
6 Build your model.
Reviewing Code Variants in the Code Generation
Report
The Code Variants Report displays a list of the variant objects in alphabetical
order and their condition. The report alsoliststhemodelblocksthathave
Variants, and the referenced models that use them. In the Contents section
of the code generation report, click the link to the Code Variants Report:
3-5
Page 44
3 Architecture Considerations
3-6
Example of Variants in the Generated Code
To open a model for generating preprocessor conditionals, ente r
rtwdemo_preprocessor.
Page 45
Generating Code Variants for Variant Models
After building the model, look at the variants in the generated code.
rtwdemo_preprocessor_types.h includes the following:
• Call to external header file,
contains the macro definition for the variant control variable,
/* Includes for objects with custom storage classes. */
#include "rtwdemo_importedmacros.h"
rtwdemo_preprocessor_macros.h,which
MODE.
• Preprocessor directives defining the variant objects, LINEAR and NONLINEAR.
The values of these macros depend on the value of the variant control
variable,
MODE. The condition expression associated with each macro,
LINEAR and NONLINEAR, determine the active variant.
/* Model Code Variants */
#ifndef LINEAR
#define LINEAR(MODE == 0)
#endif
#ifndef NONLINEAR
#define NONLINEAR(MODE == 1)
#endif
• A check to ensure that exactly one variant is active at a time:
/* Exactly one variant for '<Root>/Left Controller' should be active */
#if (LINEAR) + (NONLINEAR) != 1
#error Exactly one variant for '<Root>/Left Controller' should be active
#endif
Calls to the step and initialization functions are conditionally compiled as
shown in a portion of the step function,
To construct model reference variants step by step a nd generate preprocessor
directives in the generated code, see the demo rtwdemo_preprocessor_script.
Page 47
Creating and Using Host-Based Shared Libraries
Creating and Using Host-Based Shared Libraries
In this section...
“Overview” on page 3-9
“Generating a Shared Library Version of Your Model Code” on page 3-10
“Creating Application Code to Load and Use Your Shared Library File”
on page 3-11
“Host-Based Shared Library Limitations” on page 3-15
Overview
The Real-Time Workshop Embedded Coder product provides an ERT target,
ert_shrlib.tlc, for generating a host-based shared library from your
Simulink model. Selecting this target allows you to generate a shared library
version of your model code that is appropriate for your host platform, either
aWindows
file. This feature can be used to package your source code securely for easy
distribution and shared use. The generated
among different applications and upgradeable without having to recompile
the applications that use it.
®
dynamic link library (.dll)fileoraUNIX®shared object (.so)
.dll or .so file is shareable
Code generation for the
• Variables and signals of type
• Real-time model structure (
ert_shrlib.tlc target exports
ExportedGlobal as data
model_M)asdata
• Functions essential to executing your model code
To view a list of symbols contained in a generated shared library file, you can
• On Windows, use the Dependency Walker utility, downloadable from
http://www.dependencywalker.com
• On UNIX, use
nm -D model.so
To generate and use a host-based shared library, you
1 Generate a shared library version of your model code
3-9
Page 48
3 Architecture Considerations
Generating a Shared Library Ve rsion of Your Model
Code
This section summarizes the steps needed to generate a shared library
version of your model code.
2 Create application code to load and use your shared library file
1 To configure your model code for shared use by applications, open your
model and select the
pane of the Configuration Parameters dialog box. Click OK.
ert_shrlib.tlc target on the Real-Time Workshop
3-10
Selecting the ert_shrlib.tlc target causes the build process to generate a
shared library version of your model code into your current working folder.
The selection does not change the code that is generated for your model.
2 Build the model.
3 After the build completes, you can examine the generated code in the
model subfolder, and the
your current folder.
.dll file or .so file that has been generated into
Page 49
Creating and Using Host-Based Shared Libraries
Creating Applic
Shared Library F
To illustrate ho
access its func
rtwdemo_shrl
w application code can load an ERT shared library file and
tions and data, The MathWorks™ provides the demo model
ib
ation Code to Load and Use Your
ile
. Clicking the blue button in the demo model runs a script
that:
1 Builds a share
rtwdemo_shr
2 Compiles and links an example application, rtwdemo_shrlib_app,thatwill
d library file from the model (for example,
lib_win32.dll
on 32-bit Windows)
load and use the shared library file
3 Executes the example application
Note It is recommended that you change directory to a new or empty folder
before running the
rtwdemo_shrlib script.
The demo model uses the following example application files, which are
located in
File
rtwdem
rtwde
matlabroot/toolbox/rtw/rtwdemos/shrlib_demo.
Description
o_shrlib_app.h
mo_shrlib_app.c
Exampl
Example application that loads and uses
e application header file
the shared library file generated for the
demo model
run_rtwdemo_shrlib_app.m
Script to compile, link, and execute the
example application
You can view each of these files by clicking white buttons in the demo model
window. Additionally, running the script places the relevant source and
generated code files in your current folder. The files can be used as templates
for writing application code for your own ERT shared library files.
The following sections present key excerpts of the example application files.
3-11
Page 50
3 Architecture Considerations
Example Application Header File
The example application header file rtwdemo_shrlib_app.h contains type
declarations for the demo model’s e xternal input and output.
Example Application C Code
The example application rtwdemo_shrlib_app.c includes the following code
for dynamically loading the shared library file. Notice that, depending on
platform, the code invokes Windows or UNIX library commands.
#ifndef _APP_MAIN_HEADER_
#define _APP_MAIN_HEADER_
typedef struct {
int32_T Input;
} ExternalInputs_rtwdemo_shrlib;
typedef struct {
int32_T Output;
} ExternalOutputs_rtwdemo_shrlib;
#endif /*_APP_MAIN_HEADER_*/
3-12
#if (defined(_WIN32)||defined(_WIN64)) /* WINDOWS */
The following code excerpt shows how the C application accesses the demo
model’s exported data and functions. Notice the hooks for adding user-defined
initialization, step, and termination code.
int32_T i;
...
void (*mdl_initialize)(boolean_T);
void (*mdl_step)(void);
void (*mdl_terminate)(void);
ExternalInputs_rtwdemo_shrlib (*mdl_Uptr);
ExternalOutputs_rtwdemo_shrlib (*mdl_Yptr);
uint8_T (*sum_outptr);
...
#if (defined(LCCDLL)||defined(BORLANDCDLL))
/* Exported symbols contain leading underscores when DLL is linked with
/* insert other user defined application step function code here */
}
/* === user application terminate function === */
mdl_terminate();
/* insert other user defined application termination code here */
}
else {
printf("Cannot locate the specified reference(s) in the shared library.\n");
return(-1);
}
Page 53
Creating and Using Host-Based Shared Libraries
Example Application Script
The application script run_rtwdemo_shrlib_app.m loads and rebuilds the
demo model, and then compiles, links, and executes the demo model’s
shared library target file. You can view the script source file by opening
rtwdemo_shrlib and clicking the appropriate white button. The script
constructs platform-dependent comm an d strings for compilation, linking,
and execution that may apply to your development environment. To run the
script, click the blue button.
Host-Based Shared Librar y Limitations
The following limitations apply to using ERT host-based shared libraries:
• Code generation for the
as data:
ert_shrlib.tlc target exports only the following
- VariablesandsignalsoftypeExportedGlobal
- Real-time model structure (model_M)
• Code generation for the
only (not C++). When you select the
selection is greyed out on the Real-Time Workshop pane of the
Configuration Parameters dialog box.
• On Windows systems, the
or retain the
portability).
You can change the default behavior and retain the
the corresponding template makefile (T MF). If you do th is, be aware that
the generated
with the generated
are using Visual C++
front of all data to be imported implicitly from the shared library file.
• To reconstruct a model simulation using a generated host-based shared
library, the application author must maintain the timing between system
and shared library function calls in the original application. The timing
needstobeconsistenttoensurecorrectsimulation and integration results.
.lib file for implicit linking (explicit linking is preferred for
model.h file will need a small modification to be used together
ert_shrlib.tlc target supports the C language
ert_shrlib.tlc target, language
ert_shrlib target by default does not generate
.lib file by modifying
ert_main.c for implicit linking. For example, if you
®
, you will need to declare __declspec(dllimport) in
3-15
Page 54
3 Architecture Considerations
3-16
Page 55
Scheduling Considerations
• “Using Discrete and Continuous Time” on page 4-2
• “Optimizing Task Scheduling for Multirate Multitasking Models on RTOS
Targets” on page 4-4
4
Page 56
4 Scheduling Considerations
Using Discrete and Continuous Time
In this section...
“Generating Code for Discrete and Continuous Time Blocks” on page 4-2
“Generating Code that Supports Continuous Solvers” on page 4-2
“Generating Code that Honors a Stop Time” on page 4-3
Generating Code for Discrete and Continuous Time
Blocks
The ERT target supports code generation for discrete and continuous time
blocks. If the Support continuous time option is selected, you can u se any
such blocks in your models, without restriction.
Note that use of certain blocks is not recommended for production code
generation for embedded systems. The Simulink Block Data Type Support
table summarizes characteristics of blocks in the Simulink and Simulink
Fixed Point block libraries, including whether or not they are recommended
for use in production code generation. To view this table, e xecute the following
command and see the “Code Generation Support” column of the table that
appears:
4-2
showblockdatatypetable
Generating Code that Supports Continuous Solvers
The ERT target supports continuous solvers. In the Solver options d ialo g,
you can select any available solver in the Solver menu. (Note that the solver
Type must be
Note Custom targets must be modified to support continuous time. The
required modifications are described in “Custom Targets” in the Real-Time
Workshop documentation.
fixed-step for use with the ERT target.)
Page 57
Using Discrete and Continuo us Time
Generating Code
The ERT target su
host-based exec
following is tr
• GRT compatibl
• External mode
Interface pan
• MAT-file log
Otherwise,
Note The ER
the
ert_ma
execution
ErrorSta
target, i
includin
the executable runs indefinitely.
in.c
by calling the
tus
f you provide your own custom static
g support for checking these flags.
pports the stop time for a model. When generating
utables, the stop time value is honored when any one of the
ue:
ecallinterfaceis selected on the Interface pane
is selected in the Data exchange subpane of the
e
ging is selected on the Interface pane
T target provides both generated and static examples of
file. The ert_main.c file controls the overall model code
/StopRequested flags to terminate execution. For a custom
that Honors a Stop Time
model_step function and optionally checking the
main.c, you should consider
4-3
Page 58
4 Scheduling Considerations
Optimizing Task Scheduling for Multirate Multitasking
Models on RTOS Targets
In this section...
“Overview” on page 4-4
“Using rtmStepTask” on page 4-5
“Task Scheduling Code for Multirate Multitasking Model on Wind River
Systems VxWorks Target” on page 4-5
“Suppressing Redundant Scheduling Calls” on page 4-6
Overview
Using the rtmStepTask macro, targets that employ the task management
mechanisms of an RTOS can eliminate certain redundant scheduling calls
during the execution of tasks in a multirate, multitasking model, thereby
improving performance of the generated code.
4-4
To understand the optimization that is available for an RTOS target, consider
how the ERT target schedules tasks for bareboard targets (where no RTOS
is present). The ERT target maintains scheduling counters and event flags
for each subrate task. The scheduling counters are implemented within the
real-time model (rtM) data structure as arrays, indexed on task identifier
(
tid).
The scheduling counters are updated by the base-rate task. The counters
are, in effect, clock rate dividers that count up the sample period associated
with each subrate task. When a given subrate counter reaches a value that
indicates it has a hit, the sample period for that rate has elapsed and the
counter is reset to zero. When this occurs, the subrate task must be scheduled
for execution.
The event flags indicate whether or not a given task is scheduled for execution.
For a multirate, multitasking model, the event flags are maintained by code in
the m odel’s generated example main program (
the code maintains a task counter. When the counter reaches 0, indicating
that the task’s sample period has elapsed, the event flag for that task is set.
ert_main.c). Foreachtask,
Page 59
Optimizing Task Scheduling for Multirate Multitasking Models on RTOS Targets
On each time step, the counters and event flags are updated and the base-rate
task executes. Then, the scheduling flags are checked in
tid order, and any
task whose event flag is set is executed. This ensures that tasks are executed
in order of priority.
For bareboard targets that cannot rely on an external RTOS, the event
flags are mandatory to allow overlapping task preemption. However, an
RTOS target uses the operating system itself to manage overlapping task
preemption, making the maintenance of the event flags redundant.
Using rtmStepTask
The rtmStepTask macro is defined in model.h and its syntax is as follows:
boolean task_ready = rtmStepTask(rtm, idx);
The arguments are:
•
rtm: pointer to the real-time model structure (rtM)
idx: task identifier (tid) of the task whose scheduling counter is to be
•
tested
rtmStepTask returns TRUE if the task’s scheduling counter equals zero,
indicating that the task s hould be scheduled for execution on the current time
step. Otherwise, it returns
FALSE.
If your target supports the Generate an example main program
parameter, you can generate calls to
RTMTaskRunsThisBaseStep.
rtmStepTask using the TLC function
Task Scheduling Code for Multirate Multitasking
Model on Wind River Systems VxWorks Target
The following task scheduling code, from ertmainlib.tlc,isdesignedfor
multirate multitasking operation on a Wind River
target. The example uses the TLC function RTMTaskRunsThisBaseStep to
generate calls to the
task, and
the VxWorks
rtmStepTask is called for each task. If rtmStepTask returns TRUE,
semGive function is called, and the VxWorks RTOS schedules
rtmStepTask macro. A loop iterates over each subrate
thetasktorun.
®
Systems VxWorks
®
4-5
Page 60
4 Scheduling Considerations
%assign ifarg = RTMTaskRunsThisBaseStep("i")
for (i = 1; i < %<FcnNumST>; i++) {
if (%<ifarg>) {
semGive(taskSemList[i]);
if (semTake(taskSemList[i],NO_WAIT) != ERROR) {
logMsg("Rate for SubRate task %d is too fast.\n",i,0,0,0,0,0);
semGive(taskSemList[i]);
}
}
}
Suppressing Redundant Scheduling Calls
Redundant scheduling calls are still generated by default for backward
compatibility. To change this setting and suppress them, add the following
TLCvariabledefinitiontoyoursystemtargetfilebeforethe
"codegenentry.tlc"
%assign SuppressSetEventsForThisBaseRateFcn = 1
statement:
%include
4-6
Page 61
5
Developing Model Patterns
that GenerateSpecific C
Constructs
• “About Modeling Patterns” on page 5-2
• “Standard Methods to Prepare a Model for Code Generation” on page 5-3
• “Types, Operators, and Expressions” on page 5-8
• “Control Flow” on page 5-25
• “Functions” on page 5-64
Page 62
5 Developing Model Patterns that Generate Specific C Constructs
About Modeling Patterns
Several standard methods are available for s etting up a model to generate
specific C Constructs in y our code. For preparing your model for code
generation, some of these methods include: configuring signals and ports,
initializing states, and setting up configuration parameters for code
generation. Depending on the components of your model, some of these
methods a re optional. Methods for confi guring a model to generate specific C
constructs are organized by category, for example, the Control Flow category
includes constructs
a construct to see how you should configure blocks and parameters in your
model. Different modeling methodologies are available, such as Simulink
blocks, Stateflow
C construct.
Model examples have the following naming conventions:
if-else, switch, for,andwhile. Refer to the name of
®
charts, and Embedded MATLAB®blocks, to implement a
Model Components
Inputs
Outputs
Parameters
States
Input ports are named to reflect the signal names that they propagate.
Naming Con
u1, u2, u3,andsoon
y1, y2, y
p1, p2,
x1, x2, x3,andsoon
p3,andsoon
vention
3
,andsoon
5-2
Page 63
Standard Methods to Prepare a Model for Code Generation
Standard Methods to Prepare a Model for Code
Generation
In this section...
“Configuring a Signal” on page 5-3
“Configuring Input and Output Ports” on page 5-4
“Initializing States” on page 5-4
“Setting Up Configuration Parameters for Code Generation” on page 5-4
“Setting Up an Example Model With a Stateflow Chart” on page 5-5
“Setting Up an Example Model With an Embedded MATLAB Block” on
page 5-7
Configuring a Signal
1 Create a model in Simulink. See “Creating a Model” in the Simulink
documentation.
2 Right-click a signal line. Select Signal Properties. A Signal Properties
dialog box opens. See “Signal Properties Dialog Box” for more information.
3 Enter a signal name for the Signal name parameter.
4 On the sam e Signal Properties dialog box, select th e Real-Time Workshop
tab. Use the drop down menu for the Storage class parameter to specify a
storage class. Examples in this chapter use
Note Alternatively, on the Signal Properties dialog box, select Signal
name must resolve to Simulink signal object. Then create a signal
data object in the base workspace with the same name as the signal.
See “Creating Simulink and mpt Data Objects” on page 11-4 for more
information on creating data objects in the base workspace. (Examples use
mpt.Signal and specify the Storage class as ExportedGlobal.
Exported Global.
5-3
Page 64
5 Developing Model Patterns that Generate Specific C Constructs
Configuring Input and Output Ports
1 In your model,
Double-click an
Inport or Outport block. A Block Parameters dialog box
opens.
2 Select the Signal Attributes tab.
3 Specify the Port dimensions and Data type. Examples leave the default
value for Port dimensions as
Inherit:auto.
1 (for inherited) and Data type as
Initializing States
1 Double-click a block.
2 In the B lock Parameters dialog box, select the Main tab.
3 Specify the Initial conditions and Sample time. See “Working with
Sample Times”.
4 Select the State Attributes pane. Specify the state name. See “Block
State Storage and Interfacing Considerations”
5 You can also use the Data Object Wizard for creating data objects. A part of
this process initializes states. See “Creating Simulink Data Objects with
Data Object Wizard” on page 11-5.
5-4
Setting Up Configuration Parameters for Code
Generation
1 Open the Configuration Parameter dialog box by selecting
Standard Methods to Prepare a Model for Code Generation
3 Open the Optimization pane, and select the Inline parameters
parameter.
4 Open the Real-Time Workshop pane, and specify ert.tlc as the System
Target File.
5 Clear Generate makefile.
6 Select Generate code only.
7 Enable the HTML report generation by opening the Real-Time Workshop
>Reportpane and selecting Create code gene ra tion report, Launch
report automatically,andCode-to-model. Enabling the HTML report
generation is optional.
8 Click Apply and then OK to exit.
Setting Up an Example Model With a Stateflow Chart
Follow this general procedure to create a simple model containing a Stateflow
chart.
1 From the Stateflow > Stateflow Chart library, add a Stateflow chart
to your model .
2 Add
3 Open the Stateflow Editor by performing on teh the following:
Inport block s and Outport blocks according to the example model.
5-5
Page 66
5 Developing Model Patterns that Generate Specific C Constructs
• Double-click the Stateflow chart.
• Select Tools > Explore.
• Press Ctrl+R.
4 Select Add > Data > Input from Simulink to add the inputs to the chart.
A Data dialog box opens for each input.
5 Specify the Name (u1, u2, ...) and the Type (Inherit:same as
Simulink
click OK.
Click Ap ply and close each dialog box.
6 Select Add > Data > Output from Simulinkto add the outputs to the
chart. A Data dialog opens for each output.
7 Specify the Name (y1, y2, ...) and Type (Inherit:same as
Simulink
, unless specified differently in the example) for each input and
, unless specified differently in the example) for each output and
5-6
click OK.
8 Click Apply and close each dialog box.
9 In the Stateflow Editor, create th e Stateflow diagram specific to the
example.
10 The inputs and outputs appear on the chart in your model.
11 Connect the Inport and Outport blocks to the Stateflow Chart.
12 Configure the input and output signals; see “Configuring a Signal” on page
5-3.
Page 67
Standard Methods to Prepare a Model for Code Generation
Setting Up an Exa
mple Model With an Embedded
MATLAB Block
1 Add the number of Inport and Outport blocks according to a C construct
example included in this chapter.
2 From the Simulink User-defined Functions library drag anEmbedded
MATLAB Function block into the model.
3 Double-click the block. The Embedded MATLAB editor opens. Edit the
function to implement your application.
4 Click File > Save and close the Embedded MATLAB editor.
5 Connect the Inport a nd blocks to the Embedded MATLAB Function block.
See “Configuring a Signal” on page 5-3.
6 Save your model.
5-7
Page 68
5 Developing Model Patterns that Generate Specific C Constructs
Types, Operators, and Expressions
In this section...
“Data Declaration” on page 5-8
“Data Type Conversion” on page 5-11
“Type Qualifiers” on page 5-15
“Relational and Logical Operators” on page 5-17
“Bitwise Operations” on page 5-21
Data Declaration
C Construct
int32 p1 =
3;
Declare a Variable for a Block Parameter Using a Data Object
You can
variab
in the g
(and w
you ch
gener
code c
info
and S
Block
Constant
Gain
For Iterator
There are several methods for configuring data objects:
specify certain block parameters as a variable. If you define the
le as a data object, the variable is global. Where the variable is declared
enerated code depends on the custom storage class that you choose
hether you select Optimization parameter Inline Parameters). If
oose Inline Parameters, then the data object name is used in the
ated code. If you did not choose Inline Parameters, the generated
reates a global structure that stores all of the parameters. For more
rmation on how to create a data object, see Defining Data Representation
torage for Code Generation on page 1.
Parameter
ue
Val
lue
Va
teration Limit
I
5-8
Page 69
Types, Operators, and Expressions
• For a m odel with many parameters, use the Data Object Wizard, which
analyzes your model and finds all of the unresolved data objects and data
types. You can then create the data objects in the D ata Object Wizard. The
procedure for using the Data Object Wizard for a parameter is similar to
the procedure for a signal. For an example, see “Declare a Variable for a
Signal using a Data Object” on page 5-10.
• To add, delete, e dit, and configure data objects, use the base workspace in
the Model Explorer.
• To create and configure data objects, use the MATLAB
®
command line.
The following example demonstrates how to create a data object using the
Model Explorer. The declaration statement in the generated code is as follows:
int Kp = 3;
1 Create a model containing a Constant block and a Gain block.
2 Press Ctrl+E to open the Config u ration Parameters dialog box.
3 On the Optimization pane of the Configuration Parameter dialog box,
select Inline parameters.
4 Click Apply and OK. The Configuration Parameter dialog box closes.
5 In your model, double-click the Constant block. The Block Parameters
dialog box opens.
6 In the Value field, enter a variable name. In this example, the variable
name is
7 In your model, double-click the Gain block. The Block Parameters dialog
p1.
box opens.
8 In the Value field, enter a variable name. In this example, the variable
name is
9 Press Ctrl+H to open the Model Explorer. On the Model Hierarchy pane,
p2.
select the base workspace.
5-9
Page 70
5 Developing Model Patterns that Generate Specific C Constructs
10 To add two MPT parameter objects, in the menu bar, select Add > MPT
Parameter in the menu bar twice. On the Contents of: Base Workspace
pane, you see the parameters.
11 Double-click each mpt.Parameter object and change their names to p1
and p2.
12 Click the p1 parameter. The data object parameters are displayed in the
right pane of the Model Explorer.
13 In the Value field, enter 3 for p1.FortheData type, select int32.
Because you chose an MPT parameter, the Storage Class is already set
to
Global(Custom).
14 In the Value field, enter 5 for p2.FortheData type, select int32.
15 Press Ctrl+B to generate code.
In the
model.c file you see:
int32 p1 = 3;
int32 p2 = 5;
Note Depending on the storage class, the global variable is represented
differently in the generated code. For more information, see “Parameter
Objects”.
C Construct
int p1 = 3;
Declare a Variable for a Signal using a Data Object
1 Create a model and label the signals.
2 In the model tool bar, click Tools > Data Object Wizard to open the Data
Object Wizard. If you are not familiar with crea t in g Simul ink Data
Objects using the wizard, refer to “Data Object Wizard” .
5-10
Page 71
Types, Operators, and Expressions
3 Click Find. The list of unresolved parameters and objects populates the
Data Object Wizard. You can do mass edits for identical data objects.
4 Select the signals individually or select all signals by clicking Check All.
5 From the parameter Choose package for selected data objects
drop-down list, select the
mpt package.ClickApply Package.Whenyou
open the Model Explorer the data objects appear in the base workspace.
6 In the base workspace, click the p1 data object . The data object parameters
appear in the right pane of the M odel Explorer.
7 From the Data type drop-down list, select int16.
8 You can also specify the storage class. The data object is an mpt.Parameter
object, therefore the Storage Class is automatically set to Global (Custom).
Note The Storage class alters the data object implementation in the
generated code. For more information, see “Signal Objects”.
Data Type Conversion
C Construct
y1 = (double)u1;
Modeling Patterns
• “Modeling Pattern for Data Type Conversion — Simulink Block” on page
5-12
• “Modeling Pattern for Data Type Conversion — Stateflow Chart” on page
5-13
• “Modeling Pattern for Data Type Conversion — Embedded MATLAB
Function” on page 5-14
5-11
Page 72
5 Developing Model Patterns that Generate Specific C Constructs
Modeling Pattern for Data Type Conversion — Simulink Block
One method to create a data type conversion is to use a Data Type C onversion
block from the Simulink > Commonly Used Blocks library.
Data_Type_SL
1 From the Commonly Used Blocks library, drag a Data Type Conversion
block into your model and connect to the Inport and Outport blocks.
2 Double-cl
Parameter
3 Select the Output data type parameter as double.
4 Press Ctrl+B to build the model and generate code.
The generated code appears in
int32_
real_T
void Da
{
y1=(r
}
ick on the Data Type Conversion block to open the Block
s dialog box. and in the Block Parameters dialog box select the .
Data_Type_SL.c,asfollows:
Tu1;
y1;
ta_Type_SL_step(void)
eal_T)u1;
The Real-Time Workshop Embedded Coder type de finitio n for double is
real_T.
5-12
Page 73
Types, Operators, and Expressions
Modeling Pattern for Data Type Conversion — Stateflow Chart
Stateflow Chart Type Conversion
Procedure.
1 Follow the
on page 5-5 .
steps for “Setting Up an Example Model With a Stateflow Chart”
This example contains one Inport block and one Outport block.
2 Name the example model Data_Type_SF.
3 Double-click the Inport block and select the Signal Attributes tab. Specify
the Data Type as
4 Double-
Specif
click the Outport block and select the Signal Attributes tab.
ytheData Type as
int32 from the drop down menu.
Inherit:auto from the drop down menu.
5 In the Stateflow Editor,specifytheData Type for y1 as Boolean
6 Press Ctrl+B to build the model and generate code.
Results. The generated code appears in
2_T u1;
int3
_T y1;
real
Data_Type_SF_step(void)
void
{
(real_T)u1;
y1 =
}
Data_Type_SF.c,asfollows:
5-13
Page 74
5 Developing Model Patterns that Generate Specific C Constructs
Modeling Pattern for Data Type Conversion — Embedded
MATLAB Function
MATLAB Block” on page 5-7 . This example model contains one Inport
block and one Outport block.
2 Name the model Data_Type_EML.
3 In the Embedded MATLAB editor enter the function, as follows:
function y1 = typeconv(u1)
y1 = double(u1);
end
4 Press Ctrl+B to build the model and generate code.
5-14
Results. The generated code appears in
a
float and real_T is a double. Type conversion occurs across assignments.
real32_T u1;
real_T y1;
void Data_Type_EML_step(void)
{
y1 = u1;
}
Data_Type_EML.c,wherereal32_T is
Other Type Conversions in Modeling
Type conversions can also occur on the output of blocks where the output
variable is specified as a different data type. For example, in the Gain b lock,
you can select the Inherit via internal rule parameter to control the
output signal data type. Another example of type conversion can occur at
the boundary of a Stateflow chart. You can specify the output variable as
a different data type.
Page 75
Types, Operators, and Expressions
Type Qualifiers
Modeling Patterns for Type Qualifiers
• “Using a Tunable Parameter in the Base Workspace” on page 5-15
• “Using a Data Object of the
Const Custom Storage Class” on page 5-16
Using a Tunable Parameter in the Base Workspace
A tunable parameter is a block parameter whose value can be changed at
runtime. The storage class property of a parameter specifies how Real-Time
Workshop declares the parameter in the generated code.
Typ e _Q ual
Procedure.
1 Create a model containing a Constant block and an Outport block.
2 Double-click the Constant block. In the Constant value field, enter the
parameter name
3 In the
Value
base workspace, create a MATLAB variable for
as
9.8 and its Data type as double.
p1 .
p1 and specify its
4 Press Ctrl+E to open the Configuration Parameters dialog box and select
the Optimization pane.
5 Select the Inline parameters parameter, which activates the Configure
button.
ck the Configure button to open the Model Parameter Configuration
6 Cli
alog box.
di
5-15
Page 76
5 Developing Model Patterns that Generate Specific C Constructs
7 To declare a tunable parameter, from the Source list, select the variable
p1.
8 Click the Add to table button to add p1 to the Global (tunable)
parameters section.
9 Click the Storage Class and select Exported Global.
10 Click the Storage Type Qualifier arrow and select const.
11 Click Apply to save all of the changes.
12 Press Ctrl+B to build the model and generate code.
Results. The generated code appears in
/* Exported block parameters */
const real_T p1 = 9.8;/* Variable: p1
* Referenced by: '<Root>/Constant'
*/
Type_Qual.c as follows:
Using a Data Object of the Const Custom Storage Class
Onewaytocreateatypequalifierinthegeneratedcodeistocreateadata
object and specify the appropriate custom storage class. Use the previous
model,
Procedure.
1 Press Ctrl+H to open the Model Explorer. On the Model Hierarchy pane,
2 In the menu bar, select Add > MPT Parameter to add an MPT parameter
3 Double-click the mpt.Parameter object and change the Name to p1.
4 Click the p1 parameter which displays the data object parameters on the
Type_Qual, for this example. Specify p1 differently as follows:
select the base workspace.
object. The parameter is displayed in the Contents of: Base Workspace
pane.
right pane of the Model Explorer.
5-16
Page 77
Types, Operators, and Expressions
5 In the Value field, enter 9.8 for p1.SpecifytheData type as auto for
64–bit double.
6 You can use the different type qualifiers by selecting a custom storage
class from the Storage class list. For this example, select
(custom)
7 In the Configuration Parameters dialog box, on the Optimization pane,
.
ConstVolatile
select the Inline parameters.
8 Press Ctrl+B to build the model and generate code.
Results. The generated code produces the type qualifier in
const volatile real_T p1 = 9.8;
Type_Qual.c:
Relational and Logical Operators
Modeling Patterns for Relational and Logical Operators
• “Modeling Pattern for Relational or Logical Operators — Simulink Blocks”
on page 5-18
• “Modeling Pattern for Relational and Logical Operators —Stateflow Chart”
on page 5-19
• “Modeling Pattern for Relational and Logical Operators — Embedded
MATLAB” on page 5-20
5-17
Page 78
5 Developing Model Patterns that Generate Specific C Constructs
Modeling Pattern for Relational or Logical Operators —
Simulink Blocks
Logical_SL
Procedure.
1 From the Logic and Bit Operations library, drag a Logical Operator
block into your model.
5-18
2 Double-c
field to
3 Nametheblocks,asshowninthemodelLogical_SL.
4 Connect the blocks and name the signals, as shown in the model
Logical_SL.
5 Press C
Note Y
acing the Logical O perator block with a Relational Operator b lock.
repl
Resu
ical_SL_step
Log
/* Exported block signals */
lick the block to configure the logical operation. Set the Operator
OR.
trl+B to build the model and generate code.
ou can use the above procedure to implement relational operators by
Modeling Pattern for Relational and Logical Operators
—Stateflow Chart
Logical SF/Logical Operator Stateflow®Chart
Procedure.
1 Follow the steps for“Setting Up an Example Model With a Stateflow
Chart” on page 5-5 . This example model contains two Inport blocks and
one Outport block.
2 Name the example model Logical_SF.
3 In th
4 In the Stateflow Editor, create the Stateflow diagram as shown. The
e Stateflow Editor,specifytheData Type for
y1 as Boolean.
relational or logical o peration actions are on the transition from one junction
to another. Relational statements specify conditions to conditionally allow
a trans it ion . In that case, the statement would be within square brackets.
5-19
Page 80
5 Developing Model Patterns that Generate Specific C Constructs
5 Press Ctrl+B to build the model and generate code.
Results. Code implementing the logical operator OR is in the
/* Embedded MATLAB Function 'Embedded MATLAB Function': '<S1>:1' */
/* '<S1>:1:4' */
switch (U.u1) {
case 2:
/* '<S1>:1:6' */
Y.y1 = U.u2;
break;
case 3:
/* '<S1>:1:8' */
Y.y1 = U.u3;
break;
default:
/* '<S1>:1:10' */
Y.y1 = U.u4;
break;
}
}
Control Flow
Converting If-Elseif-Else to Switch statement
If an Embedded MATLAB Function block or a Stateflow chart contains uses
if-elseif-else decision logic, you can convert it to a switch statement by
using a configuration parameter. In the Configuration Parameters dialog
box, on the Real-Time Workshop > Code Style pane, select the “Convert
if-elseif-else patterns to switch-case statements” parameter. For more
information, see “Converting If-Elseif-Else Code to Switch-Case Statements”
in the Sim u l ink documentation. For more information on this conversion
using a Stateflow chart, see “Converting If-Elseif-Else Code to Switch-Case
Statements” and “Example of Converting Code for If-Elseif-Else Decision
Logic to Switch-Case Statements” in the Stateflow documentation.
5-37
Page 98
5 Developing Model Patterns that Generate Specific C Constructs
For loop
C Construct
y1 = 0;
for(inx = 0; inx <10; inx++)
{
y1 = u1[inx] + y1;
}
Modeling Pa
• “Modeling P
• “Modeling
• “Modeling
Pattern for For Loop: Stateflow Chart” on page 5-42
Pattern for For Loop: Embedded MATLAB block” on page 5-45
tterns:
attern for For Loop: For-Iterator Subsystem block” on page 5-39
5-38
Page 99
Control Flow
Modeling Pattern for For Loop: For-Iterator Subsystem block
One method for creating a for loop is to use a For Iterator Subsystem block
from the Simulink > Ports and Subsystems library.
Model For_Loop_SL
For Iterator Subsystem
Procedure.
1 Drag a For Iterator Subsystem block from the Simulink > Ports and
Subsystems library into your model.
2 Connect the data inputs and outputs to the For Iterator Subsystem block.
3 Open the Inport block.
4 In the Block Parameters dialog box, select the Signal Attributes pane and
set the Port dimensions parameter to 10 .
5 Double-click the For Iterator Subsystem block to open the subsystem.
5-39
Page 100
5 Developing Model Patterns that Generate Specific C Constructs
6 Drag an Index Vector block from the Signal-Routing library into the
subsystem.
7 Open the For Iterator block. In the Block Parameters dialog box set the
Index-mode parameter to
to 10.
8 Connect the controlling input to the topmost input port of the Index Vector
block, and the other input to the s econd port.
9 Drag an Add block from the Math Operations library into the subsystem.
10 Drag a Unit Delay block from Commonly Used Blocks library into the
subsystem.
11 Double-click the Unit Delay block and set the Initial Conditions
parameter to
12 Connect the blocks as shown in the model diagram.
13 Save the subsystem and the model.
0. This parameter initializes the state to zero.
Zero-based and the Iteration limit parameter
5-40
14 Enter Ctrl+B to build the model and generate code.
Results. Real-Time Workshop software generates the following
For_Loop_SL_step function in the file For_Loop_SL.c:
/* External inputs (root inport signals with auto storage) */
ExternalInputs U;
/* External outputs (root outports fed by signals with auto storage) */
ExternalOutputs Y;
/* Model step function */
void For_Loop_SL_step(void)
{
int32_T s1_iter;
int32_T rtb_y1;
/* Outputs for iterator SubSystem: '<Root>/For Iterator Subsystem' incorporates:
* ForIterator: '<S1>/For Iterator'
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.