0% found this document useful (0 votes)
9 views

Sim U Link Conversion Tutorial

This document provides an overview of converting Simulink models to RSCAD components. It discusses the MATLAB and Simulink packages required, requirements and considerations for the Simulink model, and restrictions. It then walks through the process of generating C code from the Simulink model and importing it into RSCAD to create a component that can be simulated. Key steps include generating C code with Embedded Coder, importing the model into RSCAD with CBuilder, and simulating the case with the new Simulink-CBuilder component.

Uploaded by

dongyu.li1992
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Sim U Link Conversion Tutorial

This document provides an overview of converting Simulink models to RSCAD components. It discusses the MATLAB and Simulink packages required, requirements and considerations for the Simulink model, and restrictions. It then walks through the process of generating C code from the Simulink model and importing it into RSCAD to create a component that can be simulated. Key steps include generating C code with Embedded Coder, importing the model into RSCAD with CBuilder, and simulating the case with the new Simulink-CBuilder component.

Uploaded by

dongyu.li1992
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Simulink to RSCAD Conversion

An Introductory Tutorial
TABLE OF CONTENTS

TABLE OF CONTENTS .............................................................................................................................. 2


1 Introduction ........................................................................................................................................... 3
2 MATLAB and Simulink Packages Required ........................................................................................ 4
3 Simulink Model Requirements ............................................................................................................. 5
4 Simulink Model Design Considerations ............................................................................................... 6
5 Simulink Model Restrictions ................................................................................................................ 7
6 Simulink C Code Generation ................................................................................................................ 8
7 Importing Simulink Model into RSCAD ............................................................................................ 17
8 Simulating RSCAD Case with Simulink-CBuilder Component ......................................................... 22
Appendix A: Troubleshooting Common Error Messages ........................................................................... 26
Appendix B: Building S-Functions using Simulink S-Function Builder .................................................... 29
REFERENCES ........................................................................................................................................... 36

-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.

Package Version MATLAB Release


MATLAB 7.14 (R2012a)
MATLAB Coder 2.2 (R2012a)
Simulink 7.9 (R2012a)
Simulink Coder 8.2 (R2012a)
Simulink Control Design 3.5 (R2012a)
Control System Toolbox 9.3 (R2012a)
Embedded Coder 6.2 (R2012a)

Table 2.1: Required MATLAB and Simulink Packages

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:

 Simulink control models only


 The Simulink model must use a fixed-step solver
 The Simulink model must only use inline S-Function blocks(if any)
 The Simulink model must be converted to ANSI C code using MATLAB’s Embedded
Coder

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:

1. Configuring code generator


2. Re-evaluating simulation output
3. Code generation

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.

Figure 6.1: A simple integrator model created in Simulink

Figure 6.2: Simulink simulation output for simple integrator model

-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.

6.1 Configuring Code Generator


This section will describe how to configure the MATLAB and Simulink Coders in order to
generate the C code required by CBuilder’s Simulink import tool. The tutorial will begin by
assuming that a Simulink model (i.e. “simpleIntegrator.mdl”) has already been created and is
opened in the Simulink Model Editor window.

a. Under “Simulation” select “Configuration Parameters”

Figure 6.3: Simulink Workspace menu bar

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.

Figure 6.4: Configuration Parameter window

-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.

Figure 6.5: Configuration Parameters window – “Solver” node

2) Click on the “Code Generation” node


a. Under “Target selection” on the right:
 Click on “Browse” button beside the “System target file” text field
 A popup window appear as in figure 6.7
 Select the “Embedded Coder” from the list and click “OK”

b. Near the bottom of the window, select “Generate code only”

Note: The “Description” under “Target Selection” should change to “Embedded Coder”

Figure 6.6: Configuration Parameter window – “Code Generation” node

-10-
Figure 6.7: System Target File Browser pop-up window

3) Expand the “Code Generation” node

4) Click on the “Symbols” sub-node under “Code Generation”


a. Under “Identifier format control”, make sure the arguments in the text fields match the
image in figure 6.8.

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.

Figure 6.8: Configuration Parameter window – “Symbols” node

-11-
5) Click on the “Interface” sub-node under “Code Generation”

a. Under “Software environment” on the right:


 Make sure “C89/C90 (ANSI)” is selected from the “Code replacement library”
dropdown box (figure 6.9)
 Under “Support” Select the following supports for the “simpleIntegrator” model
i. floating-point numbers
ii. continuous time

b. under “Code Interface” on the right


 Select “Single output/update function”
 de-select “Terminate function required”

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.

Figure 6.9: Configuration Parameter window – “Interface” node

-12-
6) Click on the “Code Style” sub-node under “Code Generation”
a. Select “Preserve extern keyword in function declarations”

Figure 6.10: Configuration Parameter window – “Code Style” node

7) Click on the “Templates” sub-node under “Code Generation”


a. Under “Custom templates” on the right:
 Select “Generate an example main program”

Figure 6.11: Configuration Parameter window – “Templates” node

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.

Figure 6.12: Run Simulink model Simulation

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.

6.3 Code Generation


Once the configuration parameters for code generation have been set and the desired output has
been verified, the Simulink C code can be generated for the model.

To start the code generation click on Tools -> Code Generation -> Build Model

Figure 6.13: Generate Simulink C code from Simulink 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.

Figure 6.14: Example code generation message error

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.

Name Example File Description

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

Table 6.1: Typical C file generated by Embedded Coder

* Important files for the Simulink to CBuilder conversion process.

-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.

7.1 Importing Simulink C Model


1) Start RSCAD and launch CBuilder

a. In CBuilder, go to Tools -> Import Simulink model

Figure 7.1: Opening Simulink import tool from CBuilder

b. The following Simulink to RSCAD conversion tool should appear

Figure 7.2: Simulink to RSCAD conversion tool

-17-
2) Under “Import Simulink Component”:
a. Click the “Browse” button

Figure 7.3: Finding Simulink model to import

b. Use the file browser to navigate to the folder containing the C code for the Simulink model
(i.e. simpleIntegrator_ert_rtw)

c. Select the modelName.c file (i.e. simpleIntegrator.c)

Figure 7.4: Choosing main Simulink model C file

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)

3) Under “New RSCAD Component”:


a. Enter a file name for the new component. File name must be at least three characters, but
no more than ten (e.g. simpleInt)

Figure 7.5: Enter new RSCAD component name

-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)

Note: Default location “RTDS_USER\ULIB”

b. Click on the second “Browse” button to select a location to save the new RSCAD
component’s source files (.c and .h)

Note: Default location “RTDS_USER\BIN\CMODEL_SOURCE”

Figure 7.6: Saving Simulink RSCAD component

5) Click “OK” to begin import process

6) If import process is successful:


a. A popup message will appear confirming a successful conversion. Click “OK”

Figure 7.7: Successful Simulink to RSCAD conversion

b. A second popup message will appear indicating the time step detected for the model. Click
“OK”

Figure 7.8: Time step detected by conversion process

-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).

7.2 Simulink-CBuilder Component Schematic


The Simulink RSCAD conversion tool will create a generic CBuilder component similar to
figure7.9.

Figure 7.9: Generic Simulink- CBuilder component

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.

1) Click “Open Component” in CBuilder


a. Browse to and select the “.def” file of the new Simulink-CBuilder component (e.g.
simpleInt.def)

Figure 7.10: Open CBuilder component

-20-
2) Select the “C File Associations” tab in the right window pane and click the “Edit” icon

Figure 7.11: Opening CBuilder .c file

3) The CBuilder component code should appear in a text editor

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.

Figure 7.12: Mapping Simulink IO to generic Simulink-CBuilder I/O pins

-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.

8.1 Simulink Model to CBuilder Component


1) Create a Simulink model in Simulink (Note: control models and fixed-step only)
2) Generate embedded C code for Simulink model through Simulink
3) Import Simulink model into RSCAD through CBuilder

8.2 Using Simulink-CBuilder Components in RSCAD Draft


1) Start RSCAD

2) If the Simulink-CBuilder component was not already compiled in CBuilder, do the


following:

a. Launch CBuilder
b. Open new component (figure 7.10)
c. Click on “C File Association” tab (figure.7.11)

d. Click “Compile” icon

3) Launch Draft

a. Create new case

b. Add Simulink-CBuilder component to Circuit Canvas


i. Right click on an empty space in Library Canvas
ii. From popup menu, go to:
 Add Component -> User
iii. Select Simulink-CBuilder “.def” file from File Browser (e.g. simpleInt.def)
iv. Drop Simulink-CBuilder component on Circuit Canvas

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.

e. Compile the Draft case

8.3 Simulating RSCAD Case containing a Simulink -CBuilder Component


1) Launch Runtime
a. Select “Runtime for last Draft Compile” from the Runtime welcome window and click
“OK”
b. Add plots, meters, slider, etc. to Runtime case
c. Run Case
Note: Optionally “Breakpoint Mode” can be used to capture and view data in increments

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.

Figure 8.1: RSCAD’s Simple Integrator Runtime output

-24-
Figure 8.2: Simulink simulation output for Simple Integrator

8.4 Simulating Runtime Case using Breakpoint


This section provides a small introduction to using “Breakpoint Mode” in RSCAD Runtime.
Breakpoint Mode provides an alternative method to running a RSCAD case which allows the
user to capture and view data in increments. Breakpoint Mode may be useful if the user is
interested in capturing only the first few step or seconds of a plot. The following procedure will
assume an RSCAD Runtime case has already been loaded.

1) In the Runtime menu bar, go to:


 Breakpoint -> open

Figure 8.3: Open Breakpoint Mode

2) Click the “Options” button in Breakpoint Mode window

Figure 8.4: Open Breakpoint Mode Options

-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

Figure 8.5: Configure Breakpoint Mode options

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.

2. Non-Inlined S-Function Detected

Steps to resolve:

a) Refer to Appendix B for converting non-inlined S-Function blocks to inline.

-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:

a) Click ok to resume conversion.


b) Copy the S-Function specific files (wrapper files and any other c files related to
S-Function) from the source location provided by the warning message and paste them in
the target location indicated by the warning message.

-28-
c) Follow the steps in section 8 to simulate a case with the converted component

5. Unsupported Library Compile Error

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.

Creating S-Function using S-Function Builder


The S-Function Builder is a Simulink block that automatically builds an S-function from C
source code. The S-Function Builder can be configured to generate the “.tlc” file for a generated
S-Function block.

A simple S-Function can be created by using the following procedure:

1) Set the MATLAB current working directory to where you wish to create S-Function.
(“Current Folder” pane within main Matlab window)

2) Create a new Simulink model (or open any existing model).

-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

Figure B.2: Simulink model editor

-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).

Figure B.3: Simulink S-Function Builder dialog

5) Enter a name for the S-Function in the text box provided.

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).

Figure B.4: Configuring input ports under Data Properties tab

-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)

Figure B.5: Configuring output ports under Data Properties tab

Note: For more advance configurations options, please refer to MATLAB’s


documentation for Building S-Functions automatically.
http://www.mathworks.com/help/simulink/sfg/building-s-functions-automatically.html

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).

Figure B.7: Building the S-Function

-34-
The S-Function Builder will create three files in addition to a Mex file in the current working
directory.

Using Generated S-Function in Simulink Models

To use the generated S-Function in a model:

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.

Figure B.8: Selecting S-Function block from 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-

You might also like