Afghanistan
Albania
Algeria
Andorra
Anguilla
Antigua & Barbuda
Argentina
Armenia
Aruba
Australia
Austria
Azerbaijan
Bahamas
Bahrain
Bangladesh
Barbados
Belarus
Belgium
Belize
Benin
Bermuda
Bhutan
Bolivia
Bonaire
Bosnia & Herzegovina
Botswana
Brazil
British Indian Ocean Ter
Brunei
Bulgaria
Burkina Faso
Burundi
Cambodia
Cameroon
Canada
Canary Islands
Cape Verde
Cayman Islands
Central African Republic
Chad
Channel Islands
Chile
China
Christmas Island
Cocos Island
Colombia
Comoros
Congo
Cook Islands
Costa Rica
Cote D Ivoire
Croatia
Cuba
Curacao
Cyprus
Czech Republic
Denmark
Djibouti
Dominica
Dominican Republic
East Timor
Ecuador
Egypt
El Salvador
Equatorial Guinea
Eritrea
Estonia
Ethiopia
Falkland Islands
Faroe Islands
Fiji
Finland
France
French Guiana
French Polynesia
French Southern Ter
Gabon
Gambia
Georgia
Germany
Ghana
Gibraltar
Greece
Greenland
Grenada
Guadeloupe
Guam
Guatemala
Guinea
Guyana
Haiti
Hawaii
Honduras
Hong Kong
Hungary
Iceland
India
Indonesia
Iran
Iraq
Ireland
Isle of Man
Israel
Italy
Jamaica
Japan
Jordan
Kazakhstan
Kenya
Kiribati
Korea North
Korea South
Kuwait
Kyrgyzstan
Laos
Latvia
Lebanon
Lesotho
Liberia
Libya
Liechtenstein
Lithuania
Luxembourg
Macau
Macedonia
Madagascar
Malawi
Malaysia
Maldives
Mali
Malta
Marshall Islands
Martinique
Mauritania
Mauritius
Mexico
Midway Islands
Moldova
Monaco
Mongolia
Montserrat
Morocco
Mozambique
Myanmar
Nambia
Nauru
Nepal
Netherland Antilles
Netherlands (Holland, Europe)
Nevis
New Caledonia
New Zealand
Nicaragua
Niger
Nigeria
Niue
Norfolk Island
Norway
Oman
Pakistan
Palau Island
Palestine
Panama
Papua New Guinea
Paraguay
Peru
Philippines
Pitcairn Island
Poland
Portugal
Puerto Rico
Qatar
Republic of Montenegro
Reunion
Romania
Russia
Rwanda
Saipan
Samoa
Samoa American
San Marino
Sao Tome & Principe
Saudi Arabia
Senegal
Serbia
Seychelles
Sierra Leone
Singapore
Slovakia
Slovenia
Solomon Islands
Somalia
South Africa
Spain
Sri Lanka
St Barthelemy
St Eustatius
St Helena
St Kitts-Nevis
St Lucia
St Maarten
St Pierre & Miquelon
St Vincent & Grenadines
Sudan
Suriname
Swaziland
Sweden
Switzerland
Syria
Tahiti
Taiwan
Tajikistan
Tanzania
Thailand
Togo
Tokelau
Tonga
Trinidad & Tobago
Tunisia
Turkey
Turkmenistan
Turks & Caicos Is
Tuvalu
Uganda
Ukraine
United Arab Emirates
United Kingdom
United States of America
Uruguay
Uzbekistan
Vanuatu
Vatican City State
Venezuela
Vietnam
Virgin Islands (Brit)
Virgin Islands (USA)
Wake Island
Wallis & Futana Is
Yemen
Zaire
Zambia
Zimbabwe
Embedded Encoder
Just a text manipulator to translate from Simulink to C
Advantages of code generation.
Reproduce code at a push of a button.
Maintain code quality in a consistent manner
Eliminate manual coding errors.
Avoid having to manually code an algorithm in a Simulink model.
Generates rigerous ANSI-standard code.
Product heiarchy
Embedded coder allows for reading/writing/modifying code.
Used to be "Realtime Workshop"
Began with "accelerator mode"
Matlab coder: computer vision.
Depenencies: need Matlab coder to run Simulink coder to Embedded Coder.
Matlab Coder came along later (5 years ago).
Less expensive license allows for testing in real time.
Not a seperate product. Just opens more options in Simulink compiler list.
What can we do with embedded coder?
Verify code by automatically importing it to Simulink for software-in-the-loop testing
Generate C/C++ code with memory useage, execution speed, and readability comparible to hadwritten code.
Do provide support packages for specific hardware.
Don't provide compilers.
Package generated code to comply with specific softare styles and standards
Genarate code from Simulink data objects, including user-defined storage classes, types, and aliases.
Support packages are just utilities to mung for specifics.
Generating Code
Generate embedded code
Identify the location and the model step function, data structure, and main routine.
Archetecture.
Architecture of an embedded applicaton
Generating ERT code
Code Modules
Logging intermediate structures
Data Structures in embedded code
Acronyms
STF System Target Files
RTW REal-Time Workshop (old product name)
GRT Generic Real-Time Code (Simulink Coder)
TLC Target Language Compiler (Mathwork API)
ERT Embedded Real-Time Code (Embedded Coder)
Archetecture
I/O Device Drivers
Run-Time Library
Main Program
Data Logging Interface
Data Exchange Interface
Model Application
There are hidden options. They are searchable.
Running Example
High-frequency noise removal.
Discrete
IIR Filter
Using a virtual subsystem
Has 2 parameters (constants)
Will drive with a sign wave.
Infinite Impulse-Response Filter
Example: iir
Code Generation Requirements
Can also set toolset for target compiler.
Model options icon: gear icon.
System target file changes remaining options
Build directory will drop in current directory.
Optimization: Parameters -> inline | tunable
Can't have an algebraic loop
Have to use fixed-step solver, usually discrete solver.
Task execution time must always be less than sample time for real time systems
Generated Files
model_data.c parameters defined here
model.h data structures, externs
model.c model_initialize(), model_step_model_terminate()
ert_main.c sample main program
model_private.h macros for inlined parameters imported externs/imported extern pointers.
model_private.h macros for inlined parameters
model_types.h
model.c
Underscores for variables to keep scope from colidding.
model name is the master object.
Inline parameters will show up as constant values in the code
Contains step()
_P is the container for the parameter array
Y's are inputs, U's are outputs. They're both structures that contain named variables.
Contains entry points
Compiler Configuration Parameters
Style is determined by target-language compiler file.
Can generate code only
Includes bi-directional code-to-model, model-to-code tracability via hyperlinks
Build Process
Simulink Model
Code Generation Interpreter
model.rtw
Target Language Compiler (TLC)
mode.c, mdel.h, model_private.h
Make mechanism
model.exe
rtwtypes.h
Contains all the mathworks types as aliases
Model.h
Public interface to the model entry points
Model data structures
Processor Macros
Different model.h for each model
Interface to the real-time model data structure
Signal type definitons
model_private.h
Data structures
Forward declarations for the real-time model
May be needed by function declarations.
Parameters data structure
ert_main.c
Example main generated by default
model_data.c
Output structure
Input structure
Parameters structure
Conditionally generated
model_initialize()
states (dwork)
External inputs and outputs
Error Status
Called at the beginning of execution
Initial conditions of states.
rt_onStep
Has overrun protection
Must have a RT OS
Called by interrupt
Exececution for one time step
model_step
Non-real-time step function
_M Model Object
_B Block Signal
_DW Block States
_Y Outputs
_U External Inputs
_P Parameters
Recommend tunable parameters vs. inline for tracability
Have to designate as a "test point" in signal parameters in the Simulink model.
model_terminate()
Normally empty.
Optionally included
_T Real-Time model
Run-Time interface
token expansion
Template makefile
model.mk
Exercises
Determine resulting code locations for the following items
E-3 in workbook
Model Compilation
Evaluate parameters
Propagate signal properties
Determine the execution order
Code Generation
Supporting TLC function library
Integrating with external code
Consider model entry points
Creating an execution harness
Input data in Smulink and generated code
Packaging generated code
MAT-file logging and nonfinite support
Use Microsoft Visual Studio Express
Pack and relocate all the necessary files
Input Data in Simulink
Works fine in Simulink
Ain't gonna get nuthin' in generated code
Ain't gonna output to workspace from generated code
Model Entry Points
model_initialize()
model_step()
model_terminate()
everything's in ert_main.c
Use generated .bat file to re-compile
Real-Time Execution
Controlling Function Prototypes
Call functions with modified prototype from a custom harness.
Pass scalar and non-scalar signals as input arguments
Modify function protoypes of model entry points
Modifying function prototypes
Generated code with modified function prototypes
Model function prototype considerations
Default model function prototype
Reusuable function interface
Implement C/C++ features in Simulink.
Will have to modify interfaces with external code to match.
Model Function Prototype
Can only customize model_step and model_initialize
Can change name of model_step
Can change name of initialize function
Model Parameters -> Code Generation -> Interface
Can change type and passing style of I/O parameters
Has a "Validate" button to check C syntax
Function defaults
Everything returns void
All data is global
Non-Scalar Signals
Switch C-Type Qualifier to "Pointer"
Model signal dimensions can be displayed by option on the Simulink model.
Will generate C for-loops to process vectors.
Output to console will now be columnated
Things to consider
Custom main function required to interface to new code
Only step and initialize functions are supported
Single output/update function required (model_step)
Multi-rate multitasking models are not supported.
Re-Usable Function interfaces
Configure Model Functions -> Code Generation -> Interface
Switch "Code Interface Packaging" to "Reusable Function" if instance specific parameters are present.
Normally uses global data.
Switches to use local data and I/O parameters.
Can pass as individual parameters, structure, or model structure
If no states use "configure functions" button.
Optimizing Generated Code
Code generation objectives
Optimizing data storage
REmoving unnecessary data support
Removing unnecesary code
Optimization considerations
Static Code Metrics
Generates lines of code, and lines
Gives us code item count
Model Properties -> Code Generation -> Report -> Static code metrics
Gets added as a tab in the code generation report
Also reports data structures: bytes and accessing
Reports on global variables
Optimization Objectives
Debugging
Traceability (mapping between model and code)
Efficency (Reduce RAM, ROM, and execution time)
Safety precaution (Least possibility of errors)
Removing Unneccessary Code
Consider the algorithm and order of operations wrt branches
Code Generation -> Optimization pane
"Remove" buttons will remove items from initialize function
Remove Terminate button is located in interface pane
Consider single "step" function (normally step() and output()).
Removing support for unnecessary data
Mostly under "interface"
Remove non-finite numbers if not needed
Remove complex numbers if not needed.
Use MAT-file logging for debugging only.
Conditional Input Branch Execution
Will optimize execution around branch operations
Won't reduce code, but may reduce operations.
Found under "Simulation Target" in Model Properties window.
Chained optimization features with dependencies
Signal Storage reuse.
Enable local block outputs
Reuse local block outputs
Eliminate superfluous local variables (expression folding)
Reuse global block outputs
Inlining parameters
Default behavior is to store parameters in a global array
Will inline parameters into code as constant values.
May show ineffective switches.
Bad for tracability. Can't tell where the numbrers came from.
Bad for safety because of traceability.
Try using a macro? Symbols -> Generate as...macro
Block Reduction
Execution speed increases.
Appearance of source model does not change.
Collapses certain groups of blocks into single blocks
Don't for traceability
Under "Simulation Target"-> Block Reduction
Store Logical signals as Boolean
Wrapping Code
What do we do with integer overflow?
example: float_int
Optimization -> Remove code for floating-point-to-integer covnersions that wraps out-of-range values
Negative for safety
Negative for debugging
Negative for tracability
Great for efficiency
Exception handling
Divide by zero handlers or not?
example: divide_zero
Optimization-> Remove code that protects against arithmetic exceptions
Bad for safety
Good for efficency
Set Objectives Tool
Allows you to prioritize objectives
System will recommend options to meet objective priorities
Will generate a report.
Not performing a top-down analysis of your model.
Execution efficiency
Is just comparing your generation parameters to objectives.
ROM Efficiency
RAM Efficiency
Traceability
Safety Precation
Debugging
MISRA-C:2012 guidelines
Polyspace
Embedded Coder Quick Start tool
Sets your generator configuration accordingly.
Asks a few initial questions
Exersise
Page E-11
Open a model called settings1
Generate code with default
Data Characteristics (Built-ins)
Simulink environment data type configuration
Data type classification
Data Characteristics
Setting state storage classes
Setting signal storage classes
Simulink environment storage classes
Setting parameter storage classes
Impact of storage classes on symbols
Display the data type of an any signal
Change it as necessary
Set storage class for signals, parameters, and states in a model using Simulink storage classes.
Data Characteristics
Data Characteristics
Memory Size
Organization
Scalar
Array
Bus
Data Type
Built-in
Float
Integer
Fixed-Point
Storage Class
Internal
Local
Global
External
Data Type Classification
Table by block
showblockdatatypetable
Environment data type
Signals
States
Parameters
Inherited or back-propagated from another block
Internal rules
Parameter of the block
Inherited from a MATLAB variable
Outpubt signal of the block
Controlling Simulink Data Types (Blocks)
Block parameter determines the data TYPE
Should have various "data type" pull-down.
Select "Parameter Attributes"
Right-click on the object
Can also use a Data Type Conversion Block
Everything else is calculated based on input inheritance.
Simulink Storage Classes (Signals)
Signal parameter determines the data STORAGE scheme.
Temporary
Model default
Exported global
Imported extern
Imported extern pointer
Custom
Example: iir_ert7
Setting Storage Classes (States)
Find the storage class for the state on the block.
State must be named.
Becomes a "customizable identifier"
Parameters
Model Parameter Configuration
Can tune some parameters and not others.
Must be set to "tuneable"
Code Generation-> Optimization -> Default Parameter Behavior -> (set to "Tunable") -> Configure
Brings up a two-table pane.
Exercise
Local and global block I/O
E-15
Modify local_sum
Global data structure: will happen by default.
Step function: enable local variables
Pointer is a storage class. Change signal storage class to imported extern pointer.
k3: make it a test point to expose the signal.
Put a signal label on k3
Label y signal. Change storage class to exported global.
Hint 1: Change storage class of U3 to Ptr
Hint 2: Signal storage reuse enable local block outputs
Hint 3: Change K3 to a test point
Hint 4: Signal "y" to storage class exported global
Data Objects (Custom Types)
Custom storage classes (SCSs)
Creating reconfigurable data types
Controlling data types with data objects
Data Objects Overview
Controling data type and variable dames
Controlling storage classes with data objects
Data dictionaries
Set storage class for signals and parameters in a model using predefined custom storage classes.
Objects Overview
Package
Class (Signal)
Property 1
Property 2
Property 4
Property 3
Class(Parameter)
Basic Data Configuration Management
Check help files for attributes and members of classes in use.
Can Save as matlab scripts
Check the Model Explorer
Can use a data dictionary to manage configurations.
Using refernces to Simulink type variables in the Matlab workspace.
Big ideas
Looking for a level of data abstraction away from our model.
Will create a data object and associate it with a model.
Pull Simulink objects into the workspace and manage by proxy
Data Types
Structured data
Existing data types with a variable. All floating -point and fixed-point types, and Boolean
Simulink.NumericType
Simulink.AliasType
Simulink.Bus
Simulink.BusElement
Creates alternative names for built-ins and enumerations
Requirements
Parameters: free-floating.
Signals:must be assiciated with a signal.
Signals: check "Must resolve to a Simulink signal object"
Alias
Create my own data type
Adds a new type to the datatype list (refresh)
Allows for global changes for connected signals.
Use to mung generated names in C code. as base types
Numeric type
Allows fixed-point library
Can be aliased to 3rd-party headers
Storage classes
Not user-defined.
Pre-defined.
Struct
Puts signals into a common structure in output code.
Can package signals, states, and parameters.
Set struct name for each signal in storage class, then name for each member
Can apply naming rules
Can use aliases to make struct names switchable.
Can store parameters, signals,and states in the same struct
Have to fumble around in model explorer to find contents of the struct...or look at generated code.
Data object naming rules
Can force all data objects to be either upper or lowercase
Symbols-> Signal Naming
Can mung generated names
Overrides
Overrides naming rules
Can override symbol names
Data Dictionaries
.sldd
Contains data and configurations.
iir_numtype_sum
Model can no longer access main Matlab workspace.
Can work from matlab base workspace or fake one with a data dictionary.
Capture all data and store it in a container.
Model window -> File -> model properties -> Data dictionary.
Exercise
E-17
switch_control
Add a new datatype alias
Need to write script per the solution.
Need to modify port to generate same type as signal setting.
Check code for signal type.
Didn't mention lower/uppercase in solution.
Creating Custom Storage Classes
Creating a Simulink data class package
User-Defined Custom Storage Classes
Using a custom storage class in a Simulnk model
Creating a custom storage class
Design a custom storage class
Workflow
2. Enable custom storage classes in your new package.
1. Create a new data class package
3. Create custom storage classes for your new data class package
Hiearchy
Simulink data class package (mySDCPackage)
Class (Signal)
Property 1 (property value)
Property 2 (property value)
Property 4 (property value)
Class (Parameter)
Property 3 (property value)
Copy existing class
Use copy_sdc_files.m
Bus Object and Model Referencing
Controlling storage class of bus signals
Controlling data type of the bus signals
Bus signals and model referencing
Generate code for models containing nonvirtual buses.
Use data objects to set the storage classes of nonvirtual bus signals
Use bus objects to set the data type of signals in nonvirtual buses.
Generate code for models that reference other models with model referencing.
Creating Bus Objects
Use "add a bus" and "Add a signal" buttons to generate new signals.
Add-> Simulink Bus
Use the model explorer
Launch Bus Editor (button)
Assigning Bus Objects to items in the Simulink Model
Select bus by name from pull-down list
Parameters -> Signal Attributes
I/O blocks and Bus Creator blocks
Always check "Output as nonvirtual bus"
Storage Class of Bus Signals
Leave the Data type of the data object as "auto"
Create a Simulink.Signal object in the base workspace with the same name as the signals.
Check "Must resolve to Simulink signal object"
Name bus signals in the model
Generate the code.
Set the Storage class (CLI)
Customizing Generated Code Architecture
Generating reusable code
Controlling Simulink code partitioning
Simulink model architecture
Generate reusable code for a subsystem or an entire model
Partition code for subsystems into separate functions
Code placement options
Control code placement for custom storage classes.
A Simulink Model May contain
S-functions
MATLAB function bocks
Non-virtural subsystems
Model references.
Stateflow charts
Controlling code Partitioning
Non-virtual subsystems (such as atomic, enabled, and triggered subsystems)
Applicable to atomic modules such as
Stateflow charts
Matlab Function blocks
Subsystems MUST be atomic.
How?
Mask the subsystem
Reusable function
Make it atomic
Input seperate parameters into mask
Delete extraneous block copy and duplicate original
Put instance-specific parameters in the mask subsystem workspace.
Store common function in library
Subsystems
Copy original (from a library)
Mask instance-specific parameters
Has to be atomic
Model Refrencing
Parent model has multiple references to same child system
Set up to partition code this way easier
Subsystem prep
Delcare input arguments using model workspace
Use model explorer.
Check "Model Reference Input arguments"
Parent Prep
Change arguments in parent to different numbers
Use the Model Block
Data objects
Modular 7 files
Compact: 5 files
Compact w/ separate data file
Code Generation -> Code Placement
How?
Code Generation -> Code Placement
Data definition: .h
Data Declaration: .c
Specify files
Use Model Explorer
Set to "volitile"
Can generate separate files
Exercise
Delete/copy
Mask the subsystem
Make it atomic
E-21
Find block parameters
Should get a common function
Advanced Customization Techniques
Modifying code generation template (CGT) files
Custom file proccessing
The code generation process
Add user-defined components to specific parts of generated code
Customize the organization of generated code
Modifying custom file proccessing (CFP) templates
The Code generation process
Change the way code is generated for a particular block.
Use the TLC
Perform large-scale customization
Modify the way the code is generated in a global sense.
Inline S-functions in your model
Embedded Coder
TLC
Custom file defiitions
model.rtw
model.c
Custom File Processing
Organize generated code into sections
Generate virutally any type of source or header file
Gnerate a main program module
Generate code to read and write model inputs and outputs
Generate code to call model functions such as model_initialize, model_step, etc
Generate custom file banners
Obtain information about the model and the files being generated from it
Acronyms cont.
CGT Code Generation Template
CFP Custom File Process
API Application Programming Interface
TLC Target Language Compiler
Organization's title, copyright's etc.
Hard-set for target Real-Time System, etc.
Custom File Process
Custom Generation Template
Components
CFP Templates
Code template API
Model code
model.rtw
CGT Files
Code Generation Template
Double %% is a comment, not %.
Is simmilar to html with <><\> tags
Edit my_ert_code_template.cgt
Templates for code, data, source, and header files
%<LastModifiedDate>
File Processing Templates
example_file_process.tlc
test_cfp.tlc
Contains macros and snippets to insert
Writes out buffers as needed
Targets specific file/code
Assembles code into buffers
Doc search: "Template symbols and rules"
Custom Targets
Custom target development process
Motivation for custom targets
Identify the components of a new target
Create required target files for real-time deployment to an Arduino Uno board
Deploying code to an Arduino Uno board
Creating a custom Arduino target
Motivation
Support I/O devices on the target hardware using custom blocks
Generate code for a specific CPU/board using a specific compiler/linker/debugger
Configure the build process for a special compiler
Turnkey targets
Easy downloading of generated standalone executables with 3rd-party debuggers
I/O driver support out of the box.
User-controlled placement of an executable in FLASH or RAM
Support for target visibility and tuning.
A harness (main) that manages timers/interrupts
driver routines inlined as S-functions
Needs the following elements
make file
Exersize
Add an abstract to a header file
E-25
Arduino IDE
Need Matlab commands to do all of that nonsense.
Put in verbose mode
Development Process
Add system target file
Add toolchain target configurations
Create required target files
Create target directory structure
Add supporting files.
Integrating Device Drivers
Customizing device driver components
Using legacy code tool
Test the device driver block
Develop a device driver block for Arduino target
Typically written in C
Improving code efficiency and compliance
Hardware implementation parameters
The model advisor
Verify compliance with standards and guidelines
Test and prove efficency
Compliance with standards and guidelines
The model advisor
Goes through code vs. checks
Takes you to specific controls to fix issues.
DO 178c
Compliant to safety standards
Suitable for activities
2 use cases
Checks vs. various coding standards.
Device driver overview
Signal in Simulink format
Device driver block
Signal in device format
device
Simulink block
Device drivers in generated code
Terminate
Write to O
Read from I
Initialize I/O
Legacy Code Tool
Specifies how to build System function block
edit lct_script
Fill out a form structure
doc legacy_code
LCT Legacy Code Tool (script)
Defines harness into legacy code: init, output, start, header, etc.
>> edit fd_func.c >> edit fd_func.h >> doc legacy_code
Performs a scripted block build
Writes S-function
Writes TLC, CFP, CGT for C-code generation.
Compiles to a .mexw64
Writes s-function that runs .mexw64
Process
Compile to binary
Generate C/Matlab exectuable
Insert hook functions
Fill out form for location and compile flags
Create a TLC file that can generate from it
Create a block that can call it
Register with RT Workshop
Can auto-stub driver calls in simulation