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.
Getting Started Guide
Revision History
July 2002First printingNew for V ersion 5.0 (Release 13)
June 2004Second printingRevised for Version 6.0 (Release 14)
October 2004Third printingRevised for Version 6.1 (Release 14SP1)
March 2005Online onlyRevised for Version 6.2 (Release 14SP2)
September 2005 Fourth printingRevised for Version 6.3 (Release 14SP3)
March 2006Online OnlyRevised for Version 6.4 (Release 2006a)
September 2006 Online OnlyRevised for Version 6.5 (Release 2006b)
March 2007Fifth printingRevised for Version 6.6 (Release 2007a)
September 2007 Online OnlyRevised for Version 7.0 (Release 2007b)
March 2008Online OnlyRevised for Version 7.1 (Release 2008a)
October 2008Sixth printingRevised for Version 7.2 (Release 2008b)
March 2009Online OnlyRevised for Version 7.3 (Release 2009a)
September 2009 Online OnlyRevised for Version 7.4 (Release 2009b)
March 2010Online OnlyRevised for Version 7.5 (Release 2010a)
Getting Started with Real-Time Workshop
1
What You Need to Know to Use Real-Time Workshop
Technology
What You Can Accomplish Using Real-Time Workshop
Technology
How the T echnology Can Fit Into Your Development
Process
Tools for Algorithm Development
Target Environments
Applications
How You Can Apply the Technology to the V-Model for
System Development
What Is the V-Model?
Types of Simulation and Prototyping
Types of In-the-Loop Testing for Verification and
Validation
.....................................1-2
.....................................1-3
.........................................1-6
....................1-6
.............................. 1-10
......................................1-14
............................. 1-16
.............................. 1-16
................. 1-18
.....................................1-19
Contents
Technology
How to Develop an Application Using Real-Time
Workshop Software
2
Workflow for Developing Applications Using Real-Time
Tutorial Overv iew
Working and Build Directories
Setting Program Parameters
Selecting the Target Configuration
Building and Running the Program
Contents of the Build Directory
Data Logging
Tutorial Overv iew
DataLoggingDuringSimulation
Data Logging from Generated Code
Code Verification
Tutorial Overv iew
Logging Signals via Scope Blocks
.................................3-4
.......................3-4
........................3-5
...................3-7
................... 3-13
...................... 3-15
......................................3-18
.................................3-18
..................... 3-19
................... 3-22
..................................3-27
.................................3-27
..................... 3-27
..............3-4
Logging Simulation Dat a ...........................3-29
Logging Data from the Generated Program
Comparing Numerical Results of the Simulation and the
Generated Program
............................. 3-31
............ 3-29
First Look at Generated Code
Tutorial Overv iew
Setting Up the Model
Generating Code Without Buffer Optimization
Generating Code With Buffer Optimization
Further Optimization: Expression Folding
HTML Code Generation Reports
Working with External Mode Using GRT
Tutorial Overv iew
Setting Up the Model
Building the Target Executable
Running the External Mode Target Program
Tuning Parameters
Generating Code for a Referenced Model
Tutorial Overv iew
Creating and Configuring a Subsystem Within the vdp
Model
Converting the Model to Use Model Referencing
Generating Model Reference Code for a GRT Target
Working w ith Project Directories
.........................................3-60
.................................3-33
.............................. 3-33
.................................3-47
.............................. 3-48
................................3-58
.................................3-60
....................... 3-33
............ 3-39
............. 3-41
..................... 3-44
............. 3-47
...................... 3-50
........... 3-54
............ 3-60
..................... 3-70
......... 3-35
........ 3-63
..... 3-67
Documenting a Code Generation Project
Tutorial Overv iew
Generating Code for the Model
Opening Re port Generator
Setting Report Output Options
Specifying Models and Subsystems to Include in a
Report
Setting Component Options
Generating the Report
Reviewing the Generated Report
........................................3-77
.................................3-72
...................... 3-73
.......................... 3-74
...................... 3-75
......................... 3-77
............................. 3-78
..................... 3-78
............ 3-72
vii
Index
viiiContents
GettingStartedwith
Real-TimeWorkshop
Technology
• “What You Need to Know to Use Real-Time Workshop Technology” on
page 1-2
• “What You Can Accomplish Using Real-Time Workshop Technology” on
page 1-3
1
• “How the Technology Can Fit Into Your Development Process” on page 1-6
• “How You Can Apply the Technology to the V-Model for System
While you do
create, tes
software, s
familiarit
documenta
concepts,
If you are
to map com
patterns
MATLAB
Web site
.
output in the MATLAB
rogramming language concepts applied to real-time systems
not need to program in C or othe r programming languages to
t, and deploy real-time systems using the Real-Time Workshop
uccessful emulation and deployment of real-time systems requires
y with parameters and design constraints. The Real-Time Workshop
tion assumes you have a basic understanding of real-time system
terminology, and environments.
familiar with C language constructs and want to learn about how
monly used C constructs to code generated from model design
that include Simulink blocks, Stateflow charts, and Embedded
®
functions, see Technical Solution 1-6AWSQ9 on the M athW orks™
eal-Time W orkshop
®
link
and Stateflow®software to create models or state
®
technology, you should be familiar with
ock diagrams, running such simulations in Simulink, and
®
workspace
1-2
What You Can Accomplish Using Real-Time Workshop®Technology
What You Can Accomplish Using Real-Time Workshop
Technology
Real-Time Work
executables fo
environment o
r algorithms that you model graphically in the Simulink
r programmatically with the Embedded MATLAB language
subset. You ca
functions tha
generated so
the function
code executi
product, yo
match to mod
of accuracy
integrate
engines. I
Real-Time
You apply
Workshop
Real-Tim
• Generat
(fixed-
• Use the
includ
hardwa
t are useful for real-time or embedded applications. The
urce code and executables for floating-point algorithms match
al behavior of Simulink simulations and Embedded MATLAB
on to high degrees of fidelity. Using the S i mulink
ucangeneratefixed-pointcodethat provides a bit-wise accurate
el simulation results. Such broad support and high degrees
are possible because Real-Time Workshop technology is tightly
d with the MATLAB and Simulink execution and simulation
n fact, the built-in accelerated simulation modes in Simulink use
Workshop technology.
Real-Time Workshop technology explicitly with the Real-Ti m e
and Real-Time Workshop
e Workshop product, you can
e source code and executables for discrete-time, continuous-time
step),andhybridsystemsmodeledinSimulink
generated code for real-time and non-real-time applications,
ing simulation acceleration, rapid prototyping, and
re-in-the-loop (HIL) testing
shop technology generates C or C++ source code and
n generate code for any Simulink blocks and MATLAB
®
Fixed Point™
®
Embedded Coder™ products. Using the
• Tune a
analy
the MA
• Gene
mode
• Prod
by T
The
Wor
nd monitor the generated code by using Simulink blocks and built-in
sis capabilities, or run and interact with the code completely outside
TLAB and Simulink environment
rate code for finite state machines modeled in Stateflow event-based
ling software, using the optional Stateflow
®
Coder™ product
uce source code for many Simulink products and blocksets provided
he MathWorks™ and third-party vendors.
Real-Time Workshop Embedded Coder product extends the Real-Time
kshop product with features that are important for embedded software
1-3
1 Getting Started with 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
The following table compares typical applications and key capabilities for
these two code generation products.
®
Technology
ProductTypical ApplicationsKey Capabilities
Real-Time Workshop
Simulation acceleration
Simulink model encryption
Rapid prototyping
HIL testing
Generate code for discrete-time,
continuous-time (fixed-step),
andhybridsystemsmodeledin
Simulink
Tune and monitor the execution of
generated code by using Simulink
blocks and built-in analysis
capabilities or by running and
interacting with the code outside
the MATLAB and Simulink
environment
Generate code for finite state
machines modeled in Stateflow
event-based modeling software,
using the optional Stateflow Coder
product
1-4
What You Can Accomplish Using Real-Time Workshop®Technology
ProductTypical ApplicationsKey Capabilities
Generate code for m any
MathWorks and third-party
Simulink products and blocksets
Integrate existing applications,
functions, and data
Real-Time Workshop
Embedded Coder
All applications listed for the
Real-Time Workshop product
Embedded systems
On-target rapid prototyping
boards
Microprocessors used in mass
production
All capabilities listed for the
Real-Time Workshop product
Generate code that has the clarity
and efficiency of professional
handwritten code
Customize the appearance and
performance of the code for specific
target environments
Enable tracing, reporting, and
testing options that facilitate code
verification activities
1-5
1 Getting Started with Real-Time Workshop
®
Technology
How the Technology Can Fit Into Your Development
Process
In this section...
“Tools for Algorithm Development” on page 1-6
“Target Environments” on page 1-10
“Applications” on page 1-14
Tools for Al
You can use
source cod
• With MATL
• As Simuli
• With MAT
The Embe
and func
dynami
large m
eventWorks
MathW
If you
to ma
patt
MATL
Web
The
Rea
tions for floating-point and fixed-point math. Simulink support for
c system simulation, conditional execution of system semantics, and
odel hierarchies provides an enviro n ment for modeling periodic and
driven algorithms commonly found in embedded systems. Real-Time
hop technology generates code for most Simulink blocks and many
orks products.
are familiar with C language constructs and want to learn about how
p commonly used C constructs to code generated from model design
erns that include Simulink blocks, Stateflow charts, and Embedded
AB functions, see Technical Solution 1-6AWSQ9 on the MathWorks
site.
following table lists products that the Real-Time Workshop a nd
l-Time Workshop Embedded Coder softwa re support.
gorithm Development
Real-Time Workshop technology to generate standalone C or C++
e for algorithms that you develop the following ways:
AB code, usin g the Embedded MATLAB language s ub set
nk models
LAB code that you incorporate into Simulink models
dded MATLAB language subset supports MATLAB operators
1-6
How the Technology Can Fit Into Your Development Process
Products Supported by Real-Time
Notes
Workshop and Real-Time Workshop
Embedded Coder
Aerospace Blockset™
Communications Blockset™
Control System T oo lbox™
Embedded IDE Link™
Fuzzy Logic Toolbox™
Gauges Blockset™
—
—
—
—
—
—
MATLABDetails: Supports Embedded MATLAB
Model-Based Calibration Toolbox™
Model Predictive Control Toolbox™
PolySpace®Model Link™ SL
Real-Time Windows Target™
—
—
Not supported by Real-Time Workshop
—
Signal Processing Blockset™Details: “Simulink Block D ata Type Support
for Signal Processing Blockset” Table (enter the
MATLAB
showsignalblockdatatypetable
command)
SimDriveline™
SimElectronics
SimHydraulics
SimMechanics™
®
®
—
—
—
—
SimPowerSystems™
Not supported by Real-Time Workshop
Embedded Coder
Simscape™
—
SimulinkDetails: “Simul in k Built-In Blocks T hat
Support Code Generation” Table in the
Real-Time Workshop documentation
Simulink Fixed Point
Simulink®3D Animation™
—
—
1-7
1 Getting Started with Real-Time Workshop
®
Technology
Products Supported by Real-Time
Workshop and Real-Time Workshop
Embedded Coder
Simulink®Design Optimization™
Simulink®Report Generator™
Simulink®Verification and Validation™
Stateflow and Stateflow Coder
System Identification Toolbox™
Target Support Package™
Vehicle Network Toolbox™
Video and Image Processing Blockset™
xPC Target™
xPC Target Embedde d Option™
Notes
—
—
—
—
Exceptions:
• Nonlinear IDNLGREY Model, IDDATA
Source, IDDATA Sink, and estimator blocks
• Nonlinear ARX models that contain custom
regressors
•
neuralnet nonlinearities
customnet nonlinearities
•
—
Exception: CAN Configuration, CAN Receive,
and CAN Transmit blocks in the CAN
Communication library
—
—
—
1-8
Use of both Embedded MATLAB code and Simulink models is typical for
Model-Based Design projects where you start developing an algorithm
through research and development or advanced production, using MATLAB,
and then use Simulink for system deploym ent and verification. Benefits of
this approach include:
• Richer system simulation environment
• Ability to verify the Embedded MATLAB code
How the Technology Can Fit Into Your Development Process
• Real-Time Workshop a nd Real-Time Workshop Embedded Coder C/C++
code generation for the model and embedded MATLAB code
Thefollowingtablesummarizeshowtogenerate C or C++ code for each of the
three approaches and identifies where you can find more information.
If you develop
Yougeneratecodeby...
algorithms using...
Embedded MATLAB
language subset
Entering the Real-Time
Workshop function emlc in the
MATLAB Command Window.
SimulinkConfiguring and initiating code
generation for your model or
subsystem with the Simulink
Configuration Parameters
dialog.
Embedded MATLAB
language subset and
Simulink
Including Embedded MATLAB
code in Simulink models or
subsystems by using the
Embedded MATLAB Function
block.
To use this block, you can do
one of the following:
• Copy your code into the block.
• Call your code from the
block by referencing the
appropriate files on the
MATLAB path.
For more information, see...
“Working with the Embedded
MATLAB Subset”
“Converting MATLAB Code to
C/C++ Code”
“Workflow for Developing
Applications Using Real-Time
Workshop Software” on page
2-2 in Getting Started with
Real-Time Workshop
“Working with the Embedded
MATLAB Subset” in
the Embedded MATLAB
documentation
The following figure shows the three design and deployment environment
options. Although not shown in the figure, other products that support code
generation, such as Stateflow software, are available.
1-9
1 Getting Started with Real-Time Workshop
®
Technology
Other MATLAB
code
MATLAB
®
Embedded MATLAB
language subset
™
Real-Time Workshop
C or C++
Compiler or
IDE toolchain
Executable
(runs in target environment)
Simulink
Embedded MATLAB
Function block
®
technology
®
™
Other Simulink
blocks
1-10
Targ et Environments
In addition to generating source code for a model or subsystem, Real-Time
Workshop technology generates make or project files you need to build an
executable for a specific target environment. The generated make or project
files are optional. That is, if you prefer, you can build an executable for the
generated source files by using an existing target build environment, such
as a third-party integrated development environment (IDE). Applications
of code generated with Real-T ime Workshop technology range from calling
a few exported C or C++ functions on a host com puter to generating a
complete executable using a custom build process, for custom hardware, in an
environment completely separate from the host computer running MATLAB
and Simulink.
How the Technology Can Fit Into Your Development Process
Real-Time Workshop technology provides built-in system target files that
generate, build, and execute code for specific target environments. These
system target files offer varying degrees of s upport for interacting with the
generated code to log data, tune parameters, and experiment with or w ithout
Simulink as the external interface to your generated code.
Before you select a system target file, you need to identify the target
environment on which you expect to execute your generated code. The three
most common target environments include:
Target
Environment
Host computer
Real-time
simulator
Description
The same computer that runs MATLAB and Simulink. Typically, a host
computer is a PC or UNIX
operating system, such as Microsoft
1
®
environment that uses a non-real-time
®
Windows®or Linux
2
®
.Non-real-time
(general purpose) operating systems are nondeterministic. For example,
they might suspend code execution to run an operating system service
and then, after providing the service, continue code execution. Thus, the
executable for your generated code might run faster or slower than the
sample rates you specified in your model.
A different computer than the host computer. A real-time simulator can
be a PC or UNIX environment that use s a real-time operating system
(RTOS), such as:
• xPC Target system
• Areal-timeLinuxsystem
• A Versa Module Eurocard (VME) chassis with Pow erP C
running a commercial R TO S, such as VxWorks
®
from Wind River
®
processors
®
Systems
The generated code runs in real time and behaves deterministically.
Although, the exact nature of execution varies based on the particular
behavior of th e system hardware and RTOS.
1. UNI
countries.
2. Linux
®
is a registered trademark of The Open Group in the Uni ted States a nd other
X
®
is a registered trademark of Linus Torvalds.
1-11
1 Getting Started with Real-Time Workshop
®
Technology
Target
Environment
Embedded
microprocessor
Description
Typically, a real-time simulator connects to a host computer for data
logging, interactive parameter tuning, and Monte Carlo batch execution
studies.
A computer that you eventually disconnect from a host computer a nd
run standalone as part of an electronics-based product. Embedded
microprocessors range in price and performance, from high-end digital
signal processors (DSPs) used to process communication signals to
inexpensive 8-bit fixed-point microcontrollers used 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 Real-Time Workshop
technology
A target environment can:
• Have single- or multiple-core CPUs
1-12
• Be standalone or communicate as part of a computer network
In addition, you can deploy different parts of a Simulink model on different
target environments. For example, it is common to separate the component
(algorithm or 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 ma n y benefits such as
early verification of component correctness.
The following figure shows example target environments for code generated
for a model.
System model
How the Technology Can Fit Into Your Development Process
Algorithm model
Code
generation
Host
executable
Host computer(s)
Code
generation
Embedded
microprocessor
Environment model
Code
generation
Real-time
simulator
1-13
1 Getting Started with Real-Time Workshop
Applications
The following ta
technology in th
®
Technology
ble lists several ways you can apply Real-Time Workshop
e contex t of the different target environments.
Application
Host Computer
Accelerated simulationYou apply techniques to speed up the execution of model
Rapid simu
System simulation
Model encryption
Real
Rapid prototypingYou generate, deploy, and tune code on a real-time
lation
-Time Simulator
Description
simulation in the context of the MATLAB and Simulink
environment. Accelerated simulations are especially
useful when run time is long compared to the time
associated with compilation and checking whether the
target is up to date.
You execute code generated for a model in non-real time
on the host computer, but outside the context of the
MATLAB and Simulink environment.
You inte
provide
for buil
shared
You gen
model
anoth
simulator connected to the system hardware (for
example, physical plant or vehicle) being controlled.
This design step is also crucial for validating whether a
component can adequately control the physical system.
grate components into a larger system. You
generated source code and related dependencies
ding in another environment or a host-based
library to which other code can dynamically link.
erate a Simulink shareable object library for a
or subsystem for use by a third-party vendor in
er Simulink simulation environment.
System simulation
1-14
You integrate generated source code and dependencies
for components into a larger system that is built in
another environment. You can use shared library files to
encrypt components for intellectual property protection.
How the Technology Can Fit Into Your Development Process
Application
Description
On-target rapid prototypingYou generate code for a detailed design that you can
runinrealtimeonanembeddedmicroprocessorwhile
tuning parameters and monitoring real-time data. This
design step allows you to assess, interact with, and
optimize code, using embedded compilers and hardware.
Embedded Microprocessor
Production code generation
From a model, you generate code that is optimized for
speed, memory usage, simplicity, and if necessary,
compliance with industry sta n dards and g uidelines.
Software-in-the-loop (SIL) testing
You execute generated code with your plant model
within Simulink to verify success ful conversion of
the model to code. You might change the code to
emulate target word size behavior and verify numerical
results expected when the code runs on an embedded
microprocessor, or use actual target word sizes and just
test production code behavior.
Processor-in-the-loop (PIL) testing
You test an object code component with a plant
or environment model in an open- or closed-loop
simulation to verify successful model-to-code conversion,
cross-compilation, and software integration.
Hardware-in-the-loop (HIL) testingYou verify an embedded system or embedded computing
unit (ECU), using a real-time target environment.
1-15
1 Getting Started with Real-Time Workshop
®
Technology
How You Can Apply the Technology to the V-Model for
System Development
In this section...
“What Is the V-Model?” on page 1-16
“Types of Simulation and Prototyping” on page 1-18
“Types of In-the-Loop Testing for Verification and Validation” on page 1-19
What Is the V-Model?
The V-model is a representation of system development that highlights
verification and validation steps in the system development process. As the
following figure shows, the left side of the V identifies steps that lead to code
generation, including requirements analysis, system specification, detailed
software design, and coding. The right side focuses on the verification and
validation of steps cited on the left side, including software integration and
system integration.
1-16
How You Can Apply the Technology to the V-Model for System Development
Verification and validation
Simulation
Rapid simulation
System Specification
System simulation (export)
Rapid prototyping
Software Detailed
On-target rapid prototyping
Depending on your application and role in the process, you might focus on one
or more of the steps called out in the V or repeat steps at several stages of
the V . Real-Time Workshop technology and related products provide tooling
you can apply at each step.
Design
Software Integration
Coding
Production code generation
Model encryption (export)
Hardware-in-the-loop
(HIL) testing
System Integration
and Calibration
Processor-in-the-loop
(PIL) testing
Software-in-the-loop
(SIL) testing
The following sections compare
• Types of simulation and prototyping
• Types of in-the-loop testing for verification and validation
For a map of information on applications of Real-Time Workshop technology
identified in the figure, see the following tables:
• “Documenting and Validating Requirements”
1-17
1 Getting Started with Real-Time Workshop
• “Developing a Model Executable Specification”
• “Developing a Detailed Softwa re Design”
• “Generating the Application Code”
• “Integrating and Verifying Software”
• “Integrating, Verifying, and Calibrating System Components”
Types of Simulation and Prototyping
The following table compares the types of simulation and prototyping
identified on the left side of the V-model diagram.
®
Technology
Purpose
Execution
hardware
Host-Based
Simulation
Test and validate
functionality of
concept model
Host computerHost computer
Standalone
Rapid
Simulations
Refine, test,
and validate
functionality of
concept model in
non-real time
Standalone
executable
runs outside
of MATLAB
and Simulink
environment
Rapid
Prototyping
Test new ideas
and research
PC or nontarget
hardware
On-Tar get Rapid
Prototyping
Refine and
calibrate
designs during
development
process
Embedded
computing
unit (ECU) or
near-production
hardware
1-18
How You Can Apply the Technology to the V-Model for System Development
Code
efficiency
and I/O
latency
Ease of use
and cost
Host-Based
Simulation
Not applicableNot applicableLess emphasis
Can simulate
component
(algorithm or
controller) and
environment (or
plant)
Normal mode
simulation in
Simulink enables
you to access,
display, and
tune data and
parameters while
experimenting
Can accelerate
Simulink
simulations with
Accelerated and
Rapid Accelerated
modes
Standalone
Rapid
Simulations
Easy to simulate
models of hybrid
dynamic systems
that include
components and
environment
models
Ideal for batch
or Monte C arlo
simulations
Can repeat
simulations with
varying data sets,
interactively or
programmatically
with scripts,
without rebuilding
the model
Can be connected
to Simulink
to monitor
signals and tune
parameters
Rapid
Prototyping
on code efficiency
and I/O latency
Might require
custom real-time
simulators and
hardware
Might be done
with inexpensive
off-the-shelf PC
hardware and I/O
cards
On-Tar get Rapid
Prototyping
More emphasis on
code efficiency and
I/O latency
Might use existing
hardware, thus
less expensive and
more convenient
Types of In-the-Loop Testing for Verification and
Validation
Thefollowingtablecomparesthetypesof in-the-loop testing for verification
and validation identified on the right side of the V-model diagram.
1-19
1 Getting Started with Real-Time Workshop
®
Technology
Purpose
Fidelity and
accuracy
Execution
platforms
Ease of use
and cost
SIL TestingPIL Testing
on Embedded
Hardware
Verify component
source code
Two options:
Same source
code as target,
but migh t
have numerical
differences
Verify component
object code
Same object code
Bit accurate for
fixed-point math
Cycle accurate
since code runs on
hardware
Changes source
code to emulate
word sizes, but is
PIL Testing on
Instruction Set
Simulator
Verify component
object code
Same object code
Bit accurate for
fixed-point math
Might not be cycle
accurate
HIL Testing
Verify system
functionality
Same executable
code
Bit accurate for
fixed-point math
Cycle accurate
Use real and
emulated system
I/O
bit accurate for
fixed-point math
HostTargetHostTarget
Desktop
convenience
Executes just in
Simulink
No cost for
hardware
Executes on desk
or test bench
Uses hardware —
process board and
cables
Desktop
convenience
Executes just on
host computer
with Simulink
and integrated
development
environment
Executes on test
bench o r in lab
Uses hardware
— processor,
embedded
computer unit
(ECU), I/O devices,
and cables
• “Workflow for Developing Applications Using Real-Time Workshop
Software” on page 2-2
2
• “Mapping Application Requirements to Configuration Options” on page 2-4
• “Adjusting Configuration Settings” on page 2-6
• “Running the Model Advisor” on page 2-7
• “Generating Code” on page 2-10
• “Building an Executable Program” on page 2-11
• “Verifying the Executable Program” on page 2-14
• “Naming and Saving the Configuration Set” on page 2-15
• “Documenting the Project” on page 2-17
2 How to Develop an Application Using Real-Time Workshop
®
Software
Workflow for Developing Applications Using Real-Time
Workshop Software
ThetypicalworkflowforapplyingtheReal-TimeWorkshopsoftwaretothe
application development process involves the following steps:
1 Map your application requirements to available configuration options.
2 Adjust configuration options as necessary.
3 Run the Model Advisor tool.
4 If necessary, tune configuration options based on the Model Advisor report.
5 Generate code for your model.
6 Repeat steps 2 to 5, if necessary.
7 Build an executable program image.
2-2
8 Verify that the generated program produces results that are equivalent
to those of your model simulation.
9 Save the configuration, and alternative ones with the model.
10 Use Simulink Report Generator to automatically document the project.
The following figure shows these steps in a flow diagram. Sections following
the figure d iscuss the step s in more detail.
Workflow for Developing Applications Using Real-Time Workshop®Software
Map Application Requirements
to Configuration Options
Adjust Configuration Settings
Run Model Advisor
Generate Code
Build Executable Program
Verify Executable Program
Name and Save
Configuration Set
Document Project
Done
Configuration
Requires
Tuning?
No
Code OK?
Yes
Results Match
Simulation?
Yes
Yes
No
No
2-3
2 How to Develop an Application Using Real-Time Workshop
®
Software
Mapping Application Requirements to Configuration
Options
The first step in applying the Real-Time Workshop software to the application
development process is to consider how your application requirements,
particularly with respect to debugging, traceability, efficiency, and safety,
maptocodegenerationoptionsavailablethroughtheSimulinkConfiguration
Parameters dialog box. The following screen display shows the Real-Time
Workshop pane of the Configuration Param eters dialog box.
2-4
Parameters that you set in the various panes of the Configuration Parameters
dialog box affect the behavior of a model in simulation and the code generated
for the model. The Real-Time Workshop software automatically adjusts the
available configuration parameters and their default settings based on your
target selection. For example, the precedingdialogboxdisplayshowsdefault
settings for the generic real-time (GRT) target. However, you should become
familiar with the various parameters and be prepared to adjust settings to
optimize a configurationforyourapplication.
As you review the parameters, consider questions such as the following:
• What settings will help you debug your application?
• What is th e highest priority for your application — efficiency, traceability,
extra safety precaution, or some other criterion?
• What is the second h ighest priority?
Mapping Application Requirements to Configuration Options
• Can the priority at the start of the project differ from the prio rity required
for the end? What tradeoffs can be made?
Once you have answered these questions, you can either:
• Use the Code Generation Advisor to identify changes to model constructs
and settings that improve the generated code. For more information, see
“Configuring Code Generation Objectives” in the Real-Time Workshop
User’s Guide.
• Review “Recommended Settings Summary”, which summarizes the impact
of each configuration option on efficiency, traceability, safety precautions,
and debugging, and indicates the default (factory) configuration settings for
the GRT target. For additional details, click the links in the Configuration
Parameter column.
Note
• Review the “Recommended Settings Summary” to see the settings the Code
Generation Advisor recommends.
• If you use a specific embedded target, a Stateflow target, or fixed-point
blocks, consider the mapping of many other configuration parameters. For
details, see the documentation specific to your target environment.
2-5
2 How to Develop an Application Using Real-Time Workshop
Adjusting Configuration Settings
Once you have mapped your application requirements to appropriate
configuration parameter settings, adjust the settings accordingly. Using
the Default column in “Map ping Application Requirements to the Solver
Pane”, identify the configuration parameters you need to modify. Then,
open the Configuration Parameters dialog box or Model Explorer and make
the necessary adjustments.
Tutorials in Chapter 3, “Working with the Real-Time Workshop Software”
guide you through exercisesthatmodifyconfiguration parameter settings.
For more information on setting configuration parameters for code generation,
see “Preparing Models for Code Generation”“B u ilding Executables” in the
Real-Time Workshop documentation. For des criptions of parameters specific
to the Real-Time Workshop product, see “Configuration Parameters for
Simulink Models” or “Configuration Parameters for Embedded MATLAB
Coder” in the Real-Time Workshop reference documentation.
®
Software
2-6
Note In addition to using the Configuration Parameters dialog box, you can
use
get_param and set_param to individually access most configuration
parameters both interactively and in scripts. The configuration parameters
you can get and set are listed in the “Parameter Reference” in the Real-Time
Workshop documentation.
Running the Model Advisor
Before yo u generate code, it is good practice to run the Model Advisor. Bas ed
on a list of options you select, this tool analyzes your model and its parameter
settings, and generates results that list findings with advice on how to correct
and improve the model and its configuration.
One way of starting the Model Advisor is to select Tools > Model Advisor in
your model win dow. A new w i ndow appears listing specific diagnostics you
can selectively enable or disable. Some examples of the diagnostics follow:
• Identify blocks that generate expensive saturation and rounding code
2 How to Develop an Application Using Real-Time Workshop
Although you can use the Model Advisor to improve model simulation, it
is particularly useful for identifying aspects of your model that limit code
efficiency or impede deployment of production code. The following figure
shows the Model Advisor.
®
Software
2-8
Running the Model Advisor
For more information on using the Model Advisor, see “Getting Advice
About Optimizing Models for Code Generation” in the Real-Time Workshop
documentation.
2-9
2 How to Develop an Application Using Real-Time Workshop
Generating Code
After fine-tuning your model and its parameter settings, you are ready to
generate code. Typically, the first timethroughtheprocessofapplying
Real-Time Workshop software for an application, you w ant to g enerate code
without going on to compile and link it into an executable program. Some
reasons for doing this include the following:
• You want to inspect the generated code. Is the Real-Time Workshop code
generator creating what you expect?
• You need to integrate custom handwritten code.
• You want to experiment with configuration option settings.
You specify code generation only by selecting the Generate code only
check box available on the Real-Time Workshop pane of the Configuration
Parameters dialog box (thus changing the label of the Build button to
Generate code). The Real-Time Workshop code gen e rator responds by
analyzing the block diagram that represents your model, generating C code,
and placing the resulting files in a build directory within your current
working directory.
®
Software
2-10
After generating the code, inspect it. Is it what you expected? If not,
determine what model and configuration changes you need to make, rerun
the Mo del Advisor, and regenerate the code. When you are satisfied with the
generated code, build an executable program image, as explained in “Building
an Executable Program” on page 2-11.
For details on the Generate code only option, see “Generate code only” in
the Real-Time Workshop documentation.
Building an Executable Program
Whenyouaresatisfiedwiththecodegenerated for your model, build an
executable program image. If it is currently selected, you need to clear the
Generate code only option on the Real-Time Workshop pane o f the
Configuration Parameters dialog box. This changes the label of the Generatecode button back to Build.
One way of initiatin g a build is to click the Build button. The Real-Time
Workshop code generator
1 Compiles the model — The Real-Time Workshop software analyzes your
block d iagram (and any models referenced by Model blocks) and compiles
an intermediate hierarchical representation in a file called model.rtw.
2 Generates C code — The Target Language Compiler reads model.rtw ,
translates it to C code, and places the C file in a build directory within
your working directory.
Building an Executable Program
When you c
2-10, proce
3 Generates a customized makefile — The Real-Time Workshop software
lick Generate code, as explained in “Generating Code” on page
ssing stops here .
constructs a makefile from the appropriate target makefile template and
writes it in the build directory.
4 Generates an executable program — Instructing your system’s make utility
to use the generated makefile to compile the generated source code, link
object files and libraries, and generate an executable program file called
model (UNIX) or model.exe (Microsoft Windows). The makefile places the
executable image in your working directory.
u select Create code generation report on the Real-Time
If yo
shop > Report> pane, a navigable summary of source files is
Work
uced when the model is built. The report files occupy directory
prod
uild directory. The report contents vary depending on the target, but
the b
reports feature links to g enerated source files.
all
he software detects code generation constraints for your model, it issues
If t
ning or error messages.
war
html in
2-11
2 How to Develop an Application Using Real-Time Workshop
The following figure illustrates the complete process. The box labeled
“Automated build process” highlights portions of the process that the
Real-Time Workshop software executes.
®
Software
Simulink
model
User-developed
model and
template
makefile
Automated
build process
Executable
C program
Configuration
Set Parameters
Generate
Code
Model Code
model.c
model.h
model_private.h
...
make -f model.mk
Program
model.exe
Your
Template
Makefile
system.tmf
Generate
Makefile
Custom
Makefile
model.mk
make_rtw.m
2-12
The MATLAB command file specified by the Make command field in
the Build process section of the Real-Time Workshop pane of the
Configuration Parameters dialog box controls an internal p o rti on of the
Real-Time Workshop build process. By default, the name of the command file
is
make_rtw; the Real-Time Workshop build proces s invokes this file for most
targets. Any options specified in this field are passed into the makefile-based
build process. In some cases, targets cus tomize the
However, the arguments used by the function must be preserved.
make_rtw command.
Building an Executable Program
Although the command may work for a stand-alone model, use of the
make_rtw command at the command line can be error prone. For example, if
you have multiple models o pe n, you need to check whether
• The current subsystem, found by entering
gcs in the MATLAB command
window, contains the model you want to build.
• The Make command specified in the Configuration Parameters dialog box
for the target environment is
make_rtw.
• The model includes Model blocks. Models containing Model blocks do not
build by using
make_rtw directly.
To build (or generate code for) a model from the MATLAB Command Window,
use one of the following
rtwbuild commands, where model isthenameof
the model:
rtwbuild model
rtwbuild('model')
2-13
2 How to Develop an Application Using Real-Time Workshop
Verifying the Executable Program
Once you have an executable image, run the image and compare the results to
the results of your model’s simulation. You can do this by
1 Logging output data produced by simulation runs
2 Logging output data produced by executable program runs
3 Comparing the results o f the simulation and executable program runs
Does the output match? Are you able to explain any differences? Do you need
to eliminate any differences? At this point, it might be necessary to revisit
and possibly fine-tune your block and configuration parameter settings.
For an example, see “Code Verification” on page 3-27.
®
Software
2-14
Naming and Saving the Configuration Set
Naming and Saving the Configuration Set
When you close a model, you should save it to preserve your configuration
settings (unless you regard your recent changesasdispensable).Ifyouwant
to maintain several alternative configurations for a model (e.g., GRT and
Rapid Simulation targets, inline parameters on/off, different solvers, etc.), you
can set up a config uration set for each set of configuration parameters and
give it an identifying name. You can do this easily in Model Explorer.
To name and save a configuration,
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click the Configuration (active) node under the model name.
The Configuration Parameters dialog box appears in the right pane.
4 In the Configuration Parameters pane, type a name you want to give
the current configuration in the Name field.
5 Click Apply. The name of the active configuration in the Model
Hierarchy pane changes to the name you typed.
6 Save the model.
Adding and Copying Configuration Sets
You can save the model with more than one configuration so that you
can instantly reconfigure it at a later time. To do this, copy the active
configuration to a new one, or add a new one, then modify and name the
new configuration, as follows:
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
2-15
2 How to Develop an Application Using Real-Time Workshop
3 To add a new configuration set, while the model is selected in the Model
Hierarchy pane, select Configuration Set from the Add menu, or click
theyellowgearicononthetoolbar:
A new configuration set named Con figu ration appears in the ModelHierarchy pane.
4 To copy an existing configuration set, right-click its name in the Model
Hierarchy pane and drag it to the + sign in front of the model name.
®
Software
A new configuration set with a numeral (e.g.,
1)appendedtoitsname
appears lower in the Model Hierarchy pane.
5 If desired, rename the new configuration by right-clicking it, selecting
Properties, and typing the new name in the Name field on the
Configuration Parameters dialog box that appears. Then click the Apply
button.
6 Make the new configuration the active one by right-clicking it in the Model
Hierarchy pane and selecting Activate from the context menu.
The content of the Is Active field in the right pane changes from no to yes.
7 Save the model.
2-16
Documenting the Project
Consider documenting the design and implementation details of your project
to facilitate
• Project verification and validation
• Collaboration with other individuals or teams, particularly if dependencies
exist
• Archiving the project for future reference
OnewayofdocumentingaReal-TimeWorkshopcodegenerationproject
is to use the Simulink Report Generator software. You can generate a
comprehensive Rich Text Format (RTF), Extensible Markup Language (XML),
or Hypertext Markup Language (HTML) report that includes the following
information:
• Model name and version
• Real-Time Workshop product version
Documenting the Project
• Date and time the code generator created the code
• List of generated source and header (include) files
• Optimization and R eal-Time Workshop target selection and build process
configuration settings
• Mapping of subsystem numbers to subsystem labels
• Listings of generated and custom code for the model
To get started with generating a code generation report, see the demo
rtwdemo_codegenrpt and tutorial “Documenting a Code Generation Project”
on page 3-72. For details on using the Report Generator, see the Simulink
Report Generator User’s Guide.
2-17
2 How to Develop an Application Using Real-Time Workshop
®
Software
2-18
3
Working with the Real-Time
Workshop Software
This chapter provides hands-on tutorials that help you get started generating
code with the R eal-Time Workshop software, as quickly as possible. It
includes the following topics:
• “Demonstration Model: rtwdemo_f14” on page 3-3
• “Building a Generic R ea l-Time Program” on page 3-4
• “Data Logging” on page 3-18
• “Code Verification” on page 3-27
• “First Look at Generated Code” on page 3-33
• “Working with External Mode Using GRT” on page 3-47
• “Generating Code for a Referenced Model” on page 3-60
• “Documenting a Code Generation Project” on page 3-72
To get the maximum benefit from this book, The MathWorks recommends
that you study and work all the tutorials, in the order presented.
These tutorials assume ba s ic familiarity with the MATLAB and Simul in k
products. You should also read Chapter 2, “How to Develop an Application
Using Real-Time Workshop Software”, before proceeding.
The procedures for building, running, and testing your programs are almost
identical in UNIX and PC environments. The discussion notes differences
where applicable.
3 Working with the Real-Time Workshop
Make sure that a MATLAB compatible C compiler is installed on y our system
before proceeding with these tutorials. For details on supported compiler
versions, see
The first three tu t orials use a demo n stration Simulink model,
rtwdemo_f14.mdl, from the directory:
matlabroot/toolbox/rtw/rtwdemos/
By default, this directory is on your MATLAB path; matla broot is the location
of MATLAB on your system. The
flight controller for the longitudinal motion of a Grumman Aerospace F-14
aircraft. T he figure below shows the top level of this model.
rtwdemo_f14 model represents a simplified
Demonstration Model: rtwdemo_f14
model simulates the pilot’s stick input with a square wave having a
The
quency of 0.5 radians per second and an amplitude of ± 1. The system
fre
puts are the aircraft angle of attack and the G forces experienced by the
out
ot. The input and output signals are visually monitored by Scope blocks.
pil
3-3
3 Working with the Real-Time Workshop
®
Software
Building a Generic Real-Time Program
In this section...
“Tutorial Overview” on page 3-4
“Working and Build Directories” on page 3-4
“Setting Program Parameters” on page 3-5
“Selecting the Target Configuration” on page 3-7
“Building and Running the Program” on page 3-13
“Contents of the Build D irectory” on page 3-15
Tutorial Overview
This tutorial walks through the process of generating C code and building an
executable program from the demonstration model. The resulting stand-alone
program runs on your workstation, independent of external timing and events.
3-4
Working and Build Dir ectories
It is convenient to work with a local copy of the rtwdemo_f14 model, stored in
its own directory,
1 In the MATLAB Current Folder browser, navigate to a directory where
you have write access.
2 Create the working directory from the MATLAB command line by typing:
r f14example
mkdi
3 Make f14exa mple your working directory:
14example
cd f
4 Open the rtwdemo_f14 model:
wdemo_f14
rt
The model appears in the Simulink window.
f14example. Set up your working directory as follows:
Building a Generic Real- Time Program
5 In the model window, choose File > Save As. Navigatetoyourworking
directory,
f14rtw.mdl.
f14example.Saveacopyofthertwdemo_f14 model as
During code generation, the Real-Time Workshop software creates a build
directory within your working directory. The build directory name is
model_target_rtw, derived from the name of the source model and the
chosen target. The build directory stores generated source code and other files
created during the build process. You examine the build directory contents at
the end of this tutorial.
Note When a model contains Model blocks (which enable one Simulink model
to include others), special project directories are created in your working
directory to organize code for referenced models. Project directories exist
alongside of Real-Time Workshop build directories, and are always named
slprj. “Generating Code for a Referenced Model” on page 3-60 describes
navigating project directory structures in Model Explorer.
Setting Program Parameters
To generate code correctly from the f14rtw model, you must change some of
the simulation parameters. In particular, note that generic real-time (GRT)
and most other targets require that the model specify a fixed-step solver.
Note The Real-Time Workshop software can generate code for models using
variable-step solvers for rapid simulation (
To set parameters, use the Model Explorer as follows:
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
rsim) and S-function targets only.
3-5
3 Working with the Real-Time Workshop
4 Click Solver in the center pane. The Solver pane appears at the right.
5 Enter the following parameter values on the Solver pane (some may
already be set):
®
Software
• Start time:
0.0
• Stop time: 60
• Type: Fixed-step
• Solver: ode5 (Dormand-Prince)
• Fixedstepsize(fundamentalsampletime): 0.1
• Tasking mode for periodic sample times: SingleTasking
The Solver pane with the modified parameter settings is shown below.
Note the tan background color of the controls you just changed. The color
also appears on fields that were set automatically by your choices in other
fields. Use this visual feedback to verify that what you set is what you
intended. When you apply your changes, the background color reverts
to white.
3-6
Building a Generic Real- Time Program
6 Click Ap
7 Save the model. Simulation parameters persist with the model, for use in
ply to register your changes.
future sessions.
Selecting the Target Configuration
Note Some of the steps in this section do not require you to make changes.
Theyareincludedtohelpyoufamiliarize yourself with the Real-Time
Workshop user interface. As you step through the dialog boxes, place the
mouse p ointer on any item of interest to see a tooltip describing its function.
To specify the desired target configuration, you choose a system target file, a
template makefile, and a
make command.
3-7
3 Working with the Real-Time Workshop
In the se tutorials (and in most applications), you do not need to specify these
parameters individually . Here, you use the ready-to-run generic real-time
target (GRT) configuration. The GRT target is d esigned to build a stand-alone
executable program that runs on your workstation.
To select the GRT target via the Model Explorer:
1 With the f14rtw model open, open Model Explorer by selecting Model
Explorer from the model’s View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
4 Click Real-Time Workshop in the center pane. The Real-Time
Workshop pane appears at the right. This pane has several tabs.
5 Click the General tab to activate the pane that controls target selection.
®
Software
3-8
Building a Generic Real- Time Program
6 Click the Browse button next to the System target file field. This opens
the System Target File Browser, illustrated below. The browser displays
a list of all currently available target configurations. Your available
configurations may differ. When you select a target configuration, the
Real-Time Workshop software automatically chooses the appropriate
system target file, template makefile, and
make command. Their names
appear at the bottom left of the window.
Note The system target file browser lists all system target files found on
the MATLAB path. Using some of these might require additional licensed
products, such as the Real-Time Workshop Embedded Coder product.
3-9
3 Working with the Real-Time Workshop
7 From the list of available configurations, select Generic Real-Time
Target
The Real-Time Workshop pane displays the correct system target
file (
grt.tlc), make command (make_rtw), and template makefile
(
grt_default_tmf), as shown below:
®
Software
(as shown above) and then click OK.
3-10
Building a Generic Real- Time Program
8 Select the Debug tab of the Real-Time Workshop pane. The options
displayed here control build verbosity and debugging support, and are
common to all target configurations. Make sure that all options are set
to their defaults , as shown below.
3-11
3 Working with the Real-Time Workshop
9 Select the Symbols tab of the Real-Time Workshop pane. The options on
this pane control the look and feel of generated code.
®
Software
3-12
Building a Generic Real- Time Program
10 Select the Comments tab of the Real-Time Workshop pane. The options
displayed here control the types of comments included in generated code.
Make sure that all options are set to their defaults, as shown below.
11 Make sure that the Generate code only check box at the bottom of the
pane is cleared.
12 Save the model.
Building and Running the Program
The Real-Time W orkshop build process generates C code from the model,
and then compiles a nd links the generated program to create an executable
image. To build and run the program,
3-13
3 Working with the Real-Time Workshop
1 With the f14rtw model open, go to the Mo del Explorer window. In the
Real-Time Workshop pane, select the General tab, then click the Build
button to start the build process.
A number of message s concerning code generation and compilation appear
in the MATLAB Command Window. The initial message is
### Starting Real-Time Workshop build procedure for model: f14r tw
The contents of many of the succeeding messages depends on your compiler
and operating system. The final message is
### Successful completion of Real-Tim e Workshop build procedure
for model: f14rtw
The w orking directory now contains an executable, f14rtw.exe (Microsoft
Windows platforms) or
Real-Time Workshop build process has created a project directory,
and a build directory,
®
Software
f14rtw (UNIX platforms). In addition, the
slprj,
f14rtw_grt_rtw, in your working directory.
3-14
Note The Real-Time Workshop build process displays a code generation
report after generating the code for the
f14rtw model. The tutorial “First
Look at Generated Code” on page 3-33 provides more information about
how to create and use a code generation report.
2 To observe the contents of the working directory after the build, type the
dir command from the MATLAB Command Window.
dir
.f14rtw.exef14rtw_grt_rtw
..f14rtw.mdlslprj
Building a Generic Real- Time Program
3 To run the executable from the Command Window, type
!f14rtw
The ! character passes the command that follow s it to the operating system,
which runs the stand-alone
f14rtw program.
The program produces one line of output in the Command Window:
**starting the model**
No data is output.
4 Finally, to see the files created in the build directory, type
dir f14rtw_grt_rtw
The exact list of files produced v aries among MATLAB platforms and
versions. Here is a sample list from a Windows platform.
The build process creates a build directory and names it model_target_rtw,
where
for the model. In this example, the build directory is named
The build directory includes the foll owing generated files.
model is the n ame of the source model and target is the target selected
f14rtw_grt_rtw.
3-15
3 Working with the Real-Time Workshop
Note The code generation report you created for the f14rtw model in the
previous section displays a link for each file listed b elow, which you can click
to explore the file contents.
®
Software
File
f14rtw.c
rt_nonfinite.c
rtGetInf.c
rtGetNaN.c
rt_rand.c
f14rtw.h
f14rtw_private.h
f14rtw_types.h
rt_nonfinite.h
rtGetInf.h
rtGetNaN.h
rt_rand.h
rtmodel.h
rtwtypes.h
Description
Standalone C code that implements the model
Functions to initialize nonfinite types (Inf,
NaN,and-In f)
Random functions, included only if needed by
the application
An include header file containing definitions of
parameters and state variables
Header file containing com m on include
definitions
Forward d eclarations of data types used in the
code
Provides support for nonfinite numbers in the
generated code, dynamically generates
NaN,and-Inf as needed
Inf,
Imported declarations for random functions,
included only if needed by the application
Master header file for including generated code
in the static main program (its name never
changes, and it simply inclu des
f14rtw.h)
Static include file for Simulink simstruct data
types; some embedded targets tailor this file to
reduce ov erhead, but GRT does not
3-16
The build directory contains other files used in the build process , most of
which you can disregard for the present:
•
f14rtw.mk — Makefile generated from a template for the GRT target
Building a Generic Real- Time Program
• Object (.obj)files
f14rtw.bat — Batch control file
•
rtw_proj.tmw —Markerfile
•
buildInfo.mat — Build information for relocating generated code to
•
another development environment
•
defines.txt — Preprocessor defines required for compiling the generated
code
•
f14rtw_ref.rsp — D ata to include as command-line arguments to mex
(Windows systems only)
The build directory also contains a subdirectory,
html, which contains the
files that make up the code generation report. For more information about
the code generation report, see the tutorial “First Look at Generated Code”
on page 3-33.
3-17
3 Working with the Real-Time Workshop
Data Logging
In this section...
“Tutorial Overview” on page 3-18
“Data Logging During Simulation” on page 3-19
“Data Logging from Generated C ode” on page 3-22
Tutorial Overview
Real-Time Workshop MAT-file data logging facility enables a generated
program to save system states, outputs, and simulation time at each model
execution time step. The data is written to a MAT-file, named (by default)
model.mat,wheremode l isthenameofyourmodel. Inthistutorial,data
generated by the model
to “Building a Generic Real-Time Program” on page 3-4 for instructions on
setting up
®
Software
f14rtw.mdl is logged to the file f14rtw.mat. Refer
f14rtw.mdl in a working directory if you have not done so already.
3-18
To configure data logging, click Data Import/Export in the center pane
of the Model Explorer. The process is the same as configuring a Simulink
modeltosaveoutputtotheMATLABworkspace. Foreachworkspacereturn
variable you define and enable, the Real-Time Workshop software defines
a parallel MAT-file variable. For example, if you save simulation time to
the v ariable
named
it entirely. You do this by selecting Real-Time Workshop in the center pane
of the Model Explorer, then clicking the Interface tab.
Note Simulink lets you log signal data from anywhere in a model via the Log
signal data option in the Signal Properties dialog box (accessed via context
menu by right-clicking signal lines). The Real-Time Workshop software
does not use this method of signal logging in generated code. To log signals
in generated code, you must either use the Data Import/Export options
described below or include To File or To Workspace blocks in your model.
In this tutorial, you modify the f14rtw model so that the generated program
saves the simulation time and system outputs to the file
tout, your generated program logs the same data to a variable
rt_tout. You can change the prefix rt_ to a suffix (_rt), or eliminate
f14rtw.mat.Then
Data Logging
you load the data into the MATLAB workspace and plot simulation time
against one of the outputs. The
f14rtw model should be open and configured
as it was at the end of the previous tutorial.
Data Logging During Simulation
To use the data logging feature:
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
4 Click Data Import/Export in the center pane. The Data Import/Export
pane appears at the right. Its Save to workspace section lets you specify
which outport data is to be saved to the workspace and what variable
names to use for it.
5 Select the Time option. This tells Simulink to save time step data during
simulation as a variable named
tout. You can enter a different name to
distinguish different simulation runs (for example using different step
sizes), but take the default for this tutorial. Selecting Time enables the
Real-Time Workshop code gene rator to create code that logs the simulation
time to a MA T-file.
6 Select the Output option. This tells Simulink to save output signal data
during simulation as a variable named
yout. Selecting Output enables
the Real-Time Workshop code generatortocreatecodethatlogstheroot
Output blocks (Angle of Attack and Pilot G Force) to a MAT-file.
Note The sort order of the yout array is based on the port number of the
Outport blocks, starting with 1. Angle of Attack and Pilot G Force are
logged to
yout(:,1) and yout(:,2),respectively.
3-19
3 Working with the Real-Time Workshop
7 If any other options are enabled, clear them. Set Decimation to 1 and
Format to
®
Software
Array. The figure below shows the dialog.
3-20
8 Click Apply to register your changes.
9 Save the model.
Data Logging
10 Open the Pilot G Force Scope block of the model, then run the model by
choosing Simulation > Start in the model window. The resulting Pilot G
Force scope display is shown below.
MATLAB workspace in MAT-files. At the MATLAB prompt, type:
whos *out
Simulink displays:
NameSizeBytesClass Attributes
tout601x14808double
yout601x29616double
3-21
3 Working with the Real-Time Workshop
12 Verify that Pilot G Force was correctly logged by plotting simulation time
versus that variable. At the M A TLAB prompt, type:
plot(tout,yout(:,2))
The resulting plot is shown below.
®
Software
3-22
Data Logging from Generated Code
In the second part of this tutorial, you build and run a Real-Time Workshop
executable of the
simulation time and outputs you previously examined. Even though you have
already generated code for the
code because you have changed the model by enabling data logging. The
steps below explain this procedure.
To avoid overwriting workspace data with data from simulation runs, the
Real-Time Workshop code generator modifies identifiers for variables logged
by Simulink. You can control these modifications from the Model Explorer:
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
f14rtw model that outputs a MAT-file containing the
f14rtw model, you must now regenerate that
Data Logging
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
4 In the center pane, click Real-Time Workshop.TheReal-Time
Workshop pane appears to the right.
5 Click the Interface tab.
6 Set MAT-file variable name modifier to _rt.Thisaddsthesuffix_rt
to each variable that you selected to be logged in the first part of this
tutorial (
tout, yout).
3-23
3 Working with the Real-Time Workshop
7 Clear the Generate code only check box, if it is currently selected. The
pane should look like this:
®
Software
3-24
8 Click Apply to register your changes.
9 Save
10 To generate code and build an executable, click the Build button.
11 When the build concludes, run the executable with the comm and:
the model.
Data Logging
!f14rtw
12 The program now produces two m essage lines, indicating that the MAT-file
has been written.
** starting the model **
** created f14rtw.mat **
13 Load the MAT-file data created by the executable and look at the workspace
variables from simulation and the generated program by typing:
Note that all a rrays have the same number of elements.
3-25
3 Working with the Real-Time Workshop
14 Observe that the variables tout_rt (ti me) and yout_rt (Pilot G Force
and Angle of Attack) have been loaded from the file. Plot Pilot G Force
as a function of time.
plot(tout_rt,yout_rt(:,2))
The resulting plot is identical to the plot you produced in step 10 of the
previous part of this tutorial:
®
Software
3-26
Code Verification
In this section...
“Tutorial Overview” on page 3-27
“Logging Signals via Scope Blocks” on page 3-27
“Logging Simulation Data” on page 3-29
“Logging Data from the Generated Program” on page 3-29
“Comparing Numerical Results of the Simulation and the Generated
Program” on page 3-31
Tutorial Overview
In this tutorial, you verify the answers computed by code generated from
the
f14rtw model. You do this by capturing two sets of output data and
comparing the sets. You obtain one set by running the Simulink model, and
the other set by executing the Real-Time Workshop generated code.
Code Ve rification
Note To obtain a valid comparison between outputs of the model and the
generated program, you must use the same Solver options and the same
Step size for both the Simulink run and the Real-Time Workshop build
process, and the model must be configured to save simulation time, as shown
in the p receding tutorial.
Logging Signals via Scope Blocks
This example uses Scope blocks (rather than Outport blocks) to log output
data. The
previous tutorial, “Data Logging” on page 3-18.
To configure the Scope blocks to log data,
1 Save the model if any unsaved changes exist.
2 Clear the MATLAB workspace to eliminate the results of previous
simulation runs. At the MATLAB prompt, type:
f14rtw model should be configured as it was at the end of the
3-27
3 Working with the Real-Time Workshop
clear
The clear operation clears not only variables created during previous
simulations, but all workspace variables, some of which are standard
variables that the
3 Reload the model so that the standard workspace variables are redeclared
and initialized:
a Closethemodelbyclickingitswindow’sClose box.
b At the MATLAB prompt, type:
f14rtw
The model reopens, which declares and initializes the standard
workspace variables.
4 Open the Stick Input Scope block and click the Parameters button (the
second button from the left) on the toolbar of the Scope window. The Stick
Input Parameters dialog box opens.
®
Software
f14rtw model requires.
3-28
5 Click the Data History tab of the Stick Input Parameters dialog box.
6 Select the Save data to workspace option and change the Variable
name to
7 Click OK.
Stick_input. The dialog box appears as follows:
The Stick Input parameters now specify that the Stick Input signal to the
Scope block will be logged to the array
Stick_input during simulation.
Code Ve rification
The generated code will log the same signal data to the MAT-file variable
rt_Stick_input during a run of the e xecutable program.
8 Configure the Pilot G Force and Angle of Attack Scope blocks similarly,
using the variable names
9 Save the model.
Pilot_G_force and Angle_of_attack.
Logging Simulation Data
The next step is to run the simulation and log the signal data from the Scope
blocks:
1 Open the Stick Input, Pilot G Force, and Angle of Attack Scope blocks.
2 Run the model. The three Scope plots look like this:
3 Use the
Pilot_
4 Plot one or more of the logged variables against simulation time. For
whos command to show that the array variables Stick_input,
G_force
,andAngle_of_attack have been saved to the workspace.
example,
plot(tout, Stick_input(:,2))
Logging Data from the Generated Program
Because y ou have modified the model, you must rebuild and run the f14rtw
executable to obtain a valid data file:
1 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
3-29
3 Working with the Real-Time Workshop
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
4 Select Real-Time Workshop on the center pane of the Model Explorer,
and click the Interface tab. The Interface pane appears.
5 Set the MAT-file variable name modifier menu to rt_.Thisprefixes
rt_ to each variable that you selected to be logged in the first part of this
tutorial.
6 Click Apply.
7 Save the model.
8 Generate code and build an executable by clicking the Build button. Status
messages in the MATLAB Command Window track the build process.
9 When the build finishes, run the stand-alone program from MATLAB.
®
Software
3-30
!f14rtw
The executing program writes the following messages to the MATLAB
Command Window.
** starting the model **
** created f14rtw.mat **
10 Load the data file f14rtw .mat and observe the workspace variables.
Your Simulink simulations and the generated code have apparently
produced nearly identical output. The next section shows how to quantify
this similarity.
Comparing Numerical Results of the Simulation and
the Generated Program
You have now obtained data from a Simulink run of the model and from a run
of the p rogram generated from the model. It is a simple matter to compare the
f14rtw model output to the Real-Time Workshop results. Your comparison
results may d i ff er from those shown below.
To compare
(generated program output), type:
max(abs(rt_Angle_of_attack-Angle_of_attack))
MATLAB prints:
ans =
1.0e-015 *
Angle_of_attack (simulation output) to rt_Angle_of_attack
00.3331
3-31
3 Working with the Real-Time Workshop
Similarly, the comparison of Pilot_G_force (simulation output) to
rt_Pilot_G_force (generated program output) is:
max(abs(rt_Pilot_G_force-Pilot_G_force))
1.0e-013 *
®
Software
00.4974
Overall agreement is within 10
-13
. The means of residuals are an order of
magnitude smaller. This slight error can be caused by many factors, including
• Different compiler optimizations
• Statement ordering
• Runtime libraries
For example, a function call such as
sin(2.0) might return a slightly
different value depending o n which C library you are using. Such variations
can also cause differences between your results and those shown above.
3-32
FirstLookatGeneratedCode
In this section...
“Tutorial Overview” on page 3-33
“Setting Up the Model” on page 3-33
“Generating Code Without Buffer Optimization” on page 3-35
“Generating Code W ith Buffer Optimization” on page 3-39
“Further Optimization: Expression Folding” on page 3-41
“HTML Code Generation Reports” on page 3-44
Tutorial Overview
In this tutorial, you examine code generated from a simple model to observe
the effects of some of the many Real-Time Workshop code optimization
features.
First Look at Generated Code
Note You can view the code generated from this example using the MATLAB
editor. You can also view the code in the MATLAB Help browser if you enable
the Create HTML report option before generating code. See the following
section, “HTML Code Generation Reports” on page 3-44, for an introduction
to using the HTML report feature.
The source model, example.mdl,isshownbelow.
Setting Up the Model
First, create the model from S imulink library blocks, and set up basic
Simulink and Real-Time Workshop parameters as follows:
3-33
3 Working with the Real-Time Workshop
1 Create a directory, exam ple_ codegen, and make it your working directory:
!mkdir example_codegen
cd example_codegen
2 Create a new model and save it as example.mdl.
3 Add Sine Wave, Gain, and Out1 blocks to your model and connect them as
shown in the preceding diagram. Label the signals as shown.
4 Open Model Explorer by selecting Model Explorer from the model’s
View menu.
5 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
6 Click Configuration (Active) in the left pane.
7 Select Solver in the center pane. The Solver pane appears at the right.
®
Software
3-34
8 In the Solver Options pane:
a Select Fixed-step in the Type field.
b Select Discrete (no continuous states) in the Solver field.
c Specify 0.1 in the Fixed-step size field. (Otherwise, the Real-Time
Workshop code generator posts a warning and supplies a default value
when you generate code.)
9 Click Apply.
10 Click Data Import/Export in the center pane and make sure all check
boxes in the right pane are cleared. Click Apply if you made any changes.
11 Select Real-Time Workshop in the center pane. Under Target Selection
in the right pane, select the default generic real-time (GRT) target
12 Select Generate code only at the bottom of the right pane. This option
causes the Real-Time W orkshop software to generate code and a
then stop at that point, rather than proceeding to invoke
make to compile
grt.tlc.
make file,
and link the code. Note that the label on the Build button changes to
Generate code.
First Look at Generated Code
13 Click Apply.
14 Save the model.
Generating Code Without Buffer Optimization
With buffer optimizations Real-Time Workshop softw are generates code that
reduces memory consumption and execution time. In this tutorial, you disable
the buffer optimizations to see what the nonoptimized generated code looks
like:
1 Select Optimization in the center pane. The Optimization pane appears
at the right. Clear the Signal storage reuse option, as shown below.
Change any other attributes as needed to match the figure.
Note Clearing the Signal storage reuse option disables the following
options:
• Enable local block outputs
• Reuse block outputs
• Eliminate superfluous local variables (Expression folding)
• Minimize data copies between local and global variables
3-35
3 Working with the Real-Time Workshop
®
Software
3-36
2 Click Apply.
3 Selec
4 Select the Create code generation report and Launch report
t Real-Time Workshop > Report in the center pane. The Report
appears at the right.
pane
automatically check boxes. Selecting these check boxes makes the code
generation report display after the build process completes.
5 Select Real-Time Workshop in the center pane, and click Generate
code on the right.
First Look at Generated Code
6 Because you selected the Generate code only option, the Real-Time
Workshop build process does not invoke your
make utility. The code
generation process ends with this message:
### Successful completion of Real-Tim e Workshop
build procedure for model: example
7 The generated code is in the build directory, example_grt_rtw.Thefile
example_grt_rtw/example.c contains the output computation for the
model. You can view thi s file in the code gen era t ion report by clicking
the
example.c link in the left pane.
8 In example.c, find the function example_out put nearthetopofthefile.
The generated C code consists of procedures that implement the algorithms
defined by your Simulink block diagram. The execution engine calls the
procedures in proper succession as time moves forward. The modules that
implement the execution engine and other capabilities are referred to
collectively as the run-time interface modules. See the Real-Time Workshop
User’s Guide for a complete discussion of how the Real-Time Workshop
software interfaces and executes application, system-dependent, and
system-independent modules, in each of the two styles of generated code.
In code generated for
example,thegeneratedexample_output function
implements the actual algorithm for multiplying a sine wave by a gain.
The
example_output function computes the model’s block outputs. The
run-time interface must call
buffer optimizations turned off,
to each block output. These buffers (
members of a global block I/O data structure, called in this code
example_output at every time step. With
example_output assigns unique buffers
rtB.sin_out, rtB.gain_out)are
example_B
anddeclaredasfollows:
/* Block signals (auto st orag e) */
BlockIO_example example_B;
The data type BlockIO_example is defined in example.h as follows:
/* tid is required for a uniform function interface.
* Argument tid is not used in the function. */
UNUSED_PARAMETER(tid);
}
®
Software
3-38
9 In GRT targets such as this, the function example_output is called
by a wrapper function,
MdlOutputs.Inexample.c, find the function
MdlOutputs near the end. It looks like this:
void MdlOutputs(int_T tid)
{
example_output(tid);
}
Note In prev ious releases, MdlOutputs was the actual output function for
code generated by all GRT-configured models. It is now implemented as a
wrapper function to provide greater compatibility among different target
configurations.
First Look at Generated Code
Generating Code With Buffer Optimization
With buffer optimizations, Real-Time Workshop software generates code that
reduces memory consumption and execution time. In this tutorial, you turn
buffer optimizations on and observe how they improve the code. Enable signal
buffer optimizations and regenerate the code as follows:
1 Change your current working directory to example_codegen if you have
not already done so.
2 Select Optimization in the center pane. The Optimization pane appears
at the right. Select the Signal storage reuse option.
3 Note that the following parameters become enabled in the Code
generation section:
• Enable local block outputs
• Reuse block outputs
• Eliminate superfluous local variables (Expression folding)
• Minimize data copies between local and global variables
3-39
3 Working with the Real-Time Workshop
Make sure that Enable local block outputs, Reuse block outputs,
and Minimize data copies between local and global variables are
selected, and that Eliminate superfluous local variables (Expressionfolding) is cleared, as shown below .
®
Software
3-40
You will observe the e ffects of expression folding later in this tutorial. Not
performing expression folding allows you to see the e ffects of the buffer
optimizations.
4 Click Apply to apply the new settings.
First Look at Generated Code
5 Select Real-Time Workshop in the center pane, and click Generate
code on the right.
As before, the Real-Time Workshop software generates code in the
example_grt_rtw directory. The previously generated code is overwritten.
6 View exam ple.c and examine the example_output function.
/* tid is required for a uniform function interface.
* Argument tid is not used in the function. */
UNUSED_PARAMETER(tid);
}
This code is more efficient in terms of memory usage and execution speed. By
eliminating a global variable and a data copy instruction, the data section
is smaller and the code is smaller and faster. The efficiency improvement
gained by sele ctin g Enable local block outputs, Reuse block ou tputs,
and M inimize data copies between local and global variables is more
significant in a large model with many signals.
Further Optimization: Expression Folding
As a final optimization, you turn on expression folding, a code optimization
technique that minimizes the computation of intermediate results and the
use of temporary buffers or variables.
Enable expression folding and regeneratethecodeasfollows:
3-41
3 Working with the Real-Time Workshop
1 Change your current working directory to example_codegen if you have
not already done so.
2 Select Optimization in the center pane. The Optimization pane appears.
3 Select the Eliminate superfluous local variables (Expression
folding) option.
®
Software
3-42
4 Cli
ck Apply.
First Look at Generated Code
5 Select Real-Time Workshop in the center pane, and click Generate
code on the right.
The Real-Time Workshop software generate s code as before.
6 View exam ple.c and examine the function example_out put.
In the previous examples, the Gain block computation was computed in a
separate code statement and the result was stored in a temporary location
before the final output computation.
With Eliminate superfluous local variables (Expression folding)
selected, there is a subtle but significant differe nce in the generated cod e:
the gain computation is incorporated (or folded) directly into the Outport
computation, eliminating the tempora ry location and separate code statement.
This computation is on the last line of the
/* tid is required for a uniform function interface.
* Argument tid is not used in the function. */
UNUSED_PARAMETER(tid);
}
In m any cases, expression folding can incorporate entire model computations
into a single, highly optimized line of code. Expression folding is turned on by
default. Us ing thi s option will improve the efficiency of generated code.
3-43
3 Working with the Real-Time Workshop
®
Software
HTML Code Genera
When the Create c
Workshop > Repor
produced when t
Selecting thi
an HTML file fo
file, in a dire
report autom
generation r
automatical
In the HTML r
include fil
• Global var
• Block head
clicking
to be high
Coder lic
s option causes the Real-Time Workshop software to produce
ctory named
ly displayed.
es, and view relevant documentation. In these reports,
iable instances are hyperlinked to their definitions.
one of these causes the block that generated that section of code
lighted ( this feature requires a Real-Time Workshop Embedded
ense and the ERT target).
ode generation report check box on the Real-Time
t pane is selected, a navigable summary of source files is
he m odel is built. See the figure below.
r each generated source file, plus a summary and an index
html within the build directory. If the Launch
atically option (which is enabled by selecting Create code
eport) is also selected, the HTML summary and index are
eport, you can click links in the report to inspect source and
er comments in source files are hyperlinked back to the model;
tion Reports
3-44
First Look at Generated Code
An HTML report for the example.mdl GRT target is shown below.
One useful feature of HTML reports is the link on the Summary page
identifying Configuration Settings at theTimeofCodeGeneration. Clicking
this opens a read-only Configuration Parameters dialog box through which
you can navigate to identify the settings of every option in place at the time
that the HTML report was generated.
You can refer to HTML reports at any time. To review an existing HTML
report after you have closed its window, use any HTML browser to open the
file
html/model_codgen_rpt.html within your build directory.
3-45
3 Working with the Real-Time Workshop
Note The contents of HTM L reports for different target types vary, and
reports for models with subsystems feature additional information. You
can also v iew HTML-formatted files and text files for generated cod e and
model reference targets within Model Explorer. See “Generating Code for a
Referenced Model” on page 3-60 for more information.
Forfurtherinformationonconfiguringand optimizing generated code, consult
these sections of the Real-Time Workshop User’s Guide documentation:
• “Building Executables” contains overviews of controlling optimizations
and other code generation options.
• “Optimizing Generated Code” has additional details on signal reuse,
expression folding, and other code optimization techniques.
• “Architecture Considerations” has details on the structure and execution
of
model.c files.
®
Software
3-46
Working with External Mode Using GRT
In this section...
“Tutorial Overview” on page 3-47
“Setting Up the Model” on page 3-48
“Building the Target Executable” on page 3-50
“Running the External Mode Target Program” on page 3-54
“Tuning Parameters” on page 3-58
Tutorial Overview
This section provides step-by-step instructions for getting started with
external mode, a very useful environment for rapid prototyping. The tutorial
consists of four parts, each of which depends on completion of the preceding
ones, in order. The four parts correspond to the steps that you follow in
simulating, building, and tuning an actua l real-time application:
Working with External Mode Using GRT
1 Set up the model.
2 Build the target ex ecutable.
3 Run th
4 Tune parameters.
The example presented uses the generic real-time target, and does not require
any hardware other than the computer on which you run the Simulink and
Real-Time Workshop software. The generated executable in this example
runs on the host computer in a separate process from MATL AB and Simulink.
The procedures for building, running, and testing your programs are almost
identical in UNIX and PC environments. The discussion notes differences
where applicable.
For a more thorough description of ext ernal mode, including a discussion of
all the options available, see “Using the External Mode User Interface” in the
Real-Time Workshop documentation.
e external mode target program.
3-47
3 Working with the Real-Time Workshop
®
Software
Setting Up the Mo
In this part of th
a directory call
executable:
1 Create the dir
mkdir ext_mode_example
2 Make ext_mo d
cd ext_mode_example
3 Create a mod
two Gain bl
below. Be s
subsequen
e tutorial, you create a simple model,
ed
ext_mode_example to store the model and the generated
ectory from the MATLAB command line by ty ping
e_example
el in Simulink with a Sine W ave block for the input signal,
ocks in parallel, and two Scope blocks. The model is shown
ure to label the Gain and Scope blocks as shown, so that
t steps will be clear to you.
del
extmode_example,and
your working directory:
3-48
4 Defin
eandassigntwovariables
ws:
follo
A=2;B=3;
A and B in the MATLAB workspace as
Working with External Mode Using GRT
5 Open Gain block A and s et its Gain parameter to the variable A.
6 Similarly, open Gain block B and set its Gain parameter to the variable B.
When the t
mode, you
by assign
the valu
Paramet
7 Verify correct operation of the model. Open the Scope blocks and ru n the
model. When
8 From the File menu, choose Save As.Savethemodelas
extmode_example.mdl.
arget program is built and connected to Simulink in external
can download new gain values to the executing target program
ing new values to workspace variables
A and B,orbyediting
es in the block parameters dialog. You explore this in “Tuning
ers” on page 3-58.
A=2and B=3, the output looks like this.
3-49
3 Working with the Real-Time Workshop
®
Software
Building the Tar
In this section,
for an external m
build the targe
1 Open Model Exp
you set up the model and code generation parameters required
texecutable:
get Executable
ode compatible target program. Then you generate code and
lorer by selecting Model Explorer from the model’s
View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
3 Click Configuration (Active) in the left pane.
4 Select Solv
5 In the Solver Options pane:
a Select Fixed-step in the Type field.
b Select Discrete (no continuous states) in the Solver field.
c Specify 0.1 in the Fixed-step size field. (Otherwise, the Real-Time
er in the c enter pane. The Solver pane appears at the right.
Workshop build process posts a warning and supplies a value when you
generate code.)
3-50
Working with External Mode Using GRT
6 Click Apply. The dialog box appears below. Note that after you click
Apply, the controls you changed again have a white background color.
7 Click Data Import/Export in the center pane, and clear the Time and
Output check boxes. In this tutorial, data is not logged to the workspace orto a MAT-file. Click Apply.
8 Click Optimization in the center pane. Make sure that the Inline
parameters option is not selected. Although external mode supports
inlined parameters, you will not exp lore them in this tutorial. Click Apply
ifyouhavemadeanychanges.
k Real-Time Workshop in the center pane. By default, the generic
9 Clic
l-time (GRT) target is selected on the Real-Time Workshop pane.
rea
ect the Interface tab. The Interface pane appears at the right.
Sel
10 On the Interface pane, select External mode from the Interface
pull-downmenuintheData exchange section. This enables generation
3-51
3 Working with the Real-Time Workshop
of external mode support code and reveals two more sections of controls:
Host/Target interface and Memory management.
11 In the Host/Target interface section, make sure that the value tcpip is
selected for the Transport layer parameter.Thepanenowlookslikethis:
®
Software
3-52
rnal mode supports communication via TCP/IP, serial, and custom
Exte
sport protocols. The MEX-file name field specifies the name of a
tran
-file that implements host and target communications on the host
MEX
e. The default for TCP/IP is
sid
l-Time Workshop software. You can override this default by supplying
Rea
ropriate files. See “Creating a TCP/IP Transport Layer for External
app
ext_comm, a MEX-file provided with the
Working with External Mode Using GRT
Communication” in the Real-Time Workshop documentation for details if
you need to support other transport layers.
The MEX-file arguments field lets you specify arguments, such as a
TCP/IP server port num be r, to be passed to the external interface program.
Note that these arguments are specific to the external interface you are
using. For information on setting thes e arguments, see “MEX-File Optional
Arguments for TCP/IP Transport” and “MEX-File Optional Arguments for
Serial Transport” in the Real-Time Workshop documentation.
This tutorial uses the d efault arguments. Leave the MEX-file arguments
field blank.
12 Click Apply to save the Interface settings.
13 Save the model.
14 Click Real-Time Workshop in the center pane of the Model Explorer.
On the right, make sure that Generate code only is cleared, then click
the Build button to generate code and create the target program. The
content of subsequent messages depends on your compiler and operating
system. The final message is
### Successful completion of Real-Tim e Workshop
build procedure for model: extmode_ex ample
In the next section, you will run the extmode_ex ample executable and use
Simulink as an interactive front end to the running target program.
3-53
3 Working with the Real-Time Workshop
®
Software
Running the Exte
The target execu
In this section,
between Simuli
Note An extern
executable. I
it does not ru
thetimeunit
time in the wo
The Externa
Mode Contr
support ex
you config
displaye
In this tu
Signal &
ure the signals that are viewed and how they are acquired and
d. You can use it to reconfigure signals while the target program runs.
torial, you observe and use the default settings of the External
Triggering dialog box.
table,
you run the target program and establish communication
nk and the target.
al-mode program like
ts execution is not tied to RTOS or a periodic timer interrupt, and
n in real time. The program just runs as fast as possible, and
s it counts off are simulated time units that do not correspond to
rld outside the program.
l Signal & Triggering dialog box (accessed via the External
ol Panel) displays a list of all the blocks in your model that
ternal mode signal monitoring and logging. The dialog box also lets
rnal Mode Ta rget Program
extmode_example, is now in your working directory.
extmode_example is a host-based
3-54
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.