Sim U Link Conversion Tutorial
Sim U Link Conversion Tutorial
An Introductory Tutorial
TABLE OF CONTENTS
-2-
1 Introduction
Simulink is a graphical block diagram modeling tool for building, simulating and analyzing
systems. MATLAB and Simulink are developed trademarks of The MathWorks Inc.
RSCAD provides the ability to import Simulink models into RSCAD’s library through CBuilder.
MATLAB’s Embedded Coder makes it possible to translate a Simulink model into C code which
can then be used to generate a CBuilder component. Presently, CBuilder’s Simulink import tool
only handles the conversion of Simulink control models to RSCAD CBuilder components.
This tutorial assumes that the user is familiar with MATLAB, Simulink and RSCAD. The tutorial
is broken up into several sections. Section 2 lists the MATLAB and Simulink software required to
translate a Simulink model into C code. Sections 3 through 5 will cover Simulink model
requirements, design considerations and restrictions. Section 6 will step through the process of
converting a Simulink model into C code. Section 7 will introduce CBuilder’s Simulink
conversion tool and the process of importing a Simulink model into CBuilder to generate a
CBuilder component. Finally, section 8 will summarize the entire process from generating C code,
importing a Simulink model and simulating a RSCAD case with the converted component.
-3-
2 MATLAB and Simulink Packages Required
To generate Simulink C code that is compatible with CBuilder’s Simulink import tool, several
MATLAB and Simulink packages are required. Table 2.1 lists the basic packages and minimum
versions needed to create Simulink control models and generate compatible C code for
CBuilder’s import tool.
To ensure compliant C code generation compatible with CBuilder’s Simulink import tool,
MATLAB Coder 2.2 or later, Simulink Coder 8.2 or later, and Embedded Coder 6.2 or later are
required.
-4-
3 Simulink Model Requirements
In order to import a Simulink model into RSCAD through CBuilder, the Simulink model must
follow several requirements. These requirements are the following:
Currently, CBuilder’s Simulink import tool is designed to import Simulink control models only.
Therefore, it does not support the conversion of Simulink power system models or components
from the Simulink power system libraries into a CBuilder component.
Simulink can only generate C code from a model if a fixed-step solver is selected. Solvers are used
to determine the time of the next simulation step. When a fixed-step solver is used, the time of next
simulation step is computed by adding the fixed step size to the current time.
If the Simulink model has any non-inline S-Function blocks it must be converted to inline (see
Appendix B) before generating the code for the model, CBuilder’s Simulink import tool is limited
to handle only inline S-Function blocks.
The Embedded coder is used to build fast and efficient C code. CBuilder’s Simulink import tool
relies on the C code format produced by MATLAB’s Embedded Coder to generate CBuilder code
for the component.
-5-
4 Simulink Model Design Considerations
There are certain design considerations which must be taken into account when designing or
re-designing a Simulink model that will be simulated on the RTDS using RSCAD.
Buffer memory
Using unsigned chars
Multi-rate models
Just like any other hardware system, there is a limit to physical memory. In Simulink, certain
Simulink components may reserve memory for their buffers. The amount of memory allocated
depends on the Simulink component and the Simulink model. A user can manually adjust the
buffer size to optimize performance. However, you should avoid allocating large amount of
memory for a component’s buffer. See Simulink component’s properties for details about setting
the buffer size.
Simulink uses the “unit8” or “uint8_T” data type to represent unsigned chars. Due to the difference
in handling of unsigned chars by Simulink and RSCAD, the “unit8” or “uint8_T” data type must
be avoided if selecting the data type for a component’s input or output ports and in MATLAB
code.
A multi-rate model is one where the components in the model may run at different time steps.
However, in order to generate C code from a model, a fixed-step solver must be chosen (i.e. a
single fixed-step size). To alleviate this problem, one option would be to determine a single
fixed-step size n, where n is the lowest common multiple of all the time-steps involved in the
model. Always re-run the simulation for the Simulink model after changing the time step to ensure
the desired output is maintained.
-6-
5 Simulink Model Restrictions
There are several limitations of the MATLAB and Simulink Coders that affect the design of a
Simulink model. These restrictions are the following:
Simulink cannot generate C code for Simulink models that use a variable-step solver
Simulink cannot generate C code for Simulink models that have algebraic-loops
Simulink cannot generate C code for a multi-rate Simulink model if a single fixed-step size
cannot be determined
Simulink cannot generate C code for Simulink models if the libraries for a component are
missing
As mentioned earlier, Simulink can only generate C code from a model if a fixed-step solver is
selected. When a variable-step solver is selected, the step size can change dynamically in response
to the system. The next simulation time-step is determined by solving a set of ordinary differential
equations that represent the model. However, in real-time applications a fixed-step size is
preferred because it is difficult to map a variable-step size to a real-time clock.
In Simulink, algebraic-loops are caused when the output of a component feeds its own input
through an input port with direct feed-through, either directly or indirectly. Direct feed-through
means, that the inputs of the component directly control its own output. For example, the
summation block has direct feed-through inputs. Figure 5.1 show an example of a simple
algebraic-loop. Equation 5.1 shows that the output of figure 5.1 relies directly on its own input to
the summation block.
1 +- 1
x y
K1
Figure 5.1: Simple algebraic-loop
( ) [ Eq. 5.1 ]
Simulink does not support the code generation for Simulink models with algebraic-loops. See
Simulink documentation for detecting algebraic-loops in a model and techniques to resolve
algebraic-loops.
For multi-rate models, Simulink can only generate C code if a single fixed-step size can be
determined. See section 4, Simulink Model Design Considerations, for options.
-7-
6 Simulink C Code Generation
Once a Simulink model is constructed that follows the guidelines provided in the previous
sections, the model can be converted into C code using MATLAB’s Embedded Coder. Translating
a Simulink model into C code is a three step process:
The following sections will describe the three step process for converting a Simulink model into C
code. This tutorial will use a simple integrator model designed in Simulink called
“simpleIntegrator.mdl” (see figure 6.1) to illustrate the process. The simulation output obtained for
the “simpleIntegrator” model in Simulink is shown in Figure 6.2.
-8-
Note, that the screenshots and procedure described in this section was done using the MATLAB
and Simulink packages (and versions) listed in table 2.1 in Section 2. The graphical interface and
process described should be similar for later versions of MATLAB and Simulink.
b. The “Configuration Parameters” window will appear. On the left-hand side of the
window, there is a tree structure with several nodes to allow a user to configure how
a simulation is run and how the C code is generated.
-9-
1) Click on the “Solver” node
a. Under “Solver options” on the right:
choose “Fixed-step” from the “Type” dropdown box
Note: The time-step can be manually set by changing the “Fixed-step size” text field. The
default value is “auto”. When auto is set, Simulink will choose the time-step. However, in
order not to miss significant behaviour, the time-step may have to be manually adjusted.
Note: The “Description” under “Target Selection” should change to “Embedded Coder”
-10-
Figure 6.7: System Target File Browser pop-up window
Note: The “Identifier format control” panel manages part of the formatting of C code
generated by Simulink, such as variable names. Different argument in these fields may
affect the parsing of C code by CBuilder’s import tool.
-11-
5) Click on the “Interface” sub-node under “Code Generation”
Note: Settings for “Support” may vary depending on the components used in the Simulink
model. A popup error message will be displayed before code generation to help indicate any
“Support” options that have not been selected for the model.
-12-
6) Click on the “Code Style” sub-node under “Code Generation”
a. Select “Preserve extern keyword in function declarations”
8) Click “Apply” and then “OK” at the bottom of the “Configuration Parameter” window
-13-
6.2 Re-Evaluate Simulation Output
After changing any setting in the “Configuration Parameter” window, it is good practice to ensure
that the model is still producing the desired output before code generation. Note, this step will not
catch all “Code Generation” setting errors, but will catch some errors such as invalid Fixed-step
size for a multi-rate model.
To re- run the Simulink simulation for a model, go to the toolbar at the top of the Simulink Model
Editor window and click the “Start Simulation” button.
A pop-up error box will appear if any configuration parameters are invalid. Errors can be fixed by
re-opening the “Configuration Parameter” window and changing the indicated settings.
To start the code generation click on Tools -> Code Generation -> Build Model
-14-
If any errors are detected by the Code Generator, such as missing libraries or incorrect code
generation settings, a message box will appear indicating the error. For Instance, for the
“simpleIntegrator” model, if “continuous time” was not chosen as one of the support for the model
(see figure 6.9) during the code generator configuration stage, the error message in figure 6.14
would appear.
The message box displays a list of errors found by the code generator. Details about each
individual error can be found by clicking on an item in the list. The details indicate what the error
is and options to fix the error.
If the Simulink model is converted to C code without any errors, a message will appear in the
Command Window of MATLAB indicating a successful conversion. Also, a new folder will
appear in the Current Folder window pane of MATLAB, this folder will contain the generated C
code for the model. The new folder will use the naming convention model name followed by the
suffix “_ert_rtw” (e.g. simpleIntegrator_ert_rtw).
Figure 6.15: Main MATLAB window displaying successful Simulink C code generation
-15-
The new folder will contain several .c and .h files generated by the Embedded Coder. Several of
these files will have filenames that begin with the Simulink model name. Table 6.1 lists the files
usually generated by the Embedded Coder. Additional files may be generated depending on the
components used in the Simulink model.
modelName.c * simpleIntegrator.c This file contains all the major function to implement
the Simulink model
modelName.h * simpleIntegrator.h This file contains the interface for all the major
functions and data structure declarations
modelName_data.c simpleIntegrator _data.c These files contain data structures specific to model
modelName_private.h simpleIntegrator _private.h
ModelName_types.h simpleIntegrator _types.h
ert_main.c * ert_main.c An example main program generated by the Embedded
Coder
-16-
7 Importing Simulink Model into RSCAD
Importing a Simulink model into RSCAD is accomplished through CBuilder. CBuilder requires
the Simulink C code generated by MATLAB’s Embedded Coder and generates a single CBuilder
component.
The first section of this chapter will describe the process of importing a Simulink model into
CBuilder using the “simpleIntegrator” example. The second section will look at the generated
Simulink-CBuilder component.
-17-
2) Under “Import Simulink Component”:
a. Click the “Browse” button
b. Use the file browser to navigate to the folder containing the C code for the Simulink model
(i.e. simpleIntegrator_ert_rtw)
Note: To ensure the right file is selected, open the modelName.c (i.e.
simpleIntegrator.c) file in a text editor. The modelName.c file will contain functions
such as modelName_step(void), modelName_initialize(void)
-18-
4) Under “Save RSCAD Component” (Optional):
a. Click on the first “Browse” button to select a location to save the new RSCAD
component’s definition file (.def)
b. Click on the second “Browse” button to select a location to save the new RSCAD
component’s source files (.c and .h)
b. A second popup message will appear indicating the time step detected for the model. Click
“OK”
-19-
Note: The default unit of time used by MATLAB is in seconds and the default unit of time used by
RSCAD is in microseconds. Figure 7.8 show the fixed time-step chosen and set by the user in
Simulink (see figure 6.5).
Note: The number and type of input/output nodes for the converted model will be directly
proportional to the number of signals contained in the input/output blocks of the Simulink model.
For example If the Simulink model has n number of signals in one or more input/output block, then
for each such block the conversion tool will create n input/output nodes indexed from 1 to n with
the same name as in the Simulink model. The example simpleInt component will just have 3 output
nodes (each output block contains one signal) as there is no input blocks attached for the model in
Simulink.
The top of the generic component is indicated by a notch. Left of the notch, are the input pins
labeled from 1 to n, from top to bottom. Right of the notch, are the output pins labeled from n to 1,
from top to bottom. Determining the IO mapping from the Simulink model to the
Simulink-CBuilder component pins can be done from CBuilder .c file.
-20-
2) Select the “C File Associations” tab in the right window pane and click the “Edit” icon
4) Scroll down near the bottom of the code to the “CODE” section
At the top of the CODE section the mapping for the inputs are defined and at the bottom the
mapping for the outputs are defined. For example, figure 7.12 shows, on the input side, pin 1 map
to speed, pin 2 map to volt and pin 3 map to current. On the output side, pin 1 map to the x position,
pin 2 map to the y position and pin 3 map to power.
-21-
7.3 Importing Simulink Models from multiple Simulink Releases
When a Simulink model is converted to RSCAD, all C code and library files are stored in
“RTDS_USER/BIN/CMODEL_SOURCE”. All converted models use the same library files. If
the Simulink/Matlab software version changes and a new Simulink model is converted, the
library files in “RTDS_USER/BIN/CMODEL_SOURCE” will be modified. As a result of new
library files, any converted components based on other Simulink/Matlab versions may not run
anymore. Therefore, it is important to recompile all RSCAD-Simulink components in the
“CMODEL_SOURCE” folder to ensure that all models are compatible with the latest library files
in the “CMODEL_SOURCE” folder. This involves obtaining the original Simulink model (i.e.
“.mdl”), re-generating the C code using the new Simulink release (see section 6) and
re-importing the C coded into CBuilder.
-22-
8 Simulating RSCAD Case with Simulink-CBuilder Component
This section will summarize the three basic steps for integrating a Simulink model into RSCAD.
The three steps are importing a Simulink model into CBuilder, creating a Draft case containing a
Simulink-CBuilder component and simulating a Runtime case with a Simulink-CBuilder
component.
a. Launch CBuilder
b. Open new component (figure 7.10)
c. Click on “C File Association” tab (figure.7.11)
3) Launch Draft
c. Label Simulink-CBuilder component’s pins (see figure 7.12 for IO mapping example)
-23-
d. Set time step according to Simulink model (figure 7.8)
i. Right click on an empty space in Circuit Canvas
ii. From popup menu, go to:
Circuit -> Parameters
iii. Set time step
Note: Some Simulink models are sensitive to the time step selected in Simulink.
During C code generation, the value of certain components may be computed and
hardcoded. The value hardcoded may depend on the time step used at code
generation. Therefore, it is important verify the correct behaviour of a model using
the detected time step before experimenting with different time steps.
Figure 8.1 displays the RSCAD Runtime output for the “simpleIntegrator.mdl” shown in section 6. These
results were obtained using Runtime’s Breakpoint Mode in order to capture and compare the first ten
seconds of the RSCAD output to the Simulink output in figure 8.2.
-24-
Figure 8.2: Simulink simulation output for Simple Integrator
-25-
3) Select the following option from the Breakpoint Mode options:
Collect plot data on resume
Resume to Breakpoint: Specify total simulation time in seconds
4) Enter desired simulation time in text field beside “until total simulation time”
5) Click “Resume to breakpoint” button to run the simulation for specified time or
time steps
-26-
Appendix A: Troubleshooting Common Error Messages
The “tmp_workspace” folder is used in the CBuilder code generation process to hold temporary
and modified versions of the MATLAB C code. If the CBuilder code generation process is
successfully, the “tmp_workspace” folder will be created and then deleted at the end of the
process. If the process is not successful, the folder may remain in the model’s folder. Unexpected
behaviour by the Simulink conversion tool or improper CBuilder code generation may occur if
the “tmp_workspace” folder exists in the MATLAB model’s folder before CBuilder code
generation.
1. No I/O Found
Steps to resolve:
a) Go back to Simulink and check if proper input or output blocks have been used in the
model. If there is no such I/O attached, assign at least one output or input block to the
model.
b) Check if a “tmp_workspace” folder has been created in the model’s generated code folder
(section 6.3). If present, delete the entire “tmp_workspace” folder.
c) Re-generate the code. In Simulink, re-check the configuration parameters and build
model again according to Section 6.
Steps to resolve:
-27-
b) Check if a “tmp_workspace” folder has been created in the model’s generated code folder
(section 6.3). If present, delete the entire “tmp_workspace” folder.
c) Re-generate the code. In Simulink, re-check the configuration parameters and build
model again according to Section 6.
3. Import Error
Steps to resolve:
a) Go back to Simulink and repeat the steps in section 6 to set the correct configuration
parameters.
b) Check if a “tmp_workspace” folder has been created in the model’s generated code folder
(section 6.3). If present, delete the entire “tmp_workspace” folder.
c) Re-generate the code in Simulink and try to convert the model once again in RSCAD.
4. Import Warning
This is a very rare warning message provided only when the model has S-Function blocks and
the code generation for the model and conversion takes place on two different computers or with
two different user accounts.
Steps to take:
-28-
c) Follow the steps in section 8 to simulate a case with the converted component
The C library “stdlib.h” is not supported by RSCAD’s compile in the CBuilder code section. In
some cases, the C code generated by MATLAB may include the “stdlib.h” library. If this C
library is included in the model that CBuilder is trying to compile an error message box will
appear (See image below).
One possible solution is to look through the model’s file generated by RSCAD, and remove the
line which includes the “stdlib.h” library (i.e. “#include <stdlib.h>”).
Note: This solution will only work if the model is not calling any function from the “stdlib.h”
library.
-29-
Appendix B: Building S-Functions using Simulink S-Function Builder
Simulink allow the creation of custom Simulink blocks called S-Functions. These custom function blocks
can be either considered inline or non-inline. Inlined function blocks, such as the Simulink block provided
in the Simulink library, have a “.tlc” (Target Language Compiler) file associated with the function block.
The “.tlc” file tells the TLC how to encode the block for a specific target language. Non-inline function
blocks do not have an associated “.tlc” file.
During code generation, if the coder does not find the associated “.tlc” file for a specified S-Function
block, the S-Function will be treated as a non-inlined function. For code generation of non-inline function
blocks, Simulink must include a special data structure called “simstruct” which is not yet supported by
Cbuilder’s Simulink import tool. On the other hand, if the S-Function provides a “.tlc” file, code for
the S-Function block will be embedded into the generated code (i.e. inline).
There are two methods to convert non-inline S-Function blocks to inline (i.e, creating a “.tlc”):
1. Write a “.tlc” file for the S-Functions blocks (fully inlined S-Function )
2. Build a S-Function using the S-Function Builder which will generate a “.tlc” file (wrapper
inlined S-Function)
The first method requires that the user has a good understand of how Simulink works and the
API available for creating S-Functions. The second method provides a simpler option for
creating inline S-Functions. The following sections will explain how to build an S-Function
using the S-Function Builder and how to use the S-Function block.
1) Set the MATLAB current working directory to where you wish to create S-Function.
(“Current Folder” pane within main Matlab window)
-30-
3) Drag and drop the “S-Function Builder” block from the “User-Defined Functions”
section of the Simulink Library Browser (figure B.1) into the Model Editor window
(figure B.2).
Figure B.1: Selecting S-Function Builder block from Simulink library browser
-31-
4) Double click on the new S-Function Builder block in the Model Editor window to open
the S-Function Builder Dialog (figure B.3).
6) Select the “Data Properties” tab. The Data Properties tab is used to configure input and
output ports of the S-Function Builder block (figure B.4).
-32-
Note: Multiple signals can be provided to or outputted from the S-Function block through
either multiple input/output ports or by configuring a single port to handle multiple
signals. A port can be configured for multiple signals by editing the “Dimension”,
“Rows” or “Columns” parameters under the “Input ports” and “Output ports” tabs, within
“Data Properties”. For example, if the S-Function block should have one input port that
take in one signal, and one output port that produces two signals, by default the block’s
input should be already configured for one input signal (See figure B.4). However, to
configure the S-Function block’s output port to produce two signals; select the “Outputs
ports” tab and increase the “Rows” parameter to two (figure B.5)
7) If the implementation for the S-Function block will rely on additional custom code
residing in a file, you can add these file through the “Libraries” tab. Select the “Libraries”
tab, and under the “Library/Object/Source files” section add the files you would like to
reference. Note, you may even add any additional header files your S-Function code may
require under the “Include files and external function declarations”.
8) Select the “Outputs” tab. The “Output” tab provides an area to write the code to compute
the output for the S-Function that will be executed each simulation time step. For
example, considering the data properties setting from above figures (figure B.4 and B.5).
We will apply gain to incoming signals and route it to output ports of the S-Function
(figure B.6).
Note: The code to compute the S-Function’s output can call any function from the
custom code file added through the “Libraries” tab.
-33-
Figure B.6: Computing outputs for S-Function
9) Next, select the “Build Info” tab. Under the section “Build options”, check the option to
“Generate wrapper TLC” (figure B.7).
10) Finally, click on “Build” button in the top right of the dialog window to generate the
S-Function (figure B.7).
-34-
The S-Function Builder will create three files in addition to a Mex file in the current working
directory.
1) Replace the S-Function Builder block in the Model Editor window with the S-Function
block found in “User-Defined Functions” of Simulink Library Browser.
2) Double click the S-Function block in the Editor Window to open the “Function Block
Parameters” dialog (figure B.9).
-35-
Figure B.9: Function Block Parameters dialog
3) Enter the name of the generated S-Function in the “Function Block Parameters” dialog
and click the “OK” button
4) The next time you generate the code for the model containing the generated
S-Function, the S-Function will be treated as inline S-Function due to the presence of
the “.tlc” file.
Note: If you would like to use the S-Function generated in another model, copy all the
S-Function’s generated files along with any additional code files used to build S-Function to the
desired models directory.
-36-
REFERENCES
[1] http://www.mathworks.com/products/embedded-coder/
[2] http://www.mathworks.com/products/matlab/
[3] http://www.mathworks.com/products/matlab-coder/
[4] http://www.mathworks.com/products/simulink/
[5] http://www.mathworks.com/products/simulink-coder/
[6] http://www.weizmann.ac.il/matlab/pdf_doc/ecoder/ecoder_ug.pdf
-37-