MATLAB-Manual RTW Gs
MATLAB-Manual RTW Gs
MATLAB-Manual RTW Gs
Modeling
Simulation
Implementation
Getting Started
Version 6
How to Contact The MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support
508-647-7000 (Phone)
508-647-7001 (Fax)
Trademarks
MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, and xPC TargetBox
are registered trademarks, and SimBiology, SimEvents, and SimHydraulics are trademarks of
The MathWorks, Inc.
Other product or brand names are 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.
Revision History
July 2002 First printing New for Version 5 (Release 13)
June 2004 Second printing Updated for Version 6.0 (Release 14)
October 2004 Third printing Updated for Version 6.1 (Release 14SP1)
March 2005 Online only Updated for Version 6.2 (Release 14SP2)
September 2005 Fourth printing Updated for Version 6.3 (Release 14SP3)
March 2006 Online Only Updated for Version 6.4 (Release 2006a)
September 2006 Online Only Updated for Version 6.5 (Release 2006b)
Contents
Introduction
1
What Is Real-Time Workshop? . . . . . . . . . . . . . . . . . . . . . . 1-2
Components and Features . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Accelerating Your Development Process . . . . . . . . . . . . . . . 1-7
Building an Application
2
Real-Time Workshop Workflow . . . . . . . . . . . . . . . . . . . . . . 2-2
Mapping Application Requirements to Configuration
Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Adjusting Configuration Settings . . . . . . . . . . . . . . . . . . . . . 2-8
Running Model Advisor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Generating Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Building an Executable Program . . . . . . . . . . . . . . . . . . . . . 2-10
Verifying the Executable Program . . . . . . . . . . . . . . . . . . . . 2-11
Naming and Saving the Configuration Set . . . . . . . . . . . . . 2-11
Documenting the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
v
Automatic Program Building . . . . . . . . . . . . . . . . . . . . . . . 2-15
vi Contents
Working with External Mode Using GRT . . . . . . . . . . . . . 3-37
Setting Up the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37
Building the Target Executable . . . . . . . . . . . . . . . . . . . . . . 3-39
Running the External Mode Target Program . . . . . . . . . . . 3-42
Tuning Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46
Examples
A
Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
vii
Glossary
Index
viii Contents
1
Introduction
What Is Real-Time Workshop? What it is, and what it can do for you
(p. 1-2)
Installing Real-Time Workshop Information on supported compilers
(p. 1-10)
Real-Time Workshop Demos (p. 1-15) Demonstrations that illustrate code
generation capabilities
MathWorks Products Supported by Products for which code can be
Real-Time Workshop (p. 1-16) generated or which otherwise work
with Real-Time Workshop
Help and Documentation (p. 1-18) Locating and using online and
printed help documents
1 Introduction
The process of generating source code from Simulink models using Real-Time
Workshop is shown in the following diagram.
1-2
What Is Real-Time Workshop?
1-3
1 Introduction
1-4
What Is Real-Time Workshop?
1-5
1 Introduction
1-6
What Is Real-Time Workshop?
When you work with tools from The MathWorks, your model represents your
understanding of your system. This understanding is preserved from one
phase of modeling to the next, reducing the need to backtrack. In the event
that rework is necessary in a previous phase, it is easier to step back because
the same model and tools are used throughout.
A spiral design process allows quick iterations between phases, enabling you
to focus on design work. To do this cost-effectively, you need to use tools that
make it easy to move from one phase to another. For example, in a matter
of minutes a control system engineer or a signal processing engineer can
verify that an algorithm works on a real-world rapid prototyping system. The
spiral process lends itself naturally to parallelism in the overall development
process. You can provide early working models to validation and production
1-7
1 Introduction
groups, involving them in your system development process from the start.
Once unit models are prototyped, tested, and ready, they can be packaged into
larger assemblies using Model blocks (the Simulink model referencing facility).
This helps to compress overall development time while increasing quality.
Simulink facilitates the first three phases described in the above figure. You
can build applications using built-in blocks from the Simulink and Stateflow
libraries, incorporate specialized blocks from the Aerospace, Communications,
Signal Processing, and other MathWorks blocksets, and develop your own
blocks by writing S-functions.
The figure below illustrates where products from The MathWorks, including
Real-Time Workshop, help you in your development process.
1-8
What Is Real-Time Workshop?
Early in the design process, you use MATLAB and Simulink to help you
formulate your objectives, problems, and constraints to create your initial
design. Real-Time Workshop speeds up models by enabling high-speed
simulations via Simulink Accelerator and by model referencing, which
includes models in other models as blocks.
After you have a functional model, you might need to tune your models
parameters. You can do this quickly using the Real-Time Workshop Rapid
Simulation Target for Monte Carlo and other batch-oriented simulations
(varying coefficients over many simulations).
Once you have tuned your model, you can move into system development
testing by exercising your model on a rapid prototyping system, such as
Real-Time Windows Target or xPC Target. With a rapid prototyping target,
you connect your model to your physical system. This lets you locate design
flaws and modeling errors quickly.
After you create your prototype system and verify its outputs, you can use
Real-Time Workshop Embedded Coder to deploy generated code on your
custom target. The signal monitoring and parameter tuning capabilities
enable you to easily integrate the embedded code into a production
environment equipped with debugging and upgrade capabilities. See the
Real-Time Workshop Embedded Coder documentation for an overview of this
process. First, however, see Real-Time Workshop Workflow on page 2-2 for a
process view of using Real-Time Workshop.
1-9
1 Introduction
If you customize your installation, the installer displays a dialog box that lets
you select the MATLAB products to install. You can select and install only
products for which you are licensed.
Additional
Licensed Product Prerequisite Products Information
Simulink MATLAB 7 (Release 14) Allows installation of
Simulink
Real-Time Workshop Simulink 6 (Release 14) Requires Borland C,
LCC, Visual C/C++
Professional, or Watcom
C compiler to create
MATLAB MEX-files or
other executables on
your platform
Real-Time Workshop Real-Time Workshop 6
Embedded Coder
If you experience installation difficulties and have Web access, use the
resources available on the MathWorks Web site Installation and Licensing
page at http://www.mathworks.com/support/install/.
1-10
Installing Real-Time Workshop
For more about third party compilers, see Choosing and Configuring
a Compiler in the Real-Time Workshop documentation. For details on
supported compiler versions, see
http://www.mathworks.com/support/tech-notes/1600/1601.shtml
Borland
Intel
LCC (use the version that ships with MATLAB)
Microsoft Visual C/C++ Professional
Watcom
1-11
1 Introduction
Real-Time Workshop uses the default optimization level for each supported
compiler. You can usually work around problems caused by compiler
optimizations by lowering the optimization level of the compiler or by turning
off optimizations. Refer to your compilers documentation for information
on how to do this.
Borland
Make sure that your Borland environment variable is defined and correctly
points to the directory in which your Borland compiler resides. To check this,
type
set BORLAND
at the DOS prompt. Check the return from this command to see whether the
BORLAND environment variable is defined and points to the Borland compiler.
If the BORLAND environment variable is not defined, you must define it to point
to where you installed your Borland compiler. Launch the System control
panel, select the Advanced tab, click Environment Variables, and define
BORLAND to be the path to your compiler.
Intel
Real-Time Workshop includes support for the Intel compiler, which requires
Microsoft Visual C/C++. To use the Intel compiler when compiling Real-Time
Workshop generated code, use mex -setup and select the Intel compiler.
1-12
Installing Real-Time Workshop
2 Edit the new mexopts.bat file and replace %MSVCDir% with the root
directory of your Microsoft Visual C/C++ installation.
LCC
The freeware LCC C compiler is shipped with MATLAB, and is
installed with the product. If you want to use LCC to build programs
generated by Real-Time Workshop, use the version that is currently
shipped with the product. Information about LCC is available at
http://www.cs.virginia.edu/~lcc-win32/.
mex -setup
to define the environment for Visual C/C++. Note that only the Professional
version is supported. On Windows platforms, S-function targets and model
reference simulation targets are generated as MEX-files via the MATLAB
mex command. The compiler support for these targets is thus limited to that
provided by mex.
Watcom
The Watcom C compiler is no longer available from the manufacturer.
Development of this compiler has been taken over by the Open Watcom
organization (http://www.openwatcom.org), which has released a binary
patch update (11.0c) for existing Watcom C/C++ and Fortran customers.
Real-Time Workshop continues to ship with Watcom-related target
configurations. However, this policy may be subject to change in the future.
1-13
1 Introduction
Make sure that your Watcom environment variable is defined and correctly
points to the directory in which your Watcom compiler resides. To check this,
type
set WATCOM
at the DOS prompt. Check the return from this command to see whether the
WATCOM environment variable is defined and points to the Watcom compiler.
If the WATCOM environment variable is not defined, you must define it to point
to where you installed your Watcom compiler. Launch the System control
panel, click the Advanced tab, click Environment Variables, and define
WATCOM to be the path to your compiler.
1-14
Real-Time Workshop Demos
rtwdemos
at the MATLAB prompt. You can also find Real-Time Workshop demos by
navigating to Real-Time Workshop, (found under Simulink) in the Demos
pane of the Help browser, and clicking the Feature Tour example.
1-15
1 Introduction
1-16
MathWorks Products Supported by Real-Time Workshop
1-17
1 Introduction
Online at http://www.mathworks.com
Through the MATLAB Help browser
As PDF documents that you can view online or print
1-18
Help and Documentation
Online Documentation
Access to the online information for Real-Time Workshop is through MATLAB
or from the MathWorks Web site at http://www.mathworks.com/support/.
Click the Documentation link.
To access the documentation with the MATLAB Help browser, use the
following procedure:
1 In the MATLAB window, click Help > Full product family help, or click
the ? icon on the toolbar.
The Help browser displays the Real-Time Workshop roadmap page in the
right pane. Click any link there, or click the + sign to the left of the book
icon in the left pane to reveal the table of contents. When you do so, the
+ changes to a -.
You can customize output from Real-Time Workshop at the block, target, and
makefile levels. For advanced uses, you might have to prepare or modify
Target Language Compiler files, as explained in the Target Language
Compiler documentation.
1-19
1 Introduction
1-20
2
Building an Application
This chapter expands the high-level discussion of code generation and the
build process given in Chapter 1, Introduction. It provides a foundation of
understanding for tutorial exercises in Chapter 3, Working with Real-Time
Workshop.
8 Verify that the generated program produces results that are equivalent
to those of your model simulation.
2-2
Real-Time Workshop Workflow
The following figure shows these steps in a flow diagram. Sections following
the figure discuss the steps in more detail.
Configuration Yes
Run Model Advisor Requires
Tuning?
No
Generate Code
No
Code OK?
Yes
BuildExecutable Program
Document Project
Done
2-3
2 Building an Application
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. Real-Time Workshop automatically adjusts the available
configuration parameters and their default settings based on your target
selection. For example, the preceding dialog box display shows default
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 configuration for your application.
2-4
Real-Time Workshop Workflow
Once you have answered these questions, review the following table,
which summarizes the impact of each configuration option on debugging,
traceability, efficiency, and safety considerations, and indicates the default
(factory) configuration settings for the GRT target. For additional details,
click the links in the Configuration Parameter column.
Configuration
Parameter Debugging Traceability Efficiency Safety Default
Solver
Stop time No impact No impact No No impact 10.0 seconds
impact
Type No impact No impact No No impact Variable step
impact
Data Import/Export
Load from N/A N/A N/A N/A Clear
workspace
Save to Maybe Maybe Clear No impact Set
workspace
2-5
2 Building an Application
Configuration
Parameter Debugging Traceability Efficiency Safety Default
Implement No impact No impact Set No impact Set
logic signals as
Boolean data
(versus double)
Inline Clear Set Set No impact Clear
parameters
Conditional No impact Set Set No impact Set
input branch
execution
Signal storage Clear Clear Set No impact Set
reuse
Application No impact No impact Finite Inf Inf
lifespan (days) value
Enable local Clear No impact Set No impact Set
block outputs
Ignore integer Clear No impact Set Clear Clear
downcasts in
fold expressions
Eliminate Clear No impact Set No impact Set
superfluous
temporary
variables
(Expression
folding)
Loop unrolling No impact No impact >0 No impact 5
threshold
Reuse block Clear Clear Set No impact Set
outputs
Inline invariant Clear Clear Set No impact Set
signals
2-6
Real-Time Workshop Workflow
Configuration
Parameter Debugging Traceability Efficiency Safety Default
Hardware Implementation
Number of bits No impact No impact Target No impact 8, 16, 32, 32
specific
Real-Time Workshop
Generate HTML Set Set No No impact Clear
report impact
Real-Time Workshop: Comments
Include Set Set No No impact Set
comments impact
Simulink block Set Set No No impact Set
comments impact
Show eliminated Set Set No No impact Clear
blocks impact
Verbose Set Set No No impact Clear
comments for impact
Simulink Global
storage class
Real-Time Workshop: Symbols
Maximum Set >30 No No impact 31
identifier length impact
Real-Time Workshop: Debug
Verbose builds Set No impact No Set Set
impact
Real-Time Workshop: Interface
Target floating No impact No impact Set No impact ANSI-C
point math
environment
2-7
2 Building an Application
Configuration
Parameter Debugging Traceability Efficiency Safety Default
Utility function Shared Shared Shared No impact Auto*
generation
MAT-file variable No impact No impact No No impact rt_
name modifier impact
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 Configuration Parameter Reference in
the Real-Time Workshop documentation.
2-8
Real-Time Workshop Workflow
One way of starting the Model Advisor is to select Tools > Model Advisor in
your model window. A new window appears listing specific diagnostics you
can selectively enable or disable. Some examples of the diagnostics follow:
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 part of a sample report from Model Advisor.
For more information on using the Model Advisor, see Using the Model
Advisor in the Real-Time Workshop documentation.
2-9
2 Building an Application
Generating Code
After fine-tuning your model and its parameter settings, you are ready to
generate code. Typically, the first time through the process of applying
Real-Time Workshop for an application, you want to generate code without
going on to compile and link it into an executable program. Some reasons
for doing this include the following:
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). Real-Time Workshop 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.
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 Model 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-10.
For a more detailed discussion of the code generation process, see Automatic
Program Building on page 2-15 and Build Process on page 2-17. For
details on the Generate code only option, see Generate Code Only in the
Real-Time Workshop documentation.
2-10
Real-Time Workshop Workflow
One way of initiating a build is to click the Build button. Real-Time Workshop
responds by
For a more detailed discussion of the build process, see Automatic Program
Building on page 2-15 and Build Process on page 2-17.
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.
2-11
2 Building an Application
1 Open Model Explorer while your model is still open by selecting Model
Explorer from the View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
1 Open Model Explorer while your model is still open, by selecting Model
Explorer from the View menu.
2 In the Model Hierarchy pane, click the + sign preceding the model name
to reveal its components.
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
the yellow gear icon on the toolbar:
2-12
Real-Time Workshop Workflow
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.
2-13
2 Building an Application
To get started with generating a code generation report, see the demo
rtwdemo_codegenrpt and tutorial Documenting a Code Generation Project
on page 3-59. For details on using the Report Generator, see the MATLAB
Report Generator documentation.
2-14
Automatic Program Building
The following figure illustrates the complete process. The box labeled
Automated build process highlights portions of the process that Real-Time
Workshop executes.
The M-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 portion of the Real-Time Workshop build
process. By default, the name of the M-file command is make_rtw; Real-Time
Workshop will invoke this M-file for most targets. Any options specified in
this field will be passed into the makefile-based build process. In some cases,
2-15
2 Building an Application
targets will customize the make_rtw command. However, the arguments used
by the function must be preserved.
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 open, you need to make sure gcs is the model you
want to build. Also, some target environments supply a Make command
in the Configuration Parameters dialog box that is not make_rtw. Finally,
models containing Model blocks do not build by using make_rtw directly.
To build (or generate code for) a model as currently configured from the
MATLAB Command Window, use one of the following rtwbuild commands.
rtwbuild modelname
rtwbuild('modelname')
2-16
Build Process
Build Process
Real-Time Workshop generates C code only or generates the C code and
produces an executable image, depending on the level of processing you
choose. By default, a Build button appears on the Real-Time Workshop
pane of the Configuration Parameters dialog box. This button completes
the entire build process and an executable image results. If you select the
Generate code only check box to the left of the button, the button label
changes to Generate code.
When you click the Build or Generate code button, Real-Time Workshop
performs the following build process. If Real-Time Workshop detects code
generation constraints for your model, it issues warning or error messages.
2-17
2 Building an Application
Model Compilation
The build process begins with Simulink compiling the block diagram. During
this stage, Simulink
2-18
Build Process
model.rtw files are similar in format to Simulink model (.mdl) files, but are
used only for automated code generation. For a general description of the
model.rtw file format, see the Target Language Compiler documentation.
Code Generation
During code generation, Real-Time Workshop uses the Target Language
Compiler (TLC) and a supporting TLC function library to transform the
intermediate model description stored in model.rtw into target-specific code.
The TLC
The system target file is the entry point or main file. You select it from
those available on the MATLAB path with the system target file browser or
you can type the name of any such file on your system prior to building.
For blocks in the Simulink model, there is a corresponding target file that
is either dynamically generated or statically provided.
2-19
2 Building an Application
You can fully customize your build process by modifying an existing template
makefile or providing your own template makefile.
2-20
Build Process
2-21
2 Building an Application
To omit this stage of processing, select the Generate code only option on
the Real-Time Workshop pane of the Configuration Parameters dialog
box. You can then cross-compile your code and download it to your target
hardware. Interacting with the Build Process in the Real-Time Workshop
documentation discusses the options that control whether or not the build
creates an executable image.
Real-Time Workshop derives many of the files from the model.mdl file you
create with Simulink. You can think of the model.mdl file as a very high-level
programming language source file.
2-22
Build Process
model.rtw
An ASCII file, representing the compiled model, generated by the
Real-Time Workshop build process. This file is analogous to the object file
created from a high-level language source program. By default, Real-Time
Workshop deletes this file when the build process is complete. However,
you can choose to retain the file for inspection.
model.c
C source code that corresponds to model.mdl and is generated by the
Target Language Compiler. This file contains
- Include files model.h and model_private.h
- All data except data placed in model_data.c
- Model-specific scheduler code
- Model-specific solver code
- Model registration code
- Algorithm code
- Optional GRT wrapper functions
model.h
Defines model data structures and a public interface to the model entry
points and data structures. Also provides an interface to the real-time
model data structure (model_rtM) via access macros. model.h is included
by subsystem .c files in the model. It includes
- Exported Simulink data symbols
- Exported Stateflow machine parented data
- Model data structures, including rtM
- Model entry point functions
model_private.h
Contains local define constants and local data required by the model and
subsystems. This file is included by the generated source files in the model.
2-23
2 Building an Application
2-24
Build Process
model.mk
Customized makefile generated by the Real-Time Workshop build process.
This file builds an executable program file.
rtmodel.h
Contains #include directives required by static main program modules
such as grt_main.c and grt_malloc_main.c. Since these modules are
not created at code generation time, they include rt_model.h to access
model-specific data structures and entry points. If you create your own
main program module, take care to include rtmodel.h.
rtwtypes.h
For GRT targets, a header file that includes simstruc_types.h, which, in
turn, includes tmwtypes.h. For Real-Time Workshop Embedded Coder
ERT targets, rtwtypes.h itself provides the necessary defines, enums,
and so on, instead of including tmwtypes.h and simstruc_types.h. The
rtwtypes.h file generated for ERT is an optimized (reduced) file based
on the settings provided with the model that is being built. See Header
Dependencies When Interfacing Legacy/Custom Code with Generated
Code in the Real-Time Workshop documentation for more information.
rt_nonfinite.c
C source file that declares and initializes global nonfinite values for inf,
minus inf, and nan. Nonfinite comparison functions are also provided. This
file is always generated for GRT-based targets and optionally generated
for other targets.
rt_nonfinite.h
C header file that defines extern references to nonfinite variables and
functions. This file is always generated for GRT-based targets and
optionally generated for other targets.
rtw_proj.tmw
File Real-Time Workshop generated for the make utility to use to determine
when to rebuild objects when the name of the current Real-Time Workshop
project changes
2-25
2 Building an Application
model.bat
Windows batch file used to set up the appropriate compiler environment
and invoke the make command
modelsources.txt
List of additional sources that should be included in the compilation.
Optional files:
model_targ_data_map.m
M-file used by external mode to initialize the external mode connection
model_dt.h
C header file used for supporting external mode. Declares structures that
contain data type and data type transition information for generated model
data structures.
subsystem.c
C source code for each noninlined nonvirtual subsystem or copy thereof
when the subsystem is configured to place code in a separate file
subsystem.h
C header file containing exported symbols for noninlined nonvirtual
subsystems. Analogous to model.h.
model_capi.h
An interface header file between the model source code and the generated
C-API. See C-API for Interfacing with Signals and Parameters in the
Real-Time Workshop Users Guide for more information.
model_capi.c
C source file that contains data structures that describe the models signals
and parameters without using external mode. See C-API for Interfacing
with Signals and Parameters in the Real-Time Workshop Users Guide
for more information.
2-26
Build Process
rt_sfcn_helper.h, rt_sfcn_helper.c
Header and source files providing functions needed by noninlined
S-functions in a model. The functions rt_CallSys, rt_enableSys, and
rt_DisableSys are used when noninlined S-functions call downstream
function call subsystems.
In addition, when you select the Generate HTML report option, Real-Time
Workshop generates a set of HTML files (one for each source file plus a
model_contents.html index file) in the html subdirectory within your build
directory.
The above source files have dependency relationships, and there are
additional file dependencies that you might need to take into account. These
are described in Generated Source Files and File Dependencies in the
Real-Time Workshop documentation.
2-27
2 Building an Application
for simulation code, some Real-Time Workshop code, utility code shared
between models, and other files. Of particular importance to Real-Time
Workshop users are
- Model reference Real-Time Workshop target files
slprj/target/modelName/
- MAT-files used during code generation of model reference
Real-Time Workshop target and stand-alone code generation
slprj/target/modelName/tmwinternal
- Shared (fixed-point) utilities
slprj/target/_sharedutils
See Working with Project Directories on page 3-58 for more information
on organizing your files with respect to project directories.
The build directory always contains the generated code modules model.c,
model.h, and the generated makefile model.mk.
Depending on the target, code generation, and build options you select, the
build directory might also include
model.rtw
Object files (.obj or .o)
Code modules generated from subsystems
HTML summary reports of files generated (in the html subdirectory)
TLC profiler report files
Block I/O and parameter tuning information file (model_capi.c)
C-API code for parameters and signals
Real-Time Workshop project (model.tmw) files
2-28
3
This chapter provides hands-on tutorials that help you get started generating
code with Real-Time Workshop, as quickly as possible. It includes the
following topics:
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 basic familiarity with MATLAB and Simulink. You
should also read Chapter 2, Building an Application, 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-2
Demonstration Model: rtwdemo_f14
matlabroot/toolbox/simulink/simdemos/aerospace
The model simulates the pilots stick input with a square wave having a
frequency of 0.5 radians per second and an amplitude of 1. The system
outputs are the aircraft angle of attack and the G forces experienced by the
pilot. The input and output signals are visually monitored by Scope blocks.
3-3
3 Working with Real-Time Workshop
2 Create the working directory from the MATLAB command line by typing:
mkdir f14example
cd f14example
rtwdemo_f14
5 In the model window, choose File > Save As. Navigate to your working
directory, f14example. Save a copy of the rtwdemo_f14 model as
f14rtw.mdl.
3-4
Building a Generic Real-Time Program
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-48 describes
navigating project directory structures in Model Explorer.
Note Real-Time Workshop can generate code for models using variable-step
solvers for rapid simulation (rsim) and S-function targets only. A Simulink
license is checked out when rsim targets execute. See Licensing Protocols
for Simulink Solvers in RSim Executables in the Real-Time Workshop
documentation for details.
1 In the f14rtw model window, choose View > Model Explorer. The Model
Explorer opens.
3 Click Configuration (Active) in the left pane, then click Solver in the
center pane. The Solver pane appears at the right.
4 Enter the following parameter values on the Solver pane (some may
already be set):
Stop Time: 60
3-5
3 Working with Real-Time Workshop
Solver options:
Type: Fixed-step
Solver: ode5 (Dormand-Prince)
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 double-check that what you set is what
you intended. When you apply your changes, the background color reverts
to white.
6 Save the model. Simulation parameters persist with the model, for use in
future sessions.
Note Some of the steps in this section do not require you to make changes.
They are included to help you familiarize yourself with the Real-Time
Workshop user interface. As you step through the dialog boxes, place the
mouse pointer on any item of interest to see a tooltip describing its function.
3-6
Building a Generic Real-Time Program
To specify the desired target configuration, you choose a system target file, a
template makefile, and a make command.
In these exercises (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 designed to build a stand-alone
executable program that runs on your workstation.
2 Click the General tab to activate the pane that controls target selection.
3 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,
Real-Time Workshop 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 Real-Time Workshop Embedded Coder.
3-7
3 Working with Real-Time Workshop
5 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.
6 Select the Symbols tab of the Real-Time Workshop pane. The options
on this pane control the look and feel of generated code. Only one option
exists for the GRT target, Maximum identifier length (the number of
3-8
Building a Generic Real-Time Program
characters allowed in variable and other symbol names). The default for
this option is 31, as shown below.
7 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.
8 Make sure that the Generate code only option is not checked, as shown
at the bottom of the preceding figure.
3-9
3 Working with Real-Time Workshop
1 In the Real-Time Workshop pane, select the General tab, then click the
Build button to start the build process.
2 To observe the contents of the working directory after the build, type the
dir command from the Command Window.
dir
. .. f14rtw.exe f14rtw.mdl f14rtw_grt_rtw slprj
!f14rtw
The ! character passes the command that follows it to the operating system,
which runs the stand-alone f14rtw program.
3-10
Building a Generic Real-Time Program
No data is output.
dir f14rtw_grt_rtw
The build directory includes these generated files (not in this order):
File Description
f14rtw.c Stand-alone C code that implements the model
rt_nonfinite.c Function to initialize nonfinite types (Inf, NaN,
and -Inf)
f14rtw.h An include header file containing definitions of
parameters and state variables
f14rtw_types.h Forward declarations of data types used in the
code
f14rtw_private.h Header file containing common include
definitions
rt_nonfinite.h Imported declarations for nonfinite types
rtwtypes.h Static include file for Simulink simstruct data
types; some embedded targets tailor this file to
reduce overhead, but GRT does not
3-11
3 Working with Real-Time Workshop
File Description
rtmodel.h Master header file for including generated code
in the static main program (its name never
changes, and it simply includes f14rtw.h)
f14rtw.mk Makefile generated from a template for the
GRT target
The build directory also contains other files used in the build process, such
as the object (.obj) files, a batch control file (f14rtw.bat), and a marker
file (rtw_proj.tmw). The build directory contains a subdirectory, html,
containing HTML files that report on the build process and show the code
that it generated.
3-12
Data Logging
Data Logging
The 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, where model is the name of your model. In this tutorial, data
generated by the model f14rtw.mdl is logged to the file f14rtw.mat. Refer
to Building a Generic Real-Time Program on page 3-4 for instructions on
setting up f14rtw.mdl in a working directory if you have not done so already.
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 model to
save output to the MATLAB workspace. For each workspace return variable
you define and enable, Real-Time Workshop defines a parallel MAT-file
variable. For example, if you save simulation time to the variable tout, your
generated program logs the same data to a variable named rt_tout. You can
change the prefix rt_ to a suffix (_rt), or eliminate 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). Real-Time Workshop 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 f14rtw.mat. Then
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 exercise.
3-13
3 Working with Real-Time Workshop
1 From the View menu of the f14rtw model window, select Model Explorer.
The Model Explorer opens.
4 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 exercise. Selecting Time enables
Real-Time Workshop to generate code that logs the simulation time to
a MAT-file.
5 Select the Output option. This tells Simulink to save time step data
during simulation as a variable named yout. Selecting Output enables
Real-Time Workshop to generate code that logs the root 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-14
Data Logging
6 If any other options are enabled, clear them. Set Decimation to 1 and
Format to Array. The figure below shows the dialog.
9 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.
3-15
3 Working with Real-Time Workshop
10 Verify that the simulation time and outputs have been saved to the
MATLAB workspace in MAT-files. At the MATLAB prompt, type:
whos *out
Simulink displays:
11 Verify that Pilot G Force was correctly logged by plotting simulation time
versus that variable. At the MATLAB prompt, type:
plot(tout,yout(:,2))
3-16
Data Logging
1 In the model window, choose View > Model Explorer. The Model
Explorer opens.
4 Set MAT-file variable name modifier to _rt. This adds the suffix _rt
to each variable that you selected to be logged in the first part of this
exercise (tout, yout).
5 Clear the Generate code only check box, if it is currently selected. The
pane should look like this:
3-17
3 Working with Real-Time Workshop
9 When the build concludes, run the executable with the command:
!f14rtw
10 The program now produces two message lines, indicating that the MAT-file
has been written.
11 Load the MAT-file data created by the executable and look at the workspace
variables from simulation and the generated program by typing:
load f14rtw.mat
whos tout* yout*
Simulink displays:
3-18
Data Logging
12 Observe that the variables tout_rt (time) 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 exercise:
3-19
3 Working with Real-Time Workshop
Code Verification
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 model itself in Simulink, and the
other set by executing code generated from the model by Real-Time Workshop.
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 preceding tutorial.
clear
The clear operation clears not only variables created during previous
simulations, but all workspace variables, some of which are standard
variables that the f14rtw model requires.
3-20
Code Verification
3 Reload the model so that the standard workspace variables are redeclared
and initialized:
a Close the model by clicking its windows Close box.
f14rtw
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.
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 Stick_input. The dialog box appears as follows:
7 Click OK.
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.
The generated code will log the same signal data to the MAT-file variable
rt_Stick_input during a run of the executable program.
3-21
3 Working with Real-Time Workshop
8 Configure the Pilot G Force and Angle of Attack Scope blocks similarly,
using the variable names Pilot_G_force and Angle_of_attack.
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 whos command to show that the array variables Stick_input,
Pilot_G_force, and Angle_of_attack have been saved to the workspace.
4 Plot one or more of the logged variables against simulation time. For
example,
plot(tout, Stick_input(:,2))
3-22
Code Verification
2 Set the MAT-file variable name modifier menu to rt_. This prefixes
rt_ to each variable that you selected to be logged in the first part of this
exercise.
3 Click Apply.
5 Generate code and build an executable by clicking the Build button. Status
messages in the MATLAB Command Window track the build process.
6 When the build finishes, run the stand-alone program from MATLAB.
!f14rtw
7 Load the data file f14rtw.mat and observe the workspace variables.
load f14rtw
whos rt*
Name Size Bytes Class
3-23
3 Working with Real-Time Workshop
figure('Name','Stick_input')
plot(rt_tout,rt_Stick_input(:,2))
figure('Name','Pilot_G_force')
plot(rt_tout,rt_Pilot_G_force(:,2))
figure('Name','Angle_of_attack')
plot(rt_tout,rt_Angle_of_attack(:,2))
3-24
Code Verification
max(abs(rt_Angle_of_attack-Angle_of_attack))
MATLAB prints:
ans =
1.0e-015 *
0 0.3331
max(abs(rt_Pilot_G_force-Pilot_G_force))
1.0e-013 *
0 0.6395
For example, a function call such as sin(2.0) might return a slightly different
value depending on which C library you are using. Such variations can also
cause differences between your results and those shown above.
3-25
3 Working with Real-Time Workshop
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-34, for an introduction
to using the HTML report feature.
!mkdir example_codegen
cd example_codegen
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 From the models View menu, choose Model Explorer. The Model
Explorer appears.
3-26
First Look at Generated Code
7 Click Apply.
8 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.
10 Select Generate code only at the bottom of the right pane. This option
causes Real-Time Workshop to generate code and a make file, then stop at
that point, rather than proceeding to invoke make to compile and link the
code. Note that the label on the Build button changes to Generate code.
11 Click Apply.
3-27
3 Working with Real-Time Workshop
2 Click Apply.
3 Select Real-Time Workshop in the center pane, and click Generate code
on the right.
6 In example.c, find the function example_output near the top of the file.
3-28
First Look at Generated Code
BlockIO_example example_B;
The output code (without comments) accesses fields of this global structure,
as shown below:
example_B.sin_out = example_P.SineWave_Amp *
sin(example_P.SineWave_Freq * example_M->Timing.t[0] +
example_P.SineWave_Phase) + example_P.SineWave_Bias;
example_Y.Out1 = example_B.gain_out;
}
3-29
3 Working with Real-Time Workshop
example_output(tid);
}
Note In previous 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.
In the steps below, you turn buffer optimizations on and observe how these
optimizations improve the code.
3-30
First Look at Generated Code
2 Note that three controls become enabled in the Code generation section:
Enable local block outputs, Reuse block outputs, and Eliminate
superfluous temporary variables (Expression folding). Make sure
that the first two options are selected, and Eliminate superfluous
temporary variables (Expression folding) is not selected, as shown
below.
You will observe the effects of expression folding later in this tutorial. Not
performing expression folding allows you to see the effects of the block
output optimizations.
4 Select Real-Time Workshop in the center pane, and click Generate code
on the right.
3-31
3 Working with Real-Time Workshop
real_T rtb_sin_out;
real_T rtb_gain_out;
rtb_sin_out = example_P.SineWave_Amp *
sin(example_P.SineWave_Freq * example_M->Timing.t[0] +
example_P.SineWave_Phase) + example_P.SineWave_Bias;
example_Y.Out1 = rtb_gain_out;
}
3-32
First Look at Generated Code
3 Click Apply.
4 Select Real-Time Workshop in the center pane, and click Generate code
on the right.
3-33
3 Working with Real-Time Workshop
real_T rtb_sin_out;
rtb_sin_out = example_P.SineWave_Amp *
sin(example_P.SineWave_Freq * example_M->Timing.t[0] +
example_P.SineWave_Phase) + example_P.SineWave_Bias;
In the HTML report, you can click links in the report to inspect source and
include files, and view relevant documentation. In these reports,
3-34
First Look at Generated Code
One useful feature of HTML reports is the link on the Summary page
identifying Configuration Settings at the Time of Code Generation. 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.
Note The contents of HTML reports for different target types vary, and
reports for models with subsystems feature additional information. You
can also view HTML-formatted files and text files for generated code and
model reference targets within Model Explorer. See Generating Code for a
Referenced Model on page 3-48 for more information.
3-35
3 Working with Real-Time Workshop
3-36
Working with External Mode Using GRT
The example presented uses the generic real-time target, and does not require
any hardware other than the computer on which you run Simulink and
Real-Time Workshop. The generated executable in this example runs on the
host computer in a separate process from MATLAB 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.
mkdir ext_mode_example
cd ext_mode_example
3-37
3 Working with Real-Time Workshop
3 Create a model in Simulink with a Sine Wave block for the input signal, two
Gain blocks in parallel, and two Scope blocks. The model is shown below.
Be sure to label the Gain and Scope blocks as shown, so that subsequent
steps will be clear to you.
A = 2; B = 3;
5 Open Gain block A and set its Gain parameter to the variable A as shown
below.
6 Similarly, open Gain block B and set its Gain parameter to the variable B.
3-38
Working with External Mode Using GRT
7 Verify correct operation of the model. Open the Scope blocks and run the
model. When A = 2 and B = 3, the output looks like this.
8 From the File menu, choose Save As. Save the model as
extmode_example.mdl.
1 From the models View menu, choose Model Explorer. The Model
Explorer appears.
3-39
3 Working with Real-Time Workshop
4 Click Apply. The dialog box appears below. Note that after you click
Apply, the controls you changed again have a white background color.
5 Click Data Import/Export in the center pane, and clear the Time and
Output check boxes. In this exercise, data is not logged to the workspace
or to a MAT-file.
6 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 explore them in this exercise.
8 In the Interface pane, select External mode from the Interface pulldown
menu in the Data exchange section. This enables generation of external
mode support code and reveals two more sections of controls: Host/Target
interface and Memory management.
3-40
Working with External Mode Using GRT
This exercise uses the default arguments. Leave the MEX-file arguments
field blank.
3-41
3 Working with Real-Time Workshop
In the next section, you will run the extmode_example executable and use
Simulink as an interactive front end to the running target program.
The External Signal & Triggering dialog box (accessed via the External
Mode Control Panel) displays a list of all the blocks in your model that
support external mode signal monitoring and logging. The dialog box also lets
you configure the signals that are viewed and how they are acquired and
displayed. You can use it to reconfigure signals while the target program runs.
3-42
Working with External Mode Using GRT
In this exercise, you observe and use the default settings of the External
Signal & Triggering dialog box.
1 From the Tools menu of the block diagram, select External Mode
Control Panel, which lets you configure signal monitoring and data
archiving. It also lets you connect to the target program and start and stop
execution of the model code.
The top three buttons are for use after the target program has started. The
two lower buttons open separate dialog boxes:
The Signal & triggering button opens the External Signal & Triggering
dialog box. This dialog box lets you select the signals that are collected
from the target system and viewed in external mode. It also lets you
select a signal that triggers uploading of data when certain signal
conditions are met, and define the triggering conditions.
The Data archiving button opens the External Data Archiving dialog
box. Data archiving lets you save data sets generated by the target
program for future analysis. This example does not use data archiving.
See Data Archiving in the Real-Time Workshop documentation for
more information.
The External Signal & Triggering dialog box opens. The default
configuration of the External Signal & Triggering dialog box is designed
to ensure that all signals are selected for monitoring. The default
configuration also ensures that signal monitoring will begin as soon as
3-43
3 Working with Real-Time Workshop
the host and target programs have connected. The figure below shows
the default configuration for extmode_example.
2 In the External Mode Control Panel, click the Signal & triggering
button.
3 Make sure that the External Signal & Triggering dialog box is set to the
defaults as shown:
Select all check box is selected. All signals in the Signal selection list
are marked with an X in the Block column.
Trigger Source: manual
Trigger Mode: normal
Duration: 1000
Delay: 0
Arm when connect to target: selected
Click Close, and then close the External Mode Control Panel.
3-44
Working with External Mode Using GRT
4 To run the target program, you must open a command prompt window
(on UNIX systems, an Xterm window). At the command prompt, change
to the ext_mode_example directory that you created in step 1. The target
program is in this directory.
cd ext_mode_example
Note On Windows platforms, you can also use the bang command (!)
in the MATLAB Command Window (note that the trailing ampersand is
required): !extmode_example -tf inf -w &
The target program begins execution. Note that the target program is in a
wait state, so no activity occurs in the MATLAB Command Window.
The -tf switch overrides the stop time set for the model in Simulink. The
inf value directs the model to run indefinitely. The model code runs until
the target program receives a stop message from Simulink.
The -w switch instructs the target program to enter a wait state until it
receives a Start real-time code message from the host. This switch is
required if you want to view data from time step 0 of the target program
execution, or if you want to modify parameters before the target program
begins execution of model code.
5 Open Scope blocks A and B. At this point, no signals are visible on the
scopes. When you connect Simulink to the target program and begin model
execution, the signals generated by the target program will be visible on
the scope displays.
3-45
3 Working with Real-Time Workshop
right side of the toolbar of the Simulink window. Alternatively, you can
select External from the Simulation menu.
7 Reopen the External Mode Control Panel and click Connect. This
initiates a handshake between Simulink and the target program. When
Simulink and the target are connected, the Start real-time code
button becomes enabled, and the label of the Connect button changes
to Disconnect.
8 Click the Start real-time code button. The outputs of Gain blocks A and
B are displayed on the two scopes in your model. With A = 2 and B = 3,
the output looks like this:
Tuning Parameters
You can change the gain factor of either Gain block by assigning a new value
to the variable A or B in the MATLAB workspace. When you change block
parameter values in the workspace during a simulation, you must explicitly
update the block diagram with these changes. When the block diagram is
updated, the new values are downloaded to the target program.
3-46
Working with External Mode Using GRT
A = 0.5;B = 3.5;
3 You can also enter gain values directly into the Gain blocks. To do this,
open the Block Parameters dialog box for Gain block A or B in the model.
Enter a new numerical value for the gain and click Apply. As soon as
you click Apply, the new value is downloaded to the target program and
the effect of the gain change becomes visible on the scope. Similarly, you
can change the frequency, amplitude, or phase of the sine wave signal by
opening the Block Parameters dialog box for the Sine Wave block and
entering a new numerical value in the appropriate field.
Note that because the Sine Wave is a source block, Simulink pauses while
the Block Parameters dialog box is open. You must close the dialog box
by clicking OK, which allows Simulink to continue and enable you to see
the effect of your changes.
Also note that you cannot change the sample time of the Sine Wave block.
Block sample times are part of the structural definition of the model and
are part of the generated code. Therefore, if you want to change a block
sample time, you must stop the external mode simulation, reset the blocks
sample time, and rebuild the executable.
3-47
3 Working with Real-Time Workshop
mkdir tutorial6
cd tutorial6
vdp
3-48
Generating Code for a Referenced Model
3 Drag a box around the three blocks on the left to select them, as shown
below:
5 If the new subsystem block is not where you want it, move it to a preferred
location.
3-49
3 Working with Real-Time Workshop
You must set several properties before you can extract a subsystem for use as
a referenced model. To set the necessary properties,
2 In the left pane of the Model Explorer, expand the vdp node and select
Configuration (Active).
4 In the right pane, under Solver Options change the Type to Fixed-step,
then click Apply. You must use fixed-step solvers when generating code,
although referenced models can use different solvers than top models.
3-50
Generating Code for a Referenced Model
a Select the Data Validity tab. In the Signals area, set Signal
resolution to Explicit only.
b Select the Connectivity tab. In the Buses area, set Mux blocks used
to create bus signals to error.
7 Click Apply.
The model now has the properties that model referencing requires.
8 In the center pane, click Model Referencing. In the right pane, set
Rebuild options to If any changes in known dependencies detected.
Click Apply. This setting prevents unnecessary code regeneration.
9 In the vdp model window, choose File > Save as. Save the model as vdptop
in your working directory. Leave the model open.
help Simulink.Subsystem.convertToModelReference
doc Simulink.Subsystem.convertToModelReference
sldemo_mdlref_conversion
3-51
3 Working with Real-Time Workshop
Simulink.SubSystem.convertToModelReference...
('vdptop/vdpmult', 'vdpmultRM',...
'ReplaceSubsystem', true, 'BuildTarget', 'Sim')
This command:
ans =
1
3-52
Generating Code for a Referenced Model
Note the changes in the appearance of the block vdpmult. These changes
indicate that it is now a Model block rather than a subsystem. As a Model
block, it has no contents of its own: the previous contents now exist in the
referenced model vdpmultRM, whose name appears at the top of the Model
block. Widen the Model block as needed to expose the complete name of the
referenced model.
If the parent model vdptop had been closed at the time of conversion, the
converter would have opened it. Extracting a subsystem to a referenced model
does not automatically create or change a saved copy of the parent model. To
preserve the changes to the parent model, save vdptop.
3-53
3 Working with Real-Time Workshop
Right-click the Model block vdpmultRM and choose Open Block to open the
referenced model. The model looks like this:
File Description
3-54
Generating Code for a Referenced Model
2 If the model vdptop is not open, open it. Make sure it is the active window.
3-55
3 Working with Real-Time Workshop
5 Check Time and Output in the Save to workspace section of the right
pane, then click Apply. The pane shows the following information:
These settings instruct the model vdptop (and later its executable) to log
time and output data to MAT-files for each time step.
6 Generate GRT code (the default) and an executable for the top model and
the referenced model by selecting Real-Time Workshop in the center
pane and then clicking the Build button.
Real-Time Workshop generates and compiles code. The current directory now
contains a new file and a new directory:
File Description
vdptop.exe The executable created by Real-Time
Workshop
vdptop_grt_rtw/ The Real-Time Workshop build
directory, containing generated code
for the top model
Real-Time Workshop also generated GRT code for the referenced model, and
placed it in the slprj directory.
3-56
Generating Code for a Referenced Model
To use the Model Explorer to inspect the newly created build directory,
vdptop_grt_rtw:
1 In Model Explorers Model Hierarchy pane, expand the node for the
vdptop model.
2 Click the plus sign in front of the node named Code for vdptop to expand
the node.
3 Click the This Model node that appears directly under Code for vdptop.
rtmodel.h
vdptop.c
vdptop.h
vdptop.mk
vdptop_data.c
vdptop_private.h
vdptop_types.h
You can browse code in any of these files by selecting a file of interest in
the Contents pane. The code for the file you select appears in the pane
to the right. The figure below illustrates viewing code for vdptop.c. Your
code may differ.
3-57
3 Working with Real-Time Workshop
The models referenced by Model blocks can be stored anywhere. A given top
model can include models stored on different file systems and directories. The
same is not true for the simulation targets derived from these models; under
most circumstances, all models referenced by a given top model must be set
up to simulate and generate model reference target code in a single project
directory. The top and referenced models can exist anywhere on your path,
but the project directory is assumed to exist in your current directory.
This means that, if you reference the same model from several top models,
each stored in a different directory, you must either
Always work in the same directory and be sure that the models are on
your path
Allow separate project directories, simulation targets, and Real-Time
Workshop targets to be generated in each directory in which you work
The files in such multiple project directories are generally quite redundant.
Therefore, to avoid regenerating code for referenced models more times than
necessary, you might want to choose a specific working directory and remain
in it for all sessions.
3-58
Documenting a Code Generation Project
Note You need a license for Simulink Report Generator to complete steps
3 and 4. If you omit those steps and use the default option settings, the
resulting output will vary from what is documented in step 6.
For details on using the Report Generator, see the MATLAB Report Generator
documentation.
3-59
3 Working with Real-Time Workshop
mkdir report_ex
cd report_ex
rtwdemo_f14
5 In the model window, choose File > Save As, navigate to the working
directory, report_ex, and save a copy of the rtwdemo_f14 model as
myf14.mdl.
7 In the Model Hierarchy pane, expand node myf14 and click the
Configuration subnode. The Model Configuration dialog appears in
the dialog pane.
10 Click Generate code. Real-Time Workshop generates code for the model.
3-60
Documenting a Code Generation Project
1 In the model window, select Tools > Report Generator. The Report
Explorer window opens.
For alternative ways of opening the Report Generator, see Opening Report
Generator in the MATLAB Report Generator documentation.
2 In the options pane (center), find the folder rtw (\toolbox\rtw) and the
setup file that it contains codegen.rpt.
3-61
3 Working with Real-Time Workshop
3-62
Documenting a Code Generation Project
1 Review the options listed under Report Options in the properties pane.
3 Select Custom: for Filename and replace index with the name
MyModelCGReport.
4 For File format, specify Rich Text Format and replace Standard Print
with Numbered Chapters & Sections.
3-63
3 Working with Real-Time Workshop
6 Click OK.
1 In the outline pane, select Model Loop. Report Generator displays Model
Loop component options in the properties pane.
2 If not already selected, select Current block diagram for the Model
name option.
3-64
Documenting a Code Generation Project
4 Click Help to review the report customizations you can make with the
Code Generation Summary component. For this tutorial, do not customize
the component.
5 Return focus to the Report Explorer window and expand the node Section
1 Generated Code Listing. The Import Generated Code component
appears.
7 Click Help to review the report customizations you can make with the
Import Generated Code component.
For alternative ways of generating reports, see Generating the Report in the
MATLAB Report Generator documentation.
3-65
3 Working with Real-Time Workshop
3-66
A
Examples
Verification
Data Logging on page 3-13
Code Verification on page 3-20
Optimizations
First Look at Generated Code on page 3-26
External Mode
Working with External Mode Using GRT on page 3-37
Model Reference
Generating Code for a Referenced Model on page 3-48
Report Generator
Documenting a Code Generation Project on page 3-59
A-2
Glossary
Glossary
application modules
With respect to Real-Time Workshop program architecture, these are
collections of programs that implement functions carried out by the
system-dependent, system-independent, and application components.
atomic subsystem
Subsystem whose blocks are executed as a unit before moving on.
Conditionally executed subsystems are atomic, and atomic subsystems
are nonvirtual. Unconditionally executed subsystems are virtual by
default, but can be designated as atomic. Real-Time Workshop can
generate reusable code only for nonvirtual subsystems.
code reuse
Optimization whereby code generated for identical nonvirtual
subsystems is collapsed into one function that is called for each
subsystem instance with appropriate parameters. Code reuse, along
with expression folding, can dramatically reduce the amount of
generated code.
Glossary-1
Glossary
configuration
Set of attributes for a model which defines parameters governing how a
model simulates and generates code. A model can have one or more such
configuration sets, and users can switch between them to change code
generation targets or to modify the behavior of models in other ways.
configuration component
Named element of a configuration set. Configuration components
encapsulate settings associated with the Solver, Data Import/Export,
Optimization, Diagnostics, Hardware Implementation, Model
Referencing, and Real-Time Workshop panes in the Configuration
Parameters dialog box. A component may contain subcomponents.
expression folding
Code optimization technique that minimizes the computation of
intermediate results at block outputs and the storage of such results
in temporary buffers or variables. It can dramatically improve the
efficiency of generated code, achieving results that compare favorably
with hand-optimized code.
file extensions
The table below lists the file extensions associated with Simulink, the
Target Language Compiler, and Real-Time Workshop.
Glossary-2
Glossary
Glossary-3
Glossary
host system
Computer system on which you create and may compile your real-time
application. Also referred to as emulation hardware.
inline
Generally, this means to place something directly in the generated
source code. You can inline parameters and S-functions using Real-Time
Workshop and the Target Language Compiler.
inlined parameters
(Target Language Compiler Boolean global variable: InlineParameters)
The numerical values of the block parameters are hard-coded into the
generated code. Advantages include faster execution and less memory
use, but you lose the ability to change the block parameter values at
run time.
inlined S-function
An S-function can be inlined into the generated code by implementing it
as a .tlc file. The code for this S-function is placed in the generated
model code itself. In contrast, noninlined S-functions require a function
call to an S-function residing in an external MEX-file.
loop rolling
(Target Language Compiler global variable: RollThreshold) Depending
on the blocks operation and the width of the input/output ports, the
generated code uses a for statement (rolled code) instead of repeating
identical lines of code (flat code) over the signal width.
make
Utility to maintain, update, and regenerate related programs and files.
The commands to be executed are placed in a makefile.
makefiles
Files that contain a collection of commands that allow groups of
programs, object files, libraries, and so on, to interact. Makefiles are
executed by your development systems make utility.
Glossary-4
Glossary
model.rtw
Intermediate record file into which Real-Time Workshop compiles the
blocks, signals, states, and parameters a model, which the Target
Language Compiler reads to generate code to represent the model.
multitasking
Process by which a microprocessor schedules the handling of multiple
tasks. In generated code, the number of tasks is equal to the number of
sample times in your model. See also pseudo multitasking.
noninlined S-function
In the context of Real-Time Workshop, this is any C-MEX S-function
that is not implemented using a customized .tlc file. If you create
a C-MEX S-function as part of a Simulink model, it is by default
noninlined unless you write your own .tlc file that inlines it.
nonreal-time
Simulation environment of a block diagram provided for high-speed
simulation of your model. Execution is not tied to a real-time clock.
nonvirtual block
Any block that performs some algorithm, such as a Gain block.
Real-Time Workshop generates code for all nonvirtual blocks, either
inline or as separate functions and files, as directed by users.
pseudo multitasking
On processors that do not offer multitasking support, you can perform
pseudomultitasking by scheduling events on a fixed time-sharing basis.
real-time system
Computer that processes real-world events as they happen, under the
constraint of a real-time clock, and that can implement algorithms in
dedicated hardware. Examples include mobile telephones, test and
measurement devices, and avionic and automotive control systems.
Glossary-5
Glossary
run-time interface
Wrapper around the generated code that can be built into a stand-alone
executable. The run-time interface consists of routines to move the time
forward, save logged variables at the appropriate time steps, and so on
The run-time interface is responsible for managing the execution of the
real-time program created from your Simulink block diagram.
S-function
Customized Simulink block written in C, Fortran, or M-code. Real-Time
Workshop can target C-code S-functions as is or users can inline C-code
S-functions by preparing TLC scripts for them.
simstruct
Simulink data structure and associated application program interface
(API) that enables S-functions to communicate with other entities
in models. Simstructs are included in code generated by Real-Time
Workshop for noninlined S-functions.
simulation target
Set of code files generated for a model which is referenced by a Model
block. Simulation target code is generated into /slprj/sim project
directory in the working directory. Also an executable library compiled
from these codes that implements a Model block. See also Real-Time
Workshop target.
single-tasking
Mode in which a model runs in one task, regardless of the number of
sample rates it contains.
stiffness
Property of a problem that forces a numerical method, in one or more
intervals of integration, to use a step length that is excessively small in
relation to the smoothness of the exact solution in that interval.
Glossary-6
Glossary
target file
File that is compiled and executed by the Target Language Compiler.
The block and system target TLC files used specify how to transform
the Real-Time Workshop file (model.rtw) into target-specific code.
target system
Specific or generic computer system on which your real-time application
is intended to execute. Also referred to as embedded hardware.
targeting
Process of creating software modules appropriate for execution on your
target system.
template makefile
Line-for-line makefile used by a make utility. Real-Time Workshop
converts the template makefile to a makefile by copying the contents
of the template makefile (usually system.tmf) to a makefile (usually
system.mk) replacing tokens describing your models configuration.
Glossary-7
Glossary
virtual block
Connection or graphical block, for example a Mux block, that has no
algorithmic functionality. Virtual blocks incur no real-time overhead
as no code is generated for them.
work vector
Data structures for saving internal states or similar information,
accessible to blocks that may require such work areas. These include
state work (rtDWork), real work (rtRWork), integer work (rtIWork), and
pointer work (rtPWork) structures. For example, the Memory block uses
a real work element for each signal.
Glossary-8
Index
A
Index LCC 1-13
acceleration of development process 1-7 list of supported 1-11
application requirements 2-3 MEX 1-11
Microsoft Visual C/C++ 1-13
optimization settings 1-11
B supported on UNIX 1-11
block target file 2-19 supported on Windows 1-11
build directory Watcom 1-13
contents of 2-28 configuration parameters 2-8
naming convention 2-27 factory defaults 2-5
rtwdemo_f14 example 3-11 impacts of settings 2-5
seeing files 3-11 questions to consider 2-4
build directory optional contents
C-API files 2-28
D
HTML report files 2-28
model.rtw 2-28 data logging 3-13
object files 2-28 from generated code 3-22
subsystem code modules 2-28 tutorial 3-13
TLC profiler files 2-28 via Scope blocks
build process example 3-20
files and directories created 2-22 debug options 3-8
messages in MATLAB Command debugging
Window 3-10 and configuration parameter settings 2-5
steps in 2-17 dialog boxes
Block Parameters 3-38
Configuration Parameters 2-4
C External Mode Control Panel 3-43
code generation for Simulink models 1-4 External Signal and Triggering 3-44
Code Generation Summary component 3-64 Model Explorer 2-8
code generation tutorial 3-26 directories
product support for 1-16 build 3-4
code verification tutorial 3-20 working 3-4
code with buffer optimization 3-32 documentation 3-59
efficiency 3-32 online 1-19
code with expression folding 3-32
code without buffer optimization 3-29
E
comments options 3-9
compilers efficiency
Borland 1-12 and configuration parameter settings 2-5
Intel 1-12 executable
Index-1
Index
Index-2
Index
S
R
safety precautions
rapid simulations 1-3
and configuration parameter settings 2-5
Real-Time Workshop
Index-3
Index
T V
target variable-step solver 3-5
how to specify 3-6 to 3-7
Real-Time Workshop support 1-5 W
target file
Windows compilers 1-11
block 2-19
working directory 2-27
system 2-19
Target Language Compiler
Index-4