KEMBAR78
RTW Gs | PDF | Simulation | Formal Verification
0% found this document useful (0 votes)
43 views60 pages

RTW Gs

Simulink Coder - Getting Started R2017a

Uploaded by

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

RTW Gs

Simulink Coder - Getting Started R2017a

Uploaded by

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

Simulink® Coder™

Getting Started Guide

R2017a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

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

Phone: 508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098

Simulink® Coder™ Getting Started Guide


© COPYRIGHT 2011–2017 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
April 2011 Online only New for Version 8.0 (Release 2011a)
September 2011 Online only Revised for Version 8.1 (Release 2011b)
March 2012 Online only Revised for Version 8.2 (Release 2012a)
September 2012 Online only Revised for Version 8.3 (Release 2012b)
March 2013 Online only Revised for Version 8.4 (Release 2013a)
September 2013 Online only Revised for Version 8.5 (Release 2013b)
March 2014 Online only Revised for Version 8.6 (Release 2014a)
October 2014 Online only Revised for Version 8.7 (Release 2014b)
March 2015 Online only Revised for Version 8.8 (Release 2015a)
September 2015 Online only Revised for Version 8.9 (Release 2015b)
October 2015 Online only Rereleased for Version 8.8.1 (Release
2015aSP1)
March 2016 Online only Revised for Version 8.10 (Release 2016a)
September 2016 Online only Revised for Version 8.11 (Release 2016b)
March 2017 Online only Revised for Version 8.12 (Release 2017a)
Check Bug Reports for Issues and Fixes
Software is inherently complex and is not free of errors. The output of a code generator
might contain bugs, some of which are not detected by a compiler. MathWorks
reports critical known bugs brought to its attention on its Bug Report system at
www.mathworks.com/support/bugreports/. Use the Saved Searches and Watched Bugs
tool with the search phrase "Incorrect Code Generation" to obtain a report of known bugs
that produce code that might compile and execute, but still produce wrong answers.

The bug reports are an integral part of the documentation for each release. Examine
periodically all bug reports for a release, as such reports may identify inconsistencies
between the actual behavior of a release you are using and the behavior described in this
documentation.

In addition to reviewing bug reports, you should implement a verification and validation
strategy to identify potential bugs in your design, code, and tools.
Contents

Product Overview
1
Simulink Coder Product Description . . . . . . . . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Code Generation Technology . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Validation and Verification for System Development . . . . . . 1-4


V-Model for System Development . . . . . . . . . . . . . . . . . . . . . 1-4
Types of Simulation and Prototyping in the V-Model . . . . . . . 1-6
Types of In-the-Loop Testing in the V-Model . . . . . . . . . . . . . 1-7
Mapping of Code Generation Goals to the V-Model . . . . . . . . 1-8

Target Environments and Applications . . . . . . . . . . . . . . . . 1-23


About Target Environments . . . . . . . . . . . . . . . . . . . . . . . . 1-23
Types of Target Environments Supported By Simulink
Coder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
Applications of Supported Target Environments . . . . . . . . . 1-25

Code Generation Workflow with Simulink Coder . . . . . . . . 1-28

Getting Started Examples


2
Generate C Code for a Model . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Configure Model for Code Generation . . . . . . . . . . . . . . . . . . 2-2
Check Model Configuration for Execution Efficiency . . . . . . . 2-4
Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Generate Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
View the Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7

vii
Build and Run Executable . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
Configure Model to Output Data to MAT-File . . . . . . . . . . . 2-11
Build Executable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
Run Executable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
View Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14

Tune Parameters and Monitor Signals During Execution . 2-17


Configure Data Accessibility . . . . . . . . . . . . . . . . . . . . . . . . 2-17
Build Standalone Executable . . . . . . . . . . . . . . . . . . . . . . . . 2-19
Run Executable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
Connect Simulink to Executable . . . . . . . . . . . . . . . . . . . . . 2-20
Tune Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21

viii Contents
1

Product Overview

• “Simulink Coder Product Description” on page 1-2


• “Code Generation Technology” on page 1-3
• “Validation and Verification for System Development” on page 1-4
• “Target Environments and Applications” on page 1-23
• “Code Generation Workflow with Simulink Coder” on page 1-28
1 Product Overview

Simulink Coder Product Description


Generate C and C++ code from Simulink and Stateflow models

Simulink® Coder™ (formerly Real-Time Workshop®) generates and executes C and


C++ from Simulink diagrams, Stateflow® charts, and MATLAB® functions. The
generated source code can be used for real-time and non-real-time applications, including
simulation acceleration, rapid prototyping, and hardware-in-the-loop testing. You can
tune and monitor the generated code using Simulink or run and interact with the code
outside MATLAB and Simulink.

Key Features
• ANSI/ISO C and C++ code and executables for discrete, continuous, or hybrid
Simulink and Stateflow models
• Incremental code generation for large models
• Integer, floating-point, and fixed-point data type support
• Code generation for single-rate, multirate, and asynchronous models
• Single-task, multitask, and multicore code execution with or without an RTOS
• External mode simulation for parameter tuning and signal monitoring

1-2
Code Generation Technology

Code Generation Technology


MathWorks® code generation technology produces C or C++ code and executables for
algorithms. You can write algorithms programmatically with MATLAB or graphically in
the Simulink environment. You can generate code for MATLAB functions and Simulink
blocks that are useful for real-time or embedded applications. The generated source code
and executables for floating-point algorithms match the functional behavior of MATLAB
code execution and Simulink simulations to a high degree of fidelity. Using the Fixed-
Point Designer product, you can generate fixed-point code that provides a bit-wise match
to model simulation results. Such broad support and high degree of accuracy are possible
because code generation is tightly integrated with the MATLAB and Simulink execution
and simulation engines. The built-in accelerated simulation modes in Simulink use code
generation technology.

Code generation technology and related products provide tooling that you can apply
to the V-model for system development. The V-model is a representation of system
development that highlights verification and validation steps in the development process.
For more information, see “Validation and Verification for System Development” on page
1-4.

To learn model design patterns that include Simulink blocks, Stateflow charts, and
MATLAB functions, and map to commonly used C constructs, see “Modeling Patterns for
C Code” (Embedded Coder).

1-3
1 Product Overview

Validation and Verification for System Development


An approach to validating and verifying system development is the V-model.

In this section...
“V-Model for System Development” on page 1-4
“Types of Simulation and Prototyping in the V-Model” on page 1-6
“Types of In-the-Loop Testing in the V-Model” on page 1-7
“Mapping of Code Generation Goals to the V-Model” on page 1-8

V-Model for System Development


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 of
the V focuses on the verification and validation of steps cited on the left side, including
software integration and system integration.

1-4
Validation and Verification for System Development

Verification and validation

Simulation Hardware-in-the-loop
Rapid simulation (HIL) testing

System Integration
System Specification
and Calibration

System simulation (export) Processor-in-the-loop


Rapid prototyping (PIL) testing

Software Detailed
Software Integration
Design

On-target rapid prototyping Software-in-the-loop


(SIL) testing

Coding

Production code generation


Model encryption (export)

Depending on your application and its role in the process, you might focus on one or more
of the steps called out in the V-model or repeat steps at several stages of the V-model.
Code generation technology and related products provide tooling that you can apply to
the V-model for system development. For more information about how you can apply
MathWorks code generation technology and related products provide tooling to the V-
model process, see:

• “Types of Simulation and Prototyping in the V-Model” on page 1-6


• “Types of In-the-Loop Testing in the V-Model” on page 1-7
• “Mapping of Code Generation Goals to the V-Model” on page 1-8

1-5
1 Product Overview

Types of Simulation and Prototyping in the V-Model


The following table compares the types of simulation and prototyping identified on the
left side of the V-model diagram.

Host-Based Standalone Rapid Rapid Prototyping On-Target Rapid


Simulation Simulations Prototyping
Purpose Test and validate Refine, test, Test new ideas Refine and calibrate
functionality of and validate and research designs during
concept model functionality of development process
concept model in
nonreal time
Execution Host computer Host computer PC or nontarget Embedded
hardware hardware computing unit
Standalone (ECU) or near-
executable runs production hardware
outside of MATLAB
and Simulink
environments
Code Not applicable Not applicable Less emphasis on More emphasis on
efficiency code efficiency and code efficiency and I/
and I/O I/O latency O latency
latency
Ease of use Can simulate Easy to simulate Might require Might use existing
and cost component models of hybrid custom real-time hardware, thus less
(algorithm or dynamic systems simulators and expensive and more
controller) and that include hardware convenient
environment (or components and
plant) environment models Might be done
with inexpensive
Normal mode Ideal for batch off-the-shelf PC
simulation in or Monte Carlo hardware and I/O
Simulink enables simulations cards
you to access,
display, and Can repeat
tune data during simulations with
verification varying data sets,
interactively or
programmatically

1-6
Validation and Verification for System Development

Host-Based Standalone Rapid Rapid Prototyping On-Target Rapid


Simulation Simulations Prototyping
Can accelerate with scripts, without
Simulink rebuilding the model
simulations with
Accelerated and Can connect to
Rapid Accelerated Simulink to monitor
modes signals and tune
parameters

Types of In-the-Loop Testing in the V-Model


The following table compares the types of in-the-loop testing for verification and
validation identified on the right side of the V-model diagram.

SIL Testing PIL Testing on PIL Testing on HIL Testing


Embedded Hardware Instruction Set
Simulator
Purpose Verify component Verify component Verify component Verify system
source code object code object code functionality
Fidelity and Two options: Same object code Same object code Same executable
accuracy code
Same source Bit accurate for Bit accurate for
code as target, fixed-point math fixed-point math Bit accurate for
but might have fixed-point math
numerical Cycle accurate Might not be cycle
differences because code runs on accurate Cycle accurate
hardware
Changes source Use real and
code to emulate emulated system I/O
word sizes, but is
bit accurate for
fixed-point math
Execution Host Target Host Target
platforms
Ease of use Desktop Executes on desk or Desktop Executes on test
and cost convenience test bench convenience bench or in lab

1-7
1 Product Overview

SIL Testing PIL Testing on PIL Testing on HIL Testing


Embedded Hardware Instruction Set
Simulator
Executes only in Uses hardware — Executes only on Uses hardware —
Simulink process board and host computer processor, embedded
cables with Simulink computer unit
Reduced hardware and integrated (ECU), I/O devices,
cost development and cables
environment (IDE)

Reduced hardware
cost
Real-time Not real time Not real time Not real time Hard real time
capability (between samples) (between samples)

Mapping of Code Generation Goals to the V-Model


The following tables list goals that you might have, as you apply code generation
technology, and where to find guidance on how to meet those goals. Each table focuses on
goals that pertain to a step of the V-model for system development.

• Documenting and Validating Requirements


• Developing a Model Executable Specification
• Developing a Detailed Software Design
• Generating the Application Code
• Integrating and Verifying Software
• Integrating, Verifying, and Calibrating System Components

Documenting and Validating Requirements

Goals Related Product Information Examples


Capture requirements in “Simulink Report Generator”
a document, spreadsheet,
data base, or requirements Third-party vendor tools such as
management tool Microsoft® Word, Microsoft Excel®,
raw HTML, or IBM® Rational®
DOORS®

1-8
Validation and Verification for System Development

Goals Related Product Information Examples


Associate requirements “Requirements Traceability” slvnvdemo_fuelsys_docreq
documents with objects in (Simulink Verification and
concept models Validation)

Generate a report on Bidirectional tracing in Microsoft


requirements associated with a Word, Microsoft Excel, HTML, and
model IBM Rational DOORS
Include requirements links in “Review of Requirements Links” rtwdemo_requirements
generated code (Simulink Verification and
Validation)
Trace model blocks and “Code Tracing” (Embedded Coder) rtwdemo_hyperlinks
subsystems to generated code
and vice versa
Verify, refine, and test concept “Model Architecture and Design” “Air-Fuel Ratio Control
model in non real time on a System with Stateflow
host system “Model Architecture and Design” Charts”
(Embedded Coder)

“Simulation” (Simulink)

“Acceleration” (Simulink)
Run standalone rapid “Accelerate, Refine, and Test “Run Rapid Simulations Over
simulations Hybrid Dynamic System on Host Range of Parameter Values”
Computer by Using RSim System
Run batch or Monte-Carlo Target File” “Run Batch Simulations
simulations Without Recompiling
“Set Up and Use Host/Target Generated Code”
Repeat simulations with Communication Channel”
varying data sets, interactively “Use MAT-Files to Feed Data
or programmatically with to Inport Blocks for Rapid
scripts, without rebuilding the Simulations”
model

Tune parameters and monitor


signals interactively

Simulate models for hybrid


dynamic systems that

1-9
1 Product Overview

Goals Related Product Information Examples


include components and an
environment or plant that
requires variable-step solvers
and zero-crossing detection
Distribute simulation runs “Simulink Test”
across multiple computers
“MATLAB Distributed Computing
Server”

“Parallel Computing Toolbox”

1-10
Validation and Verification for System Development

Developing a Model Executable Specification

Goals Related Product Information Examples


Produce design artifacts for “MATLAB Report Generator”
algorithms that you develop in
MATLAB code for reviews and
archiving
Produce design artifacts from “System Design Description” rtwdemo_codegenrpt
Simulink and Stateflow models (Simulink Report Generator)
for reviews and archiving
Add one or more components “Deploy Algorithm Model for
to another environment for Real-Time Rapid Prototyping”
system simulation

Refine a component model

Refine an integrated system


model

Verify functionality of a model


in nonreal time

Test a concept model


Schedule generated code “Absolute and Elapsed Time rtwdemos, select Multirate
Computation” Support

“Time-Based Scheduling and


Code Generation”

“Asynchronous Events”
Specify function boundaries of “Subsystems” rtwdemo_atomic
systems rtwdemo_ssreuse
rtwdemo_filepart
rtwdemo_exporting_functions
Specify components and “Component-Based Modeling” rtwdemo_mdlreftop
boundaries for design and
incremental code generation “Component-Based Modeling”
(Embedded Coder)

1-11
1 Product Overview

Goals Related Product Information Examples


Specify function interfaces “Function and Class Interfaces” rtwdemo_fcnprotoctrl
so that external software can rtwdemo_cppclass
compile, build, and invoke the “Function and Class Interfaces”
generated code (Embedded Coder)
Manage data packaging in “File Packaging” rtwdemo_ssreuse
generated code for integrating rtwdemo_mdlreftop
and packaging data “File Packaging” (Embedded rtwdemo_advsc
Coder)
Generate and control the “Add Custom Comments to rtwdemo_comments
format of comments and Generated Code” (Embedded rtwdemo_symbols
identifiers in generated code Coder)

“Construction of Generated
Identifiers” (Embedded Coder)
Create a zip file that contains “Relocate Code to Another rtwdemo_buildinfo
generated code files, static Development Environment”
files, and dependent data to
build generated code in an
environment other than your
host computer
Export models for validation “Package Generated Code as rtwdemo_shrlib
in a system simulator using Shared Libraries” (Embedded
shared libraries Coder)
Refine component and “Deployment”
environment model designs
by rapidly iterating between “Deployment” (Embedded
algorithm design and Coder)
prototyping

Verify whether a component


can adequately control a
physical system in non-real
time

Evaluate system performance


before laying out hardware,

1-12
Validation and Verification for System Development

Goals Related Product Information Examples


coding production software, or
committing to a fixed design

Test hardware
Generate code for rapid “Function and Class Interfaces” rtwdemo_counter
prototyping rtwdemo_counter_msvc
“Entry-Point Functions and rtwdemo_async
Scheduling”

“Generate Modular Function


Code” (Embedded Coder)
Generate code for rapid “Simulink Real-Time” “Simulink Real-Time Examples”
prototyping in hard real time, (Simulink Real-Time)
using PCs
Generate code for rapid “Simulink Desktop Real-Time” sldrtex_vdp (and others)
prototyping in soft real time,
using PCs

Developing a Detailed Software Design

Goals Related Product Information Examples


Refine a model design for “Data Representation”
representation and storage of
data in generated code “Data Representation”
(Embedded Coder)
Select code generation features “Run-Time Environment rtwdemo_counter
for deployment Configuration” rtwdemo_counter_msvc
rtwdemo_async
“Run-Time Environment “Sample Workflows” (Embedded
Configuration” (Embedded Coder)
Coder)

“Sharing Utility Code”


(Embedded Coder)

“AUTOSAR Code Generation”


(Embedded Coder)

1-13
1 Product Overview

Goals Related Product Information Examples


Specify target hardware “Run-Time Environment rtwdemo_targetsettings
settings Configuration”

“Run-Time Environment
Configuration” (Embedded
Coder)
Design model variants “Define, Configure, and
Activate Variants” (Simulink)

“Variant Systems” (Embedded


Coder)
Specify fixed-point algorithms “Data Types and Scaling” rtwdemo_fixpt1
in Simulink, Stateflow, and the (Fixed-Point Designer) “Air-Fuel Ratio Control System
MATLAB language subset for with Fixed-Point Data”
code generation “Fixed-Point Code Generation
Support” (Fixed-Point
Designer)
Convert a floating-point model “Convert to Fixed Point” fxpdemo_fpa
or subsystem to a fixed-point (Fixed-Point Designer)
representation
Iterate to obtain an optimal “Data Types and Scaling” fxpdemo_feedback
fixed-point design, using (Fixed-Point Designer)
autoscaling
Create or rename data types “What Are User-Defined Data rtwdemo_udt
specifically for your application Types?” (Embedded Coder)

“Data Type Replacement”


(Embedded Coder)
Control the format of identifiers “Construction of Generated rtwdemo_symbols
in generated code Identifiers” (Embedded Coder)
Specify how signals, tunable “Custom Storage Classes” rtwdemo_cscpredef
parameters, block states, and (Embedded Coder)
data objects are declared,
stored, and represented in
generated code

1-14
Validation and Verification for System Development

Goals Related Product Information Examples


Create a data dictionary for a “Data Definition and rtwdemo_advsc
model Declaration Management”
(Embedded Coder)
Relocate data segments for “Control Data and Function rtwdemo_memsec
generated functions and data Placement in Memory by
using #pragmas for calibration Inserting Pragmas” (Embedded
or data access Coder)
Assess and adjust model “Model Configuration” “Generate Code Using
configuration parameters based Simulink® Coder™”
on the application and an “Model Configuration” “Generate Code Using
expected run-time environment (Embedded Coder) Embedded Coder®” (Embedded
Coder)
Check a model against basic “Run Model Checks” (Simulink) rtwdemo_advisor1
modeling guidelines
Add custom checks to the “Create Model Advisor Checks” slvnvdemo_mdladv
Simulink Model Advisor (Simulink Verification and
Validation)
Check a model against custom “Run Model Checks” (Simulink)
standards or guidelines
Check a model against industry “Standards, Guidelines, and rtwdemo_iec61508
standards and guidelines Block Usage” (Embedded
(MathWorks Automotive Coder)
Advisory Board (MAAB), IEC
61508, IEC 62304, ISO 26262, “Model Guidelines Compliance”
EN 50128 and DO-178) (Simulink Verification and
Validation)
Obtain model coverage for “Coverage Analysis” (Simulink
structural coverage analysis Verification and Validation)
such as MC/DC
Prove properties and generate Simulink Design Verifier™ sldvdemo_cruise_control
test vectors for models sldvdemo_cruise_control_-
verification
Generate reports of models and “MATLAB Report Generator” rtwdemo_codegenrpt
software designs
“Simulink Report Generator”

1-15
1 Product Overview

Goals Related Product Information Examples


“System Design Description”
(Simulink Report Generator)
Conduct reviews of your model “Model Web Views” (Simulink slxml_sfcar
and software designs with Report Generator)
coworkers, customers, and
suppliers who do not have “Model Comparison” (Simulink
Simulink available Report Generator)
Refine the concept model of “Deployment” rtwdemos, select Embedded
your component or system IDEs or Embedded Targets
“Deployment” (Embedded
Test and validate the model Coder)
functionality in real time
“Code Execution Profiling”
Test the hardware (Embedded Coder)

Obtain real-time profiles and “Static Code Metrics”


code metrics for analysis and (Embedded Coder)
sizing based on your embedded
processor

Assess the feasibility of the


algorithm based on integration
with the environment or plant
hardware
Generate source code for your “Code Generation” rtwdemo_counter
models, integrate the code rtwdemo_counter_msvc
into your production build “Code Generation” (Embedded rtwdemo_fcnprotoctrl
environment, and run it on Coder) rtwdemo_cppclass
existing hardware rtwdemo_async
“Sample Workflows” (Embedded
Coder)
Integrate existing externally “Block Creation” (Simulink) rtwdemos, select Integrating
written C or C++ code with with C Code or Integrating
your model for simulation and “External Code Integration” with C++ Code
code generation

1-16
Validation and Verification for System Development

Goals Related Product Information Examples


Generate code for on-target “Deploy Generated Component In rtwdemos, select one of the
rapid prototyping on specific Software to Application Target following: Embedded IDEs or
embedded microprocessors and Platforms” (Embedded Coder) Embedded Targets
IDEs

Generating the Application Code

Goals Related Product Information Examples


Optimize generated ANSI ® “Performance” rtwdemos, select
C code for production (for Optimizations
example, disable floating- “Performance” (Embedded
point code, remove termination Coder)
and error handling code, and
combine code entry points into
single functions)
Optimize code for a specific “Code Replacement” “Optimize Generated Code
run-time environment, using By Developing and Using
specialized function libraries “Code Replacement” Code Replacement Libraries -
(Embedded Coder) Simulink®” (Embedded Coder)

“Code Replacement
Customization” (Embedded
Coder)
Control the format and style of “Control Code Style” rtwdemo_parentheses
generated code (Embedded Coder)
Control comments inserted into “Add Custom Comments to rtwdemo_comments
generated code Generated Code” (Embedded
Coder)
Enter special instructions “Customize Post-Code- rtwdemo_buildinfo
or tags for postprocessing by Generation Build Processing”
third-party tools or processes
Include requirements links in “Review of Requirements rtwdemo_requirements
generated code Links” (Simulink Verification
and Validation)

1-17
1 Product Overview

Goals Related Product Information Examples


Trace model blocks and “Code Tracing” (Embedded rtwdemo_comments
subsystems to generated code Coder) rtwdemo_hyperlinks
and vice versa
“Standards, Guidelines, and
Block Usage” (Embedded
Coder)
Integrate existing externally “Block Creation” (Simulink) rtwdemos, select Integrating
written code with code with C Code or Integrating
generated for a model “External Code Integration” with C++ Code
(Embedded Coder)
Verify generated code for “MISRA C Guidelines”
MISRA C and other run-time (Embedded Coder)
®a

violations
“Polyspace Bug Finder”

“Polyspace Code Prover”


Protect the intellectual “Protected Model” (Simulink)
property of component model
design and generated code “Package Generated Code as
Shared Libraries” (Embedded
Generate a binary file (shared Coder)
library)
Generate a MEX-file S-function “Automate S-Function
for a model or subsystem so Generation with S-Function
that it can be shared with a Builder”
third-party vendor
Generate a shared library for “Package Generated Code as
a model or subsystem so that Shared Libraries” (Embedded
it can be shared with a third- Coder)
party vendor
Test generated production code “Software-in-the-Loop “Test Generated Code with
with an environment or plant Simulation” (Embedded Coder) SIL and PIL Simulations”
model to verify a conversion of (Embedded Coder)
the model to code
Create an S-function wrapper “Write Wrapper S-Function and
for calling your generated TLC Files”

1-18
Validation and Verification for System Development

Goals Related Product Information Examples


source code from a model
running in Simulink
Set up and run SIL tests on “Software-in-the-Loop “Test Generated Code with
your host computer Simulation” (Embedded Coder) SIL and PIL Simulations”
(Embedded Coder)

a. MISRA® and MISRA C are registered trademarks of MISRA Ltd., held on behalf of the MISRA Consortium.

Integrating and Verifying Software

Goals Related Product Information Examples


Integrate existing externally “Block Creation” (Simulink) rtwdemos, select Integrating
written C or C++ code with a with C Code or Integrating
model for simulation and code “External Code Integration” with C++ Code
generation (Embedded Coder)
Connect to data interfaces “Data Exchange Interfaces” rtwdemo_capi
for generated C code data rtwdemo_asap2
structures “Data Exchange Interfaces”
(Embedded Coder)
Control the generation of code “Function and Class Interfaces” rtwdemo_fcnprotoctrl
interfaces so that external (Embedded Coder) rtwdemo_cppclass
software can compile, build,
and invoke the generated code
Export virtual and function-call “Generate Component Source rtwdemo_exporting_functions
subsystems Code for Export to External
Code Base” (Embedded Coder)
Include target-specific code “Code Replacement” “Optimize Generated Code
By Developing and Using
“Code Replacement” Code Replacement Libraries -
(Embedded Coder) Simulink®” (Embedded Coder)

“Code Replacement
Customization” (Embedded
Coder)
Customize and control the build “Build Process Customization” rtwdemo_buildinfo
process

1-19
1 Product Overview

Goals Related Product Information Examples


Create a zip file that contains “Relocate Code to Another rtwdemo_buildinfo
generated code files, static Development Environment”
files, and dependent data to
build the generated code in an
environment other than your
host computer
Integrate software components “Target Environment
as a complete system for testing Verification” (Embedded Coder)
in the target environment
Generate source code for “Code Generation” rtwdemo_async
integration with specific “Sample Workflows” (Embedded
production environments “Code Generation” (Embedded Coder)
Coder)
Integrate code for a specific “Code Replacement” “Optimize Generated Code
run-time environment, using By Developing and Using
specialized function libraries “Code Replacement” Code Replacement Libraries -
(Embedded Coder) Simulink®” (Embedded Coder)

“Code Replacement
Customization” (Embedded
Coder)
Enter special instructions “Customize Post-Code- rtwdemo_buildinfo
or tags for postprocessing by Generation Build Processing”
third-party tools or processes
Integrate existing externally “Block Creation” (Simulink) rtwdemos, select Integrating
written code with code with C Code or Integrating
generated for a model “External Code Integration” with C++ Code
Connect to data interfaces “Data Exchange Interfaces” rtwdemo_capi
for the generated C code data rtwdemo_asap2
structures “Data Exchange Interfaces”
(Embedded Coder)
Schedule the generated code “Timers” rtwdemos, select Multirate
Support
“Time-Based Scheduling”

“Event-Based Scheduling”

1-20
Validation and Verification for System Development

Goals Related Product Information Examples


Verify object code files in a “Software-in-the-Loop “Test Generated Code with
target environment Simulation” (Embedded Coder) SIL and PIL Simulations”
(Embedded Coder)
Set up and run PIL tests on “Processor-in-the-Loop “Test Generated Code with
your target system Simulation” (Embedded Coder) SIL and PIL Simulations”
(Embedded Coder)

“Configure Processor-In-The-
Loop (PIL) for a Custom Target”
(Embedded Coder)

“Create a Target
Communication Channel for
Processor-In-The-Loop (PIL)
Simulation” (Embedded Coder)

See the list of supported


hardware for the Embedded
Coder® product on the
MathWorks Web site, and then
find an example for the related
product of interest

1-21
1 Product Overview

Integrating, Verifying, and Calibrating System Components

Goals Related Product Information Examples


Integrate the software and “Deploy Algorithm Model for
its microprocessor with the Real-Time Rapid Prototyping”
hardware environment for the
final embedded system product “Deploy Environment Model for
Real-Time Hardware-In-the-
Add the complexity of the Loop (HIL) Simulation”
environment (or plant) under
control to the test platform “Deploy Generated Standalone
Executable Programs To Target
Test and verify the embedded Hardware” (Embedded Coder)
system or control unit by using
a real-time target environment “Deploy Generated Component
Software to Application Target
Platforms” (Embedded Coder)
Generate source code for HIL “Code Generation”
testing
“Code Generation” (Embedded
Coder)

“Deploy Environment Model for


Real-Time Hardware-In-the-
Loop (HIL) Simulation”
Conduct hard real-time HIL “Simulink Real-Time” “Simulink Real-Time Examples”
testing using PCs (Simulink Real-Time)
Tune ECU properly for its “Data Exchange Interfaces” rtwdemo_capi
intended use rtwdemo_asap2
“Data Exchange Interfaces”
(Embedded Coder)
Generate ASAP2 data files “Export ASAP2 File for Data rtwdemo_asap2
Measurement and Calibration”

Generate C API data interface “Exchange Data Between rtwdemo_capi


files Generated and External Code
Using C API”

1-22
Target Environments and Applications

Target Environments and Applications

In this section...
“About Target Environments” on page 1-23
“Types of Target Environments Supported By Simulink Coder” on page 1-23
“Applications of Supported Target Environments” on page 1-25

About Target Environments


In addition to generating source code, the code generator produces make or project files to
build an executable for a specific target environment. The generated make or project files
are optional. 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 generated code range from calling a few exported C
or C++ functions on a host computer 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.

The code generator provides built-in system target files that generate, build, and execute
code for specific target environments. These system target files offer varying degrees
of support for interacting with the generated code to log data, tune parameters, and
experiment with or without Simulink as the external interface to your generated code.

Types of Target Environments Supported By Simulink Coder


Before you select a system target file, identify the target environment on which you
expect to execute your generated code. The most common target environments include
those environments listed in the following table.

Target Environment Description


Host computer The same computer that runs MATLAB and Simulink. Typically, a host
computer is a PC or UNIX®a environment that uses a non-real-time operating
system, such as Microsoft Windows® or Linux®b. Non-real-time (general
purpose) operating systems are nondeterministic. For example, those
operating systems might suspend code execution to run an operating system

1-23
1 Product Overview

Target Environment Description


service and then, after providing the service, continue code execution.
Therefore, the executable for your generated code might run faster or slower
than the sample rates that you specified in your model.
Real-time A different computer than the host computer. A real-time simulator can be
simulator a PC or UNIX environment that uses a real-time operating system (RTOS),
such as:

• Simulink Real-Time system


• A real-time Linux system
• A Versa Module Eurocard (VME) chassis with PowerPC® processors
running a commercial RTOS, such as VxWorks® from Wind River®
Systems

The generated code runs in real time and behaves deterministically. The
exact nature of execution varies based on the particular behavior of the
system hardware and RTOS.

Typically, a real-time simulator connects to a host computer for data logging,


interactive parameter tuning, and Monte Carlo batch execution studies.
Embedded A computer that you eventually disconnect from a host computer and run as
microprocessor a standalone computer as part of an electronics-based product. Embedded
microprocessors range in price and performance, from high-end digital signal
processors (DSPs) that process communication signals to inexpensive 8-bit
fixed-point microcontrollers in mass production (for example, electronic parts
produced in the millions of units). Embedded microprocessors can:

• Use a full-featured RTOS


• Be driven by basic interrupts
• Use rate monotonic scheduling provided with code generation

a. UNIX is a registered trademark of The Open Group in the United States and other countries.
b. Linux is a registered trademark of Linus Torvalds.

Note Compile the code produced by the code generator for target hardware by using a
two's complement representation for signed integer values. The code generator does not
provide a check for this configuration in the generated code.

1-24
Target Environments and Applications

A target environment can:

• Have single- or multiple-core CPUs


• Be a standalone computer 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 many benefits, such as early verification of components.

The following figure shows example target environments for code generated for a model.

System model

Algorithm model Environment model


generation

generation
generation
Code

Code
Code

Host Embedded Real-time


executable microprocessor simulator

Host computer(s)

Applications of Supported Target Environments


The following table lists several ways that you can apply code generation technology in
the context of the different target environments.

Application Description
Host Computer
Accelerated simulation You apply techniques to speed up the execution of model
simulation in the context of the MATLAB and Simulink
environments. Accelerated simulations are especially
useful when run time is long compared to the time

1-25
1 Product Overview

Application Description
associated with compilation and checking whether the
target is up to date.
Rapid simulation You execute code generated for a model in nonreal time on
the host computer, but outside the context of the MATLAB
and Simulink environments.
System simulation You integrate components into a larger system. You
provide generated source code and related dependencies
for building a system in another environment or in a host-
based shared library to which other code can dynamically
link.
Model intellectual property protection You generate a Simulink shareable object library for a
(Embedded Coder) model or subsystem for use by a third-party vendor in
another Simulink simulation environment.
Real-Time Simulator
Rapid prototyping You generate, deploy, and tune code on a real-time
simulator connected to the system hardware (for example,
physical plant or vehicle) being controlled. This design
step is crucial for validating whether a component can
control the physical system.
System simulation 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 for
intellectual property protection.
On-target rapid prototyping You generate code for a detailed design that you can run
in real time on an embedded microprocessor while 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 potentially,
compliance with industry standards and guidelines.

1-26
Target Environments and Applications

Application Description
“Software-in-the-Loop Simulation” You execute generated code with your plant model
(Embedded Coder) within Simulink to verify 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, you might
use actual target word sizes and just test production code
behavior.
“Processor-in-the-Loop Simulation” You test an object code component with a plant or
(Embedded Coder) environment model in an open- or closed-loop simulation
to verify model-to-code conversion, cross-compilation, and
software integration.
Hardware-in-the-loop (HIL) testing You verify an embedded system or embedded computing
unit (ECU), using a real-time target environment.

1-27
1 Product Overview

Code Generation Workflow with Simulink Coder


You can use MathWorks code generation technology to generate standalone C or C++
source code for rapid prototyping, simulation acceleration, and hardware-in-the-loop
(HIL) simulation:

• By developing Simulink models and Stateflow charts, and then generating C/C++ code
from the models and charts with the Simulink Coder product
• By integrating MATLAB code for code generation in MATLAB Function blocks in a
Simulink model, and then generating C/C++ code with the Simulink Coder product

You can generate code for most Simulink blocks and many MathWorks products on page
1-3. The following figure shows the product workflow for code generation with Simulink
Coder. Other products that support code generation, such as Stateflow software, are
available.

MATLAB Simulink

Other Code generation MATLAB Function Other


MATLAB code from MATLAB block Simulink blocks

Simulink
Coder

C or C++
code

Compiler or
IDE toolchain

Executable program
(runs in target environment)

The code generation workflow is a part of the V-model for system development. The
process includes code generation, code verification, and testing of the executable program
in real-time. For rapid prototyping of a real-time application, typical tasks are:

1-28
Code Generation Workflow with Simulink Coder

• Configure the model for code generation in the model configuration set
• Check the model configuration for execution efficiency using the Code Generation
Advisor
• Generate and view the C code
• Create and run the executable of the generated code
• Verify the execution results
• Build the target executable
• Run the external model target program
• Connect Simulink to the external process for testing
• Use signal monitoring and parameter tuning to further test your program.

A typical workflow for applying the software to the application development process is:

1-29
1 Product Overview

For more information on how to perform these tasks, see the Getting Started with
Simulink Coder tutorials:

1 “Generate C Code for a Model” on page 2-2


2 “Build and Run Executable” on page 2-11
3 “Tune Parameters and Monitor Signals During Execution” on page 2-17

1-30
2

Getting Started Examples

• “Generate C Code for a Model” on page 2-2


• “Build and Run Executable” on page 2-11
• “Tune Parameters and Monitor Signals During Execution” on page 2-17
2 Getting Started Examples

Generate C Code for a Model


In this section...
“Configure Model for Code Generation” on page 2-2
“Check Model Configuration for Execution Efficiency” on page 2-4
“Simulate the Model” on page 2-5
“Generate Code” on page 2-6
“View the Generated Code” on page 2-7

Simulink Coder generates standalone C/C++ code for Simulink models for deployment
in a wide variety of applications. The Getting Started with Simulink Coder includes
three tutorials. It is recommended that you complete Generate C Code for a Model
first, and then the following tutorials: “Build and Run Executable” on page 2-11 and
“Tune Parameters and Monitor Signals During Execution” on page 2-17.

This example shows how to prepare the rtwdemo_secondOrderSystem


model for code generation and generate C code for real-time simulation. The
rtwdemo_secondOrderSystem model implements a second-order physical system called
an ideal mass-spring-damper system. Components of the system equation are listed as
mass, stiffness, and damping. To open the model, in the command window, type:

rtwdemo_secondOrderSystem

Configure Model for Code Generation


To prepare the model for generating C89/C90 compliant C code, you can specify
code generation settings in the Configuration Parameters dialog box. To open the
Configuration Parameters dialog box, in the Simulink Editor, click the Model
Configuration Parameters button.

Solver for Code Generation

To generate code for a model, you must configure a solver. Simulink Coder generates only
standalone code for a fixed-step solver. On the Solver pane, select a solver that meets

2-2
Generate C Code for a Model

the performance criteria for real-time execution. For this model, observe the following
settings.

Code Generation Target

To specify a target configuration for the model, choose a system target file, a template
makefile, and a make command. You can use a ready-to-run Generic Real-Time Target
(GRT) configuration.

1 In the Configuration Parameters dialog box, select the Code Generation pane.
2 To open the System Target File Browser dialog box, click the System target file
parameter Browse button. The System Target File Browser dialog box includes a
list of available targets. This example uses the system target file grt.tlc Generic
Real-Time Target.

2-3
2 Getting Started Examples

3 Click OK.

Code Generation Report

You can specify that the code generation process automatically generates an HTML
report that includes the generated code and information about the model.

1 In the Configuration Parameters dialog box, select the Code Generation > Report
pane.
2 For this example, the following configuration parameters are selected:

• Create code generation report


• Open report automatically

After the code generation process is complete, an HTML code generation report appears
in a separate window.

Check Model Configuration for Execution Efficiency


When generating code for real-time deployment, a common objective for the generated
code is that it executes efficiently. You can run the Code Generation Advisor on your
model for a specified objective, such as Execution efficiency. The advisor provides
information on how to meet code generation objectives for your model.

1 In the Configuration Parameters dialog box, select the Code Generation pane.
2 Under Code generate objectives, select the following and then click Apply:

• Select objective, select Execution efficiency.


• Check model before generating code, select On (proceed with
warnings).
3 Click Check Model.
4 In the System Selector dialog box, click OK to run checks on the model.

After the advisor runs, there are two warnings indicated by a yellow triangle.
5 On the left pane, click Check model configuration settings against code
generation objectives.
6 On the right pane, click Modify Parameters. The configuration parameters that
caused the warning are changed to the software-recommended setting.

2-4
Generate C Code for a Model

7 On the right pane, click Run This Check. The check now passes. The Code
Generation Advisor lists the parameters and their recommended settings for
Execution efficiency. Close the Code Generation Advisor.

Ignore the warning for the Identify questionable blocks within the specified
system. This warning is for production code generation which is not the goal for this
example.

Simulate the Model


In the Simulink Editor, simulate the model to verify that the output is as you expect for
the specified solver settings.

1 Simulate the model.


2 When the simulation is done, in the Simulink Editor, click the Simulation Data
Inspector button to open the Simulation Data Inspector.
3 Expand the run and then select the Outport block data check boxes to plot the data.

2-5
2 Getting Started Examples

Leave these results in the Simulation Data Inspector. Later, you can compare the
simulation data to the output data generated from the executable shown in “Build and
Run Executable” on page 2-11.

Generate Code
1 In the Configuration Parameters dialog box, on the Code Generation pane, select
the Generate code only check box.
2 Click Apply.
3 In the Simulink Editor, press Ctrl+B.

After code generation, the HTML code generation report opens.

2-6
Generate C Code for a Model

View the Generated Code


The code generation process places the source code files in the
rtwdemo_secondOrderSystem_grt_rtw folder. The HTML code
generation report is in thertwdemo_secondOrderSystem_grt_rtw/html/
rtwdemo_secondOrderSystem_codegen_rpt.html folder.

Open the HTML code generation report,


rtwdemo_secondOrderSystem_codegen_rpt.html. The code generation report
includes:

2-7
2 Getting Started Examples

• Summary
• Subsystem Report
• Code Interface Report
• Generated Code

Code Interface Report

In the left navigation pane, click Code Interface Report to open the report. The code
interface report provides information on how an external main program can interface
with the generated code. There are three entry point functions to initialize, step, and
terminate the real-time capable code.

2-8
Generate C Code for a Model

For rtwdemo_secondOrderSystem, the Outports section includes a single output


variable representing the Outport block of the model.

2-9
2 Getting Started Examples

Generated Code

The generated model.c file rtwdemo_secondOrderSystem.c contains the algorithm


code, including the ODE solver code. The model data and entry point functions are
accessible to a caller by including rtwdemo_secondOrderSystem.h.

On the left navigation pane, click rtwdemo_secondOrderSystem.h to view the extern


declarations for block outputs, continuous states, model output, entry points, and timing
data:

The next example shows how to build an executable. See “Build and Run Executable” on
page 2-11.

2-10
Build and Run Executable

Build and Run Executable

In this section...
“Configure Model to Output Data to MAT-File” on page 2-11
“Build Executable” on page 2-13
“Run Executable” on page 2-14
“View Results” on page 2-14

Simulink Coder supports the following methods for building an executable:

• Using toolchain based controls.


• Using template makefile based controls.
• Interfacing with an IDE.

The code generation target that you select for your model determines the build process
controls that are presented to you. The example model uses the GRT code generation
target, which enables the toolchain based controls. This example shows how to build an
executable using the toolchain controls and then test the executable results.

Before following this example, simulate the example model,


rtwdemo_secondOrderSystem, as described in “Generate C Code for a Model” on page
2-2. Later on, the simulation results are used to compare the results from running the
executable.

Configure Model to Output Data to MAT-File


Before building the executable, enable the model to log output to a MAT-file instead of
the base workspace. You can then view the output data by importing the MAT-file into
the Simulation Data Inspector.

1 In the Configuration Parameters dialog box, select the All Parameters tab and
search for MAT-file.
2 Select rt_ for the MAT-file variable name modifier value and check the MAT-
file logging box.

2-11
2 Getting Started Examples

3 On the Commonly Used Parameters tab, click the Data Import/Export pane
and specify the Save to workspace or file parameters, as shown here.

4 Click Apply.

2-12
Build and Run Executable

Build Executable
The internal MATLAB function make_rtw executes the code generation process for a
model. make_rtw performs an update diagram on the model, generates code, and builds
an executable.

To build an executable in the working MATLAB folder:

1 On the All Parameters tab, search for the Toolchain parameter and set the value
to Automatically locate an installed toolchain.
2 Click Validate to verify your toolchain.

The Validation Report indicates if the checks passed.


3 On the All Parameters tab, select the check box in the MAT-file logging and
Support non-finite numbers parameters.
4 On the Commonly Used Parameters tab, in the Code Generation pane, clear
the Generate code only check box.
5 Click Apply.
6 Press Ctrl+B in the Simulink Editor to build the executable.

As the code generator builds the executable, Building appears on the bottom left of
the Simulink Editor window. The process is complete when the text reads Ready and
the Code Generation Report appears.

The code generator places the executable in the working folder. On Windows the
executable is rtwdemo_secondOrderSystem.exe. On Linux the executable is
rtwdemo_secondOrderSystem.

2-13
2 Getting Started Examples

Run Executable
In the MATLAB command window, run the executable using one of the following
commands:

For Windows, type

!rtwdemo_secondOrderSystem
For Linux, type

!./rtwdemo_secondOrderSystem

The MATLAB command window displays the following output:


** starting the model **
** created rtwdemo_secondOrderSystem.mat **

The code generator outputs a MAT-file, rtwdemo_secondOrderSystem.mat. It saves


the file to the working folder.

View Results
This example shows you how to import data into the Simulation Data Inspector and then
compare the executable results with the simulation results. If you have not already sent
logged data from the workspace to the simulation data to the Simulation Data Inspector,
follow the instructions in “Simulate the Model” on page 2-5.

1 If the Simulation Data Inspector is not already open, in the Simulink Editor, click
the Simulation Data Inspector button.
2 To open the Import dialog, click Import from the Visualize tab on the Simulation
Data Inspector toolstrip.
3 In the Import dialog, for Import from, select the MAT-file option button.

Enter the rtwdemo_secondOrderSystem.mat file. The data populates the table.

2-14
Build and Run Executable

Click Import.
4 Click the Compare tab.
5 Select Run 1: rtwdemo_secondOrderSystem from the Baseline list and Run 2:
Imported_Data from the Compare To list.
6 Click Compare.The Simulink Data Inspector indicates that the output from
the executed code is within a reasonable tolerance of the simulation data output
previously collected in “Generate C Code for a Model” on page 2-2.

2-15
2 Getting Started Examples

The next example shows how to run the executable on your machine using Simulink as
an interface for testing. See “Tune Parameters and Monitor Signals During Execution”
on page 2-17.

2-16
Tune Parameters and Monitor Signals During Execution

Tune Parameters and Monitor Signals During Execution

In this section...
“Configure Data Accessibility” on page 2-17
“Build Standalone Executable” on page 2-19
“Run Executable” on page 2-19
“Connect Simulink to Executable” on page 2-20
“Tune Parameter” on page 2-20
“More Information” on page 2-21

This example shows how to access parameter and signal data while a generated
executable runs. Use this approach to experiment with parameters and signal inputs
during rapid prototyping.

To interact with a generated program by using Simulink, simulate a model in external


mode. In this example, the program runs as a standalone executable in nonreal time on
your host computer. Simulink communicates with the executable by using a TCP/IP link.

To learn about the example model and how to generate code, see the tutorials “Generate
C Code for a Model” on page 2-2 and “Build and Run Executable” on page 2-11.

Configure Data Accessibility


To efficiently implement a model in C code, you typically do not allocate storage in
memory for every parameter, signal, and state in the model. As long as the model
algorithm does not require these data items to calculate outputs, code generation
optimizations can eliminate storage for the data. To instead allocate storage for the data
so you can access it during prototyping, disable the optimizations.

1 Open the example model.

rtwdemo_secondOrderSystem

2-17
2 Getting Started Examples

2 Set Configuration Parameters > Optimization > Signals and Parameters >
Default parameter behavior to Tunable.

2-18
Tune Parameters and Monitor Signals During Execution

With this setting, by default, block parameters (such as the Gain parameter of a
Gain block) are tunable in the generated code.
3 Clear the Configuration Parameters > All Parameters > Signal storage reuse
check box.

With this setting, by default, the generated code allocates storage for signal lines.
The external mode simulation can access the values of these signals so that you can
monitor the signals, for example, by using a Scope block in the model.

Build Standalone Executable


Generate code and create an executable from the model.

1 Select the Configuration Parameters > Code Generation > Interface >
External mode check box.

This option enables the generated executable to later communicate with Simulink.
2 Generate code from the model. For example, in the model, press Ctrl+B.

The generated executable, rtwdemo_secondOrderSystem, appears in your current


folder. A code generation report opens.

Run Executable
At the command prompt, run the generated executable. Use the option -tf to override
the stop time so that the executable runs indefinitely.

system('rtwdemo_secondOrderSystem -tf inf &')

2-19
2 Getting Started Examples

Connect Simulink to Executable


To interact with the running process, use external mode simulation in Simulink.

1 In the Simulink Editor toolbar, set the Simulation mode drop-down list to
External.

2
Click the Connect to Target button .
3 In the model, double-click the Scope block. The scope displays the values of the
system output signals.

Tune Parameter
Experiment with the value of a block parameter during execution. Observe the impact of
the change.

2-20
Tune Parameters and Monitor Signals During Execution

1 In the model, select View > Property Inspector.


2 Click the Gain block named Damping: c/m.
3 In the Property Inspector, change the value of Gain from 400 to 800.

The Scope block shows the effect of the change on the signal values.

More Information
For more information, the following table includes common capabilities and resources for
generating and executing C and C++ code for your model.

To... See....
Configure data accessibility for rapid “Access Signal, State, and Parameter Data
prototyping During Execution”
Model multirate systems “Scheduling”

2-21
2 Getting Started Examples

To... See....
Create multiple model configuration sets “Configuration Reuse” (Simulink)
and share configuration parameter settings
across models
Control how signals are stored and “Signals”
represented in the generated code
Generate block parameter storage “Override Default Parameter Behavior by
declarations and interface block Creating Global Variables in the Generated
parameters to your code Code”
Store data separate from the model “Data Objects” (Simulink)
Interface with legacy code for simulation “External Code Integration”
and code generation
Generate separate files for subsystems and “File Packaging”
model
Configure code comments and reserve “Code Appearance”
keywords
Generate C++ compatible code “Programming Language”
Export an ASAP2 file containing “Export ASAP2 File for Data Measurement
information about your model during the and Calibration”
code generation process
Write host-based or target-based code that “Exchange Data Between Generated and
interacts with signals, states, root-level External Code Using C API”
inputs/outputs, and parameters in your
target-based application code
Create a protected model that hides all “Model Protection”
block and line information to share with
third-party
Customize the build process “Build Process Customization”
Create a custom block “Block Authoring and Customization”
Create your own target “Target Development”

2-22

You might also like