Embedded Coder Getting Started Guide
Embedded Coder Getting Started Guide
R2016a
www.mathworks.com
www.mathworks.com/sales_and_services
User community:
www.mathworks.com/matlabcentral
Technical support:
www.mathworks.com/support/contact_us
Phone:
508-647-7000
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
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
October 2014
March 2015
September 2015
October 2015
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
March 2016
Online only
Contents
Product Overview
Embedded Coder Product Description . . . . . . . . . . . . . . . . . .
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
1-2
1-3
1-4
1-5
1-6
1-8
1-8
1-10
1-11
1-12
1-29
1-29
1-29
1-31
MATLAB Tutorials
Generate C Code from MATLAB Code . . . . . . . . . . . . . . . . . .
About MATLAB Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting Started Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . .
Embedded Coder Capabilities for Code Generation from
MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2
2-2
2-2
2-3
vii
viii
Contents
2-9
2-9
2-10
2-10
2-10
2-11
2-11
2-12
2-12
2-12
2-13
2-13
2-14
2-14
2-15
2-15
2-16
2-16
2-17
2-17
2-17
3-2
3-2
3-2
3-6
3-6
3-7
3-8
3-11
3-11
3-13
3-19
3-22
3-22
3-23
3-25
3-27
3-27
3-30
3-31
3-33
3-33
3-34
3-38
3-39
3-41
3-41
3-42
3-44
3-44
3-45
3-48
3-46
A-2
A-2
A-3
A-4
A-4
A-4
A-5
A-6
A-6
ix
Contents
A-7
1
Product Overview
Embedded Coder Product Description on page 1-2
Code Generation Technology on page 1-3
Code Generation Workflows with Embedded Coder on page 1-4
Validation and Verification for System Development on page 1-8
Target Environments and Applications on page 1-29
Product Overview
Key Features
Optimization and code configuration options that extend MATLAB Coder and
Simulink Coder
Storage class, type, and alias definition using Simulink data dictionary capabilities
Processor-specific code optimization
Multirate, multitask, and multicore code execution with or without an RTOS
Code verification, including SIL and PIL testing, custom comments, and code reports
with tracing of models to and from code and requirements
Integration with Texas Instruments Code Composer Studio, Analog Devices
VisualDSP++, and other third-party embedded development environments
Standards support, including ASAP2, AUTOSAR, DO-178, IEC 61508, ISO 26262,
and MISRA-C
1-2
1-3
Product Overview
1-4
Although not shown in this figure, other products that support code generation, such as
Stateflow software, are available.
To develop algorithms with MATLAB code for code generation, see Code Generation
from MATLAB Code on page 1-5.
To implement algorithms as Simulink blocks and Stateflow charts in a Simulink model,
and generate C or C++ code, see Code Generation from Simulink Models on page
1-6.
Product Overview
MATLAB
MATLAB Coder
Embedded Coder
MATLAB Coder supports a subset of core MATLAB language features, including
program control constructs, functions, and matrix operations. To generate C or C+
+ code, you can use MATLAB Coder projects or enter the function codegen in the
MATLAB Command Window. Embedded Coder provides additional options and advanced
optimizations for fine-grain control of the generated codes functions, files, and data.
For more information about these options and optimizations , see Embedded Coder
Capabilities for Code Generation from MATLAB Code on page 2-3.
For more information about generating code from MATLAB code, see MATLAB Code for
Code Generation Workflow Overview in the MATLAB Coder documentation.
To get started generating code from MATLAB code using Embedded Coder, see
Generate C Code from MATLAB Code on page 2-2.
To get started generating code from Simulink models using Embedded Coder, see
Generate C Code from Simulink Models on page 3-2.
To learn how to model and generate code for commonly used C constructs using Simulink
blocks, Stateflow charts, and MATLAB functions, see Modeling Patterns for C Code.
1-7
Product Overview
1-8
Hardware-in-the-loop
(HIL) testing
Rapid simulation
System Integration
and Calibration
System Specification
Processor-in-the-loop
(PIL) testing
Software Integration
Software-in-the-loop
(SIL) testing
Coding
Production code generation
Model encryption (export)
Depending on your application and its role in the process, you might focus on one or more
of the steps called out in the V-model or repeat steps at several stages of the V-model.
Code generation technology and related products provide tooling that you can apply to
the V-model for system development. For more information about how you can apply
MathWorks code generation technology and related products provide tooling to the Vmodel process, see:
Types of Simulation and Prototyping in the V-Model on page 1-10
Types of In-the-Loop Testing in the V-Model on page 1-11
Mapping of Code Generation Goals to the V-Model on page 1-12
1-9
Product Overview
Standalone Rapid
Simulations
Rapid Prototyping
On-Target Rapid
Prototyping
Purpose
Refine, test,
and validate
functionality of
concept model in
nonreal time
Execution
hardware
Host computer
Host computer
PC or nontarget
hardware
Embedded
computing unit
(ECU) or nearproduction hardware
Code
efficiency
and I/O
latency
Not applicable
Not applicable
Ease of use
and cost
Can simulate
component
(algorithm or
controller) and
environment (or
plant)
Easy to simulate
models of hybrid
dynamic systems
that include
components and
environment models
Might require
custom real-time
simulators and
hardware
Normal mode
simulation in
Simulink enables
you to access,
display, and
tune data during
verification
1-10
Standalone
executable runs
outside of MATLAB
and Simulink
environments
Can repeat
simulations with
varying data sets,
interactively or
programmatically
Might be done
with inexpensive
off-the-shelf PC
hardware and I/O
cards
Host-Based
Simulation
Can accelerate
Simulink
simulations with
Accelerated and
Rapid Accelerated
modes
Standalone Rapid
Rapid Prototyping
Simulations
with scripts, without
rebuilding the model
On-Target Rapid
Prototyping
Can connect to
Simulink to monitor
signals and tune
parameters
PIL Testing on
PIL Testing on
Embedded Hardware Instruction Set
Simulator
HIL Testing
Purpose
Verify component
source code
Verify component
object code
Verify component
object code
Verify system
functionality
Fidelity and
accuracy
Two options:
Same source
code as target,
but might have
numerical
differences
Same executable
code
Changes source
code to emulate
word sizes, but is
bit accurate for
fixed-point math
Cycle accurate
Might not be cycle
because code runs on accurate
Cycle accurate
hardware
Use real and
emulated system I/O
Execution
platforms
Host
Target
Host
Ease of use
and cost
Desktop
convenience
Target
Executes on test
bench or in lab
1-11
Product Overview
SIL Testing
PIL Testing on
PIL Testing on
Embedded Hardware Instruction Set
Simulator
Executes only in
Uses hardware
Executes only on
Simulink
process board and
host computer
cables
with Simulink
Reduced hardware
and integrated
cost
development
environment (IDE)
HIL Testing
Uses hardware
processor, embedded
computer unit
(ECU), I/O devices,
and cables
Reduced hardware
cost
Real-time
capability
Examples
Capture requirements in
a document, spreadsheet,
data base, or requirements
management tool
1-12
Goals
Examples
Associate requirements
documents with objects in
concept models
Requirements Traceability
Simulink Verification and
Validation
slvnvdemo_fuelsys_docreq
Generate a report on
Bidirectional tracing in Microsoft
requirements associated with a Word, Microsoft Excel, HTML, and
model
IBM Rational DOORS
Include requirements links in
generated code
rtwdemo_requirements
rtwdemo_hyperlinks
1-13
Product Overview
Goals
Simulate models for hybrid
dynamic systems that
include components and an
environment or plant that
requires variable-step solvers
and zero-crossing detection
Examples
Simulink Test
1-14
Examples
Subsystems
rtwdemo_atomic
rtwdemo_ssreuse
rtwdemo_filepart
rtwdemo_exporting_functions
Component-Based Modeling
Simulink Coder
rtwdemo_mdlreftop
Component-Based Modeling
Embedded Coder
1-15
Product Overview
Goals
Examples
Customize Generated
Identifier Naming Rules
Embedded Coder
Create a zip file that contains
generated code files, static
files, and dependent data to
build generated code in an
environment other than your
host computer
rtwdemo_buildinfo
rtwdemo_shrlib
Deployment Simulink
Coder
rtwdemo_profile
1-16
Deployment Embedded
Coder
Goals
Evaluate system performance
before laying out hardware,
coding production software, or
committing to a fixed design
Examples
Test hardware
Generate code for rapid
prototyping
Simulink Real-Time
Examples
Data Representation
Simulink Coder
Data Representation
Embedded Coder
rtwdemo_counter
rtwdemo_async
Sample Workflows in the
Embedded Coder documentation
Product Overview
Goals
Examples
Target Environment
Configuration Simulink
Coder
rtwdemo_targetsettings
Target Environment
Configuration Embedded
Coder
Design model variants
rtwdemo_fixpt1
Air-Fuel Ratio Control System
with Fixed-Point Data
fxpdemo_fpa
fxpdemo_feedback
rtwdemo_udt
1-18
rtwdemo_symbols
Goals
Examples
rtwdemo_cscpredef
rtwdemo_advsc
rtwdemo_memsec
rtwdemo_advisor1
Customization and
Automation
slvnvdemo_mdladv
rtwdemo_iec61508
sldvdemo_cruise_control
1-19
Product Overview
Goals
Examples
sldvdemo_cruise_control_verification
rtwdemo_codegenrpt
Deployment Simulink
Coder
Deployment Embedded
Coder
slxml_sfcar
Model Comparison
Simulink Report Generator
rtwdemos, select Embedded
IDEs or Embedded Targets
1-20
Goals
Examples
Examples
Performance Simulink
Coder
rtwdemos, select
Optimizations
Code Replacement
Simulink Coder
Performance Embedded
Coder
Code Replacement
Embedded Coder
Code Replacement
Customization Embedded
Coder
Control the format and style of Control Code Style
generated code
Embedded Coder
rtwdemo_parentheses
1-21
Product Overview
Goals
Examples
rtwdemo_buildinfo
Review of Requirements
rtwdemo_requirements
Links Simulink Verification
and Validation
rtwdemo_comments
rtwdemo_hyperlinks
1-22
Goals
Examples
Software-in-the-Loop (SIL)
Simulation Embedded
Coder
a.
MISRA and MISRA C are registered trademarks of MISRA Ltd., held on behalf of the MISRA Consortium.
Examples
rtwdemo_capi
rtwdemo_asap2
1-23
Product Overview
Goals
software can compile, build,
and invoke the generated code
Examples
rtwdemo_exporting_functions
Code Replacement
Simulink Coder
Code Replacement
Embedded Coder
Code Replacement
Customization Embedded
Coder
rtwdemo_buildinfo
rtwdemo_buildinfo
Code Replacement
Simulink Coder
1-24
Code Replacement
Embedded Coder
Goals
Examples
rtwdemo_buildinfo
Timers
rtwdemo_capi
rtwdemo_asap2
Event-Based Scheduling
Verify object code files in a
target environment
Software-in-the-Loop (SIL)
Simulation Embedded
Coder
Processor-in-the-Loop (PIL)
Simulation Embedded
Coder
1-25
Product Overview
Goals
Examples
Processor-in-the-Loop (PIL)
Simulation
See the list of supported
hardware for the Embedded
Coder product on the
MathWorks Web site, and then
find an example for the related
product of interest
1-26
Examples
Simulink Real-Time
rtwdemo_capi
rtwdemo_asap2
1-27
Product Overview
Goals
Examples
rtwdemo_capi
1-28
Description
Host computer
The same computer that runs MATLAB and Simulink. Typically, a host
computer is a PC or UNIXa environment that uses a non-real-time operating
system, such as Microsoft Windows or Linuxb. Non-real-time (general
purpose) operating systems are nondeterministic. For example, those
operating systems might suspend code execution to run an operating system
service and then, after providing the service, continue code execution.
1-29
Product Overview
Target Environment
Description
Therefore, the executable for your generated code might run faster or slower
than the sample rates that you specified in your model.
Real-time
simulator
Embedded
microprocessor
A computer that you eventually disconnect from a host computer and run as
a standalone computer as part of an electronics-based product. Embedded
microprocessors range in price and performance, from high-end digital signal
processors (DSPs) to process communication signals to inexpensive 8-bit
fixed-point microcontrollers in mass production (for example, electronic parts
produced in the millions of units). Embedded microprocessors can:
Use a full-featured RTOS
Be driven by basic interrupts
Use rate monotonic scheduling provided with code generation
a.
b.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Linux is a registered trademark of Linus Torvalds.
controller) portion of a model from the environment (or plant). Using Simulink to model
an entire system (plant and controller) is often referred to as closed-loop simulation and
can provide many benefits, such as early verification of a component.
The following figure shows example target environments for code generated for a model.
System model
Code
generation
Code
generation
Environment model
Code
generation
Algorithm model
Host
executable
Embedded
microprocessor
Real-time
simulator
Host computer(s)
Description
Host Computer
Acceleration
Product Overview
Application
Description
Rapid Simulation
Model Protection
Real-Time Simulator
Real-Time Rapid Prototyping
1-32
Application
Description
Embedded Microprocessor
Code Generation
1-33
2
MATLAB Tutorials
Generate C Code from MATLAB Code on page 2-2
Controlling C Code Style on page 2-9
Tracing Between Generated C Code and MATLAB Code on page 2-14
MATLAB Tutorials
Project Setting
Support only
purely-integer
numbers
PurelyIntegerCode
Speed
Control generation
of floating-point data
and operations
N/A
Code Appearance
2-3
MATLAB Tutorials
Goal
Project Setting
Comment Style
CommentStyle
Specify Comment
Style for C/C++ Code
Generate traceable
MATLAB function
code that includes the help text
MATLAB function
help text in the
function banner
MATLABFcnDesc
Tracing Between
Generated C Code and
MATLAB Code on
page 2-14
Convert if-elseif-else
patterns to switchcase statements
ConvertIfToSwitch
Controlling C Code
Style on page 2-9
N/A
Parentheses
ParenthesesLevel
N/A
Specify whether to
replace multiplications
by powers of two with
signed left bitwise
shifts in the generated
code
EnableSignedLeftShifts
Control Signed Left
Shifts in Generated
Code
Specify whether to
allow signed right
bitwise shifts in the
generated code
2-4
Goal
Project Setting
IndentStyle
IndentSize
Customize generated
global variable
identifiers
Global variables
CustomSymbolStrGlobalVar
Customize Generated
Identifiers
Customize generated
global type identifiers
Global types
CustomSymbolStrType
Customize Generated
Identifiers
Customize generated
field names in global
type identifiers
Customize generated
local functions
identifiers
Local functions
CustomSymbolStrFcn
Customize Generated
Identifiers
Customize generated
identifiers for local
temporary variables
Local temporary
variables
CustomSymbolStrTmpVar
Customize Generated
Identifiers
CustomSymbolStrEMXArray
Customize Generated
Identifiers
Customize generated
identifiers for EMX
Array (Embeddable
mxArrays) utility
functions
CustomSymbolStrEMXArrayFcn
Customize Generated
Identifiers
Customize function
interface in the
generated code
N/A
2-5
MATLAB Tutorials
Goal
Project Setting
N/A
CodeTemplate
Generate Custom
File and Function
Banners for C/C++
Code
Code Generation
Template Files for
MATLAB
Control declarations
N/A
and definitions of
global variables in the
generated code
N/A
Debugging
Generate a static
code metrics report
including generated
file information,
number of lines, and
memory usage
Generate a code
Code replacements
replacement report
that summarizes the
replacements used
from the selected code
replacement library
2-6
GenerateCodeReplacementReport
Replace Code
Generated from
MATLAB Code
Review and Test
Code Replacements
Goal
Project Setting
Highlight Potential
Data Type Issues in a
Report
Replace functions
Code replacement
and operators in the
library
generated code to meet
application-specific
code requirements
CodeReplacementLibrary
N/A
Code Replacement
Customization
VerificationMode
Code Verification
Through Softwarein-the-Loop and
Processor-in-the-Loop
Execution
Custom Code
N/A
Verification
Verify generated code N/A
using software-in-theloop and processor-inthe-loop execution
Debug code during
software-in-the-loop
execution
Profile execution
times during software
-in-the-loop and
processor-in-the-loop
execution
Execution Time
Profiling
CodeExecutionProfiling
2-7
MATLAB Tutorials
Goal
Project Setting
2-8
MATLAB Tutorials
Name
Description
Function code
test_code_style.m
2-10
On the Select Source Files page, type or select the name of the entry-point
function test_code_style.m.
Click Next to go to the Define Input Types step. The app analyzes the function for
coding issues and code generation readiness. If the app identifies issues, it opens the
Review Code Generation Readiness page where you can review and fix issues.
In this example, because the app does not detect issues, it opens the Define Input
Types page.
To open the Check for Run-Time Issues dialog box, click the Check for Issues
arrow
In the Check for Run-Time Issues dialog box, enter code that calls
test_code_style with an example input. For this example, enter
test_code_style(int16(4)).
2-11
MATLAB Tutorials
On the Debugging tab, verify that Always create a code generation report is
selected, and then click Close.
Generate C Code
Click Generate.
When the code generation is complete, MATLAB Coder generates a C static library,
test_code_style.lib, and C code in the /codegen/lib/test_code_style
subfolder. Because you selected report generation, MATLAB Coder provides a link to the
report.
2-12
case 1:
y = 1.0;
break;
case 2:
y = 2.0;
break;
case 3:
y = 3.0;
break;
default:
y = 4.0;
break;
}
Learn More
To
See
2-13
MATLAB Tutorials
Name
Description
Function code
polar2cartesian.m
To run the tutorial, copy this file to a local folder. For instructions, see Copying Files
Locally on page 2-15.
2-14
Set your MATLAB current folder to the work folder that contains the file for this
tutorial. At the MATLAB command line, enter:
cd work
where work is the full path of the work folder containing your files.
Contents of polar2cartesian.m
function [x y] = polar2cartesian(r,theta)
%#codegen
% Convert polar to Cartesian
x = r * cos(theta);
y = r * sin(theta);
Enable the MATLBFcnDesc option to include the function help text in the function
banner.
cfg.MATLABFcnDesc = true;
2-15
MATLAB Tutorials
Click the View report link to open the code generation report.
2-16
Learn More
To...
See...
Code Traceability
Traceability Limitations
2-17
3
Simulink Code Generation Tutorials
Generate C Code from Simulink Models on page 3-2
Configure a Model for Code Generation on page 3-6
Generate and Analyze C Code on page 3-11
Customize Code Appearance on page 3-22
Customize Function Interface and File Packaging on page 3-27
Define Data in the Generated Code on page 3-33
Deploy and Verify Executable Program on page 3-41
Embedded Coder Documentation on page 3-48
Prerequisites
To complete these tutorials, you must install the following products:
MATLAB
MATLAB Coder
Simulink
Simulink Coder
Embedded Coder
be traceable back to model requirements. You can use reviews, analysis, simulations,
and requirements-based tests to prove that your original requirements are met by
your design and that the design does not contain unintended functionality. Performing
verification and validation activities at each step of the process can reduce expensive
errors during production.
The Embedded Coder tutorials use the rtwdemo_roll model, which has been verified for
simulation. To open the model, in the Command Window, type:
rtwdemo_roll
The rtwdemo_roll model implements a basic roll axis autopilot algorithm, which
controls the aileron position of an aircraft.
3-3
There are two operating modes: roll attitude hold and heading hold. The mode
logic for these modes is external to this model. The model architecture uses atomic
subsystems to represent the roll angle reference (RollAngleReference), heading hold
mode (HeadingMode), and basic roll attitude (BasicRollMode) functions as atomic
subsystems. The roll attitude control function is a PID controller that uses roll attitude
and roll rate feedback to produce an aileron command. The input to the controller is
either a basic roll angle reference or a roll command to track the desired heading. The
controller operates at 40 Hz.
Two additional models are provided for the Embedded Coder tutorials:
3-4
3-5
To open the Configuration Parameters dialog box, on the Simulink Editor toolbar,
click the Model Configuration Parameters icon.
In the Configuration Parameters dialog box, in the left navigation pane, select the
Solver pane.
To generate code, the model must use a fixed-step solver, which maintains a constant
(fixed) step size. In the generated code, the Solver parameter applies a fixed-step
integration technique for computing the state derivative of the model. The Fixed-step
3-6
size parameter sets the base rate, which must be the lowest common multiple of all rates
in the system. For roll, the following solver settings are selected.
In the Configuration Parameters dialog box, select the Code Generation pane.
To open the System Target File Browser dialog box, click the System target file
parameter Browse button. The System Target File Browser dialog box includes
a list of available targets. This example uses the system target file ert.tlc
Embedded Coder, which is already set.
3-7
3-8
In the Configuration Parameters dialog box, select the Code Generation pane.
In the Select Objectives dialog box, the following objectives are in the Selected
objectives prioritized list in the following order: Execution efficiency,
Traceability, Safety precaution, and RAM efficiency.
Click OK. In the Configuration Parameters dialog box, the selected objectives are
shown in the Prioritized objectives list.
In the Configuration Parameters dialog box, on the Code Generation pane, click
Check Model.
3-9
In the left pane, click Check model configuration settings against code
generation objectives.
In the right pane, review the recommendations for the configuration parameters in
the table.
To change the configuration parameters that caused the warnings to the softwarerecommended settings, click Modify Parameters. The Result table displays the
parameters and changed values. Clicking a parameter name displays Configuration
Parameters dialog box pane where the parameter exists.
In the left pane, click the next warning for Identify blocks that generate
expensive fixed-point and saturation code.
In the right pane, find the warning, Identify Discrete Integrator blocks for
questionable fixed-point operations. Under the warning, click the link to the
Integrator block.
In the Simulink Editor, the Integrator block is highlighted in blue.
In the Block Parameter dialog box, set the Initial condition setting to State
(most efficient).
Generate Code
Before generating code, you can specify that the code generation process generates an
HTML report that includes the generated code and information about the model. This
information helps you to evaluate the generated code.
1
In the left navigation pane, select the Code Generation > Report pane.
Observe the selected parameters that create a code generation report and include
traceability between the code to the model.
Create code generation report
Open report automatically
Code-to-model
Model-to-code, which enables the Traceability Report Contents parameters.
To include static code metrics in the code generation report, confirm that Static code
metrics is selected.
3-11
On the Code Generation pane, select the Generate code only check box.
Click Apply.
After the code generation process is complete, the HTML code generation report opens.
3-12
Note: If you close the code generation report, you can reopen the report from the
Simulink Editor by selecting the menu option: Code > C/C++ Code > Code Generation
Report > Open Model Report.
The Code Reuse Exceptions section provides information on subsystems configured for
reuse, but code reuse does not occur. For this model, there are no reuse exceptions.
3-14
For roll, the Inports and Outports sections include block names that you can click to
navigate to the corresponding block in the model. The other columns in the table include
the name for the block, the data type, and dimension as it is represented in the generated
code.
3-15
Traceability Report
To map model objects to and from the generated code, open the traceability report. The
Eliminated / Virtual Blocks table lists objects that are virtual or eliminated from the
generated code due to an optimization.
3-16
3-17
3-19
element in the model. For this example, roll is set up to include traceability. To enable
traceability and generate hyperlinks the following parameters must be selected:
On the Code Generation > Report pane:
Code-to-model
Model-to-code
On the Code Generation > Comments pane:
Include comments
Simulink block / Stateflow object comments
Trace from Model to Code
To trace from roll to the code generation report, in the Simulink Editor, right-click the
HeadingMode subsystem. From the menu list, select C/C++ code > Navigate to C/C++
code. In the code generation report, the source code for HeadingMode is highlighted.
After reviewing the reports and analyzing the generated code, you can change the
appearance of the generated code according to defined style standards. To change the
generation of comments, identifiers, and code style, see the next example, Customize
Code Appearance on page 3-22.
3-21
Comments
To customize the appearance of comments in the generated code for model roll, open
the Configuration Parameters dialog box and select the Code Generation > Comments
pane.
In the model roll, Include comments is selected to include comments in the generated
code and enable the other comment parameters. If you configured your model for
3-22
Identifiers
To customize the appearance of identifiers in the generated code, in the Configuration
Parameters dialog box, select the Code Generation > Symbols pane. The Autogenerated identifier naming rules group of parameters allows you to include a string
of predefined tokens to customize the generated identifier names. In the model roll, the
tokens specified are the default values.
3-23
For example, in the roll model, the Local block output variables is specified with an
rtb prefix.
1
If the code generation report is not open, generate code for the roll model.
In the HTML code generation report, in the left navigation pane, select roll.c.
At the top of the window, in the Find box, type rtb and press Enter.
Variables beginning with rtb are highlighted in the report.
To navigate between instances, use the up and down arrows in the code generation
report.
Code Style
To customize the appearance of the generated code, in the Configuration Parameters
dialog box, click the Code Generation > Code Style pane.
3-25
3-26
Model Interface
You can configure the interface of the code for the model in the Configuration Parameters
dialog box, on the Code Generation > Interface pane. By default, the models entry
points are implemented as void/void functions. Model roll is set to generate nonreusable
code with a minimal function interface.
When configuring the model interface, you can choose whether to produce reusable
or nonreusable code. Reusable code consists of reentrant functions that can be called
with different data sets. In general, nonreusable code executes more efficiently in an
embedded system because nonreentrant functions can avoid pointer dereference.
For this example, roll is configured to generate a nonreusable function interface. Verify
that Code interface packaging is set to Nonreusable function.
For roll, the interface settings direct the code generator to create two entry point
functions to initialize and step through algorithm code.
3-27
Configuration Parameter
Description
Remove the error status field in the realtime model data structure
All Parameters > Single output/update Produce a single entry point function to
step the model
function is selected
All Parameters > Terminate function
required is cleared
All Parameters > Combine signal/state Produce a single data structure for the
models global data
structures is selected
The software generates this code based on the following assumptions:
The solver setting indicates that the step function executes the code at 40 Hz.
The initialize function is called once prior to executing the step function.
Configure Model Initialize and Step Functions
You can specify the names of the model initialize and step function, and the function
prototype of the model step function.
3-28
To open the Model Interface dialog box, on the Interface pane, click Configure
Model Functions.
Click Get Default Configuration. The Model Interface dialog box expands to
display the Configure model initialize and step functions parameters.
3-29
In the Step function arguments table, verify that the order of the first two
arguments is Phi and then Psi. You can use the Up and Down buttons to reorder
the arguments.
Subsystem Interface
You can configure how the software implements atomic subsystems in the generated
code. In the Simulink editor, locate the subsystem, BasicRollMode.
3-30
In the Block Parameters dialog box, click the Code Generation tab. The Function
packaging parameter Auto option instructs the software to use its heuristic to
implement the system efficiently, based on its usage in the model. Otherwise, you
can specify the function implementation based on criteria that you are using for
execution speed and memory utilization.
To use the block name as the function name, in the dialog box, specify Function
name options as Use subsystem name.
To place the code for the function in a separate file and use the function name,
specify File name options as Use function name.
To pass the subsystem inputs and outputs as arguments to the function, specify
Function interface as Allow arguments.
Press Ctrl+B to generate the code. Verify that the subsystem code is in
roll_BasicRollMode.c and its declaration is in roll_BasicRollMode.h.
3-31
compact the generated code into a few files. If your model contains referenced models,
you can specify a different file packaging format for each referenced model.
For your model roll, the File packaging format is set to Modular. Therefore, the code
generator creates the following files:
roll.c
roll.h
roll_private.h
roll_types.h
Subsystem files: roll_BasicRollMode.c and roll_BasicRollMode.c
This example showed how to configure the function interfaces for a model and a
subsystem. The example showed how to configure your model to modularize the
generated code into different file packaging formats. The next example shows how to set
up your model to specify how data appears in the generated code. For more information,
see Define Data in the Generated Code on page 3-33.
3-32
In the Configuration Parameters dialog box, open Code Generation > Code
Placement.
3-33
By default, the code generator places definitions and declarations for global data that use
custom storage classes in the generated files global.c and global.h. Data that do not
use custom storage classes do not appear in these files.
You can also use custom storage classes such as ExportToFile to override this default
placement.
3-34
In the Simulink Editor, select Code > Data Objects > Data Object Wizard.
In the Data Object Wizard, in the Find options group, select all of the check boxes.
Click Find.
In the Class column, if the data object class is not Simulink.Signal, click Change
Class. In the dialog box, for the drop-down list Signal, select Simulink.Signal.
Click OK.
In the Data Object Wizard, click Create to create the data objects. When the data
objects are created in the base workspace, the signal names no longer appear in the
Data Object Wizard.
In the Simulink Editor, open the Model Explorer by clicking the icon.
In the Model Explorer, on the left pane, in the Model hierarchy tree, click Base
Workspace. The newly created data objects are now listed in the base workspace
(center pane).
The next step is to associate the data objects with the signals.
Configure Signal Data Objects
To configure the new signal data objects ailCmd and phiCmd, define the data objects
such that the code generator places them in a struct in the generated code.
1
In the Model Explorer, with the base workspace available in the center pane, select
ailCmd.
The Simulink.Signal properties are displayed in the right pane.
3-35
3-36
Click Apply.
Repeat steps 1 through 4 for phiCmd. ailCmd and phiCmd use the same
StructName, signal_data.
On the Code Generation > Interface pane, click the Configure Model
Functions button. On the Model Interface dialog box, set the Function
specification parameter to Default model initialize and step
functions. Click Apply and OK.
Now the variables ailCmd and phiCmd are defined in a struct in roll.h and used in
roll.c. The struct definition looks similar to the following:
/* Type definition for custom storage class: Struct */
typedef struct signal_data_tag {
real32_T phiCmd;
real32_T ailCmd;
} signal_data_type;
In the Signal Properties dialog box, observe that the Signal name must resolve
to Simulink signal object parameter is selected. When the Data Object Wizard
created Simulink.Signal data objects, the software set this parameter.
Click OK.
Notice the signal object icon on the signal. This icon is another indication that the signal
is associated with a Simulink.Signal object in the base workspace.
3-37
3
3-38
Right-click the block and select Block Parameters (Constant) from the list.
In the Block Parameter dialog box, replace the numeric Constant value with
the corresponding variable name: upThr for 6, or loThr for -6.
In the Model Explorer, in the left navigation pane, select Base Workspace.
From the menu bar, select Add > Simulink.Parameter. This action creates a
Simulink.Parameter object with the default name Param in the center pane.
In the center pane, click the name of the object and rename it to upThr. Press
Enter. The data object properties for upThr are displayed in the right pane.
Click Apply.
10 In the code generation report, select threshold.h. In the file, find the data
declarations for upThr and loThr.
11 In the file global.c, find the data definitions. Because the data objects upThr
and loThr use a custom storage class, by default the generated code places the
definitions in global.c.
In the model, select File > Model Properties > Link to Data Dictionary.
In the Model Properties dialog box, select Data Dictionary. Click New.
In the Create a new Data Dictionary dialog box, set File name to rollDict. Click
Save.
The data dictionary file rollDict.sldd appears in your current folder.
Click Yes in response to the message about migrating base workspace data.
Click Yes in response to the message about removing imported items from the base
workspace.
In the lower-left corner of the model, click the data dictionary badge.
The contents of the data dictionary appear in the Model Explorer.
Related Examples
More About
3-40
Data Objects
When running in SIL simulation mode, the configuration parameters for the top model
and the referenced model must match.
1
For roll_harness, on the Code Generation pane, verify that the Generate code
only check box is cleared.
3-42
To send logged data from the workspace to the Simulation Data Inspector for
model roll_harness, on the Simulink Editor toolbar, click the Simulation Data
Inspector button arrow and select Send Logged Workspace Data to Data
Inspector.
2
3
Right-click the Model block, Roll Axis Autopilot, and from the context menu,
select Block Parameters (ModelReference).
In the Block Parameters dialog box, for Simulation mode, verify that the Normal
option is selected. Click OK.
Simulate roll_harness.
When the simulation is done, view the simulation results in the Simulation Data
Inspector. If the Simulation Data Inspector is not already open, in the Simulink
Editor, click the Simulation Data Inspector button.
For the new run, double-click the run name field and rename the run:
roll_harness: Normal mode.
3-43
In the roll_harness model window, right-click the Roll Axis Autopilot model
block and select Block Parameters (ModelReference).
In the Block Parameters dialog box, specify Simulation mode as Software-inthe-loop (SIL). Click Apply and OK.
On the Simulink Editor toolbar, verify that logged data recording is on.
In the Simulation Data Inspector, double-click the run name field and rename the
new run to roll_harness: SIL mode.
3-44
For Baseline, select roll_harness: Normal mode. For Compare To, select
roll_harness: SIL mode.
Click Compare.
If you find differences in testing results, it is important to investigate and understand the
differences. Some differences can be attributed to implementation changes (converting
from an interpreted model to an executable implementation), or can be an indication of
bugs. You must understand all differences to confirm that the behavior of the system is
free of bugs.
3-45
After testing your model and code, you can fine-tune your model configuration to improve
the code performance. For a specific performance goal, Embedded Coder provides model
configuration parameters on the Optimization panes to help you improve memory
usage and reduce execution time.
When choosing optimization parameters for your model, consider the trade-offs of
one optimization over another optimization. Improving one area of performance can
sacrifice another area of performance. For example, reducing memory usage can sacrifice
execution efficiency.
See
Variant Systems
Data Representation
File Packaging
To
See
3-47
3-48
A
Installing and Using IDE
A-2
Then...
Go to step 4
Go to step 2
Unzip the downloaded Eclipse CDT zip file. Copy the contents of the directories
features and plugins to the corresponding directories in c:\eclipse.
Run the setup.exe file. A Cygwin Setup - Choose Installation Type dialog box
opens.
In the dialog box for selecting packages, set the Devel category to Install by clicking
the selector icon
Add the folder c:\cygwin\bin to your system Path variable. For example, on a
Windows XP system:
a
Click Start > Settings > Control Panel > System > Advanced >
Environment Variables.
Under System variables, select the Path variable and click Edit.
Note: To use Cygwin, your build folder must be on your C drive. The folder path cannot
include spaces.
A-3
About Eclipse
Eclipse (www.eclipse.org) is an integrated development environment for developing
and debugging embedded software. Cygwin (www.cygwin.com) is an environment that is
similar to the Linux environment, but runs on Windows and includes the GCC compiler
and debugger.
This section contains instructions for using the Eclipse IDE with Cygwin tools to build,
run, test, and debug projects that include generated code. There are many other software
packages and tools that can work with code generation software to perform similar tasks.
Installing Eclipse IDE and Cygwin Debugger on page A-2 contains instructions for
installing Eclipse and Cygwin. Before proceeding, be sure you have installed Eclipse and
Cygwin, as described in that section.
To use Cygwin, your build folder must be on your C drive. The folder path cannot include
spaces.
A-4
In Eclipse, choose File > New > C Project. A C Project dialog box opens.
In the Project name field, type the project name throttlecntrl_## (## is
externenv or testcode) .
In the Location field, specify the location of your build folder (for example, C:
\EclipseProjects\throttlecntrl\externenv).
In the Project type selection box, select and expand Makefile project.
In the Select Configurations dialog box, click Advanced settings. The Properties
dialog box appears.
In Eclipse, choose Run > Debug Configurations. The Debug Configurations dialog
box opens.
Setting
Name
throttlecntrl_externenv Default
C/C++ Application
Default\throttlecntrl_externenv.exe
Project
throttlecntrl_externenv
Build configuration
Default
Cleared
Cleared
Selected
A-5
Click Close.
In the main Eclipse window, select Run > Debug. A Confirm Perspective Switch
dialog box opens.
Click Yes. Tabbed debugger panes that display debugging information and controls
are displayed in the main Eclipse window.
Specify the location of the project files. The Cygwin debugger creates a virtual
drive (for example, main() at /cygdrive/) during the build process. To run the
debugger, Eclipse remaps the drive or locates your project files. Once Eclipse locates
the first file, it automatically finds the remaining files. In the Eclipse window, click
Locate File. The Open dialog box opens.
For information on using the Edit Source Lookup Path button, see Set the
Cygwin Path on page A-6.
Navigate to the example_main.c file and click Open. Your program opens in the
debugger software.
A-6
Open the Debug Configurations dialog box by selecting Run > Debug
Configurations > C/C++ Application.
Select Path Mapping and click OK. The Path Mappings dialog box opens.
In the Local file system path field, click the Browse button, navigate to your C:\
drive, and click OK.
Click Apply.
Click Close.
Command
Step into
F5
Step over
F6
Step out
F7
Resume
F8
Ctrl + Shift + B
A-7