| Contents | Index |
| On this page… |
|---|
Data Interchange Using the C API |
External mode allows two separate systems, a host and a target, to communicate. The host is the computer where the MATLAB and Simulink environments execute. The target is the computer where the executable created by the code generation and build process runs.
The host (the Simulink environment) transmits messages requesting the target to accept parameter changes or to upload signal data. The target responds by executing the request. External mode communication is based on a client/server architecture, in which the Simulink environment is the client and the target is the server.
External mode lets you
Modify, or tune, block parameters in real time. In external mode, whenever you change parameters in the block diagram, the Simulink engine downloads them to the executing target program. This lets you tune your program's parameters without recompiling.
View and log block outputs in many types of blocks and subsystems. You can monitor and/or store signal data from the executing target program, without writing special interface code. You can define the conditions under which data is uploaded from target to host. For example, data uploading could be triggered by a selected signal crossing zero in a positive direction. Alternatively, you can manually trigger data uploading.
External mode works by establishing a communication channel between the Simulink engine and generated code. The channel's low-level transport layer handles the physical transmission of messages. The Simulink engine and the generated model code are independent of this layer. The transport layer and the code directly interfacing to it are isolated in separate modules that format, transmit, and receive messages and data packets.
This design allows for different targets to use different transport layers. ERT, GRT, GRT malloc, and RSim targets support external mode host/target communication by using TCP/IP and RS-232 (serial) communication. The xPC Target product uses a customized transport layer. The Wind River Systems Tornado target supports TCP/IP only. Serial transport is implemented only for Microsoft Windows architectures. The Real-Time Windows Target product uses shared memory.
About Setting Up an External Mode Communication Channel. This section provides step-by-step instructions for getting started with external mode, a very useful environment for rapid prototyping. The example consists of four parts, each of which depends on completion of the preceding ones, in order. The four parts correspond to the steps that you follow in simulating, building, and tuning an actual real-time application:
Set up the model.
Build the target executable.
Run the external mode target program.
Tune parameters.
The example presented uses the GRT target, and does not require hardware other than the computer on which you run the Simulink and Simulink Coder software. The generated executable in this example runs on the host computer in a separate process from MATLAB and Simulink.
The procedures for building, running, and testing your programs are almost identical in UNIX and PC environments. The discussion notes differences where applicable.
Set Up the Model. In this part of the example, you create a simple model, extmode_example, and a folder called ext_mode_example to store the model and the generated executable:
Create the folder from the MATLAB command line by typing
mkdir ext_mode_example
Make ext_mode_example your working folder:
cd ext_mode_example
Create a model in Simulink with a Sine Wave block for the input signal, two Gain blocks in parallel, and two Scope blocks. The model is shown below. Be sure to label the Gain and Scope blocks as shown, so that subsequent steps will be clear to you.

Define and assign two variables A and B in the MATLAB workspace as follows:
A = 2; B = 3;
Open Gain block A and set its Gain parameter to the variable A.

Similarly, open Gain block B and set its Gain parameter to the variable B.
When the target program is built and connected to Simulink in external mode, you can download new gain values to the executing target program by assigning new values to workspace variables A and B, or by editing the values in the block parameters dialog. You explore this in Tune Parameters.
Verify operation of the model. Open the Scope blocks and run the model. When A = 2 and B = 3, the output looks like this.

From the File menu, choose Save As. Save the model as extmode_example.mdl.
Build the Target Executable. In this section, you set up the model and code generation parameters required for an external mode compatible target program. Then you generate code and build the target executable:
Open Model Explorer by selecting Model Explorer from the model's View menu.
In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.
Click Configuration (Active) in the left pane.
Select Solver in the center pane. The Solver pane appears at the right.
In the Solver Options pane:
Click Apply. The dialog box appears below. Note that after you click Apply, the controls you changed again have a white background color.

Click Data Import/Export in the center pane, and clear the Time and Output check boxes. In this example, data is not logged to the workspace or to a MAT-file. Click Apply.
Click Optimization in the center pane and click the Signals and Parameters tab in the right pane. Make sure that the Inline parameters option is not selected. Although external mode supports inlined parameters, you will not explore them in this example. Click Apply if you have made any changes.
Click Code Generation in the center pane. By default, the generic real-time (GRT) target is selected on the Code Generation pane. Select the Interface tab. The Interface pane appears at the right.
On the Interface pane, select External mode from the Interface pull-down menu in the Data exchange section. This enables generation of external mode support code and reveals two more sections of controls: Host/Target interface and Memory management.
In the Host/Target interface section, make sure that the value tcpip is selected for the Transport layer parameter. The pane now looks like this:

External mode supports communication via TCP/IP, serial, and custom transport protocols. The MEX-file name field specifies the name of a MEX-file that implements host and target communications on the host side. The default for TCP/IP is ext_comm, a MEX-file provided with the Simulink Coder software. You can override this default by supplying other files. See Create a Transport Layer for External Communication in the Simulink Coder documentation for details if you need to support other transport layers.
The MEX-file arguments field lets you specify arguments, such as a TCP/IP server port number, to be passed to the external interface program. Note that these arguments are specific to the external interface you are using. For information on setting these arguments, see MEX-File Optional Arguments for TCP/IP Transport and MEX-File Optional Arguments for Serial Transport in the Simulink Coder documentation.
This example uses the default arguments. Leave the MEX-file arguments field blank.
Click Code Generation in the center pane of the Model Explorer. On the right, make sure that Generate code only is cleared, then click the Build button to generate code and create the target program. The content of subsequent messages depends on your compiler and operating system. The final message is
### Successful completion of build procedure for model: extmode_example
In the next section, you will run the extmode_example executable and use Simulink as an interactive front end to the running target program.
Run the External Mode Target Program. The target executable, extmode_example, is now in your working folder. In this section, you run the target program and establish communication between Simulink and the target.
Note An external-mode program like extmode_example is a host-based executable. Its execution is not tied to RTOS or a periodic timer interrupt, and it does not run in real time. The program just runs as fast as possible, and the time units it counts off are simulated time units that do not correspond to time in the world outside the program. |
The External Signal & Triggering dialog box (accessed via the External Mode Control Panel) displays a list of all the blocks in your model that support external mode signal monitoring and logging. The dialog box also lets you configure the signals that are viewed and how they are acquired and displayed. You can use it to reconfigure signals while the target program runs.
In this example, you observe and use the default settings of the External Signal & Triggering dialog box.
From the Tools menu of the block diagram, select External Mode Control Panel, which lets you configure signal monitoring and data archiving. It also lets you connect to the target program and start and stop execution of the model code.

The top three buttons are for use after the target program has started. The two lower buttons open separate dialog boxes:
The Signal & triggering button opens the External Signal & Triggering dialog box. This dialog box lets you select the signals that are collected from the target system and viewed in external mode. It also lets you select a signal that triggers uploading of data when certain signal conditions are met, and define the triggering conditions.
The Data archiving button opens the External Data Archiving dialog box. Data archiving lets you save data sets generated by the target program for future analysis. This example does not use data archiving. See Data Archiving in the Simulink Coder documentation for more information.
In the External Mode Control Panel, click the Signal & Triggering button. The External Signal & Triggering dialog box opens. The default configuration of the External Signal & Triggering dialog box is designed to select all signals for monitoring. The default configuration sets signal monitoring to begin as soon as the host and target programs have connected. The figure below shows the default configuration for extmode_example.

Make sure that the External Signal & Triggering dialog box is set to the defaults as shown:
Select all check box is selected. All signals in the Signal selection list are marked with an X in the Block column.
Trigger Source: manual
Trigger Mode: normal
Duration: 1000
Delay: 0
Arm when connecting to target: selected
Click Close, and then close the External Mode Control Panel.
For information on the options mentioned above, see External Signal Uploading and Triggering in the Simulink Coder documentation.
To run the target program, you must open a command prompt window (on UNIX systems, an Xterm window). At the command prompt, change to the ext_mode_example folder that you created in step 1. The target program is in this folder.
cd ext_mode_example
Next, type the following command:
extmode_example -tf inf -w
and press Return.
Note On Microsoft Windows platforms, you can also use the "bang" command (!) in the MATLAB Command Window (note that the trailing ampersand is required): !extmode_example -tf inf -w & |
The target program begins execution. Note that the target program is in a wait state, so no activity occurs in the MATLAB Command Window.
The -tf switch overrides the stop time set for the model in Simulink. The inf value directs the model to run indefinitely. The model code runs until the target program receives a stop message from Simulink.
The -w switch instructs the target program to enter a wait state until it receives a Start real-time code message from the host. This switch is required if you want to view data from time step 0 of the target program execution, or if you want to modify parameters before the target program begins execution of model code.
Open Scope blocks A and B. At this point, no signals are visible on the scopes. When you connect Simulink to the target program and begin model execution, the signals generated by the target program will be visible on the scope displays.
The model itself must be in external mode before communication between the model and the target program can begin. To enable external mode, select External from the simulation mode pull-down menu located on the right side of the toolbar of the Simulink window. Alternatively, you can select External from the Simulation menu.
Reopen the External Mode Control Panel (found in the Tools menu) and click Connect. This initiates a handshake between Simulink and the target program. When Simulink and the target are connected, the Start Real-Time Code button becomes enabled, and the label of the Connect button changes to Disconnect.
Click the Start Real-Time Code button. The outputs of Gain blocks A and B are displayed on the two scopes in your model.
Having established communication between Simulink and the running target program, you can tune block parameters in Simulink and observe the effects the parameter changes have on the target program. You do this in the next section.
Tune Parameters. You can change the gain factor of either Gain block by assigning a new value to the variable A or B in the MATLAB workspace. When you change block parameter values in the workspace during a simulation, you must explicitly update the block diagram with these changes. When the block diagram is updated, the new values are downloaded to the target program.
To tune the variables A and B,
In the MATLAB Command Window, assign new values to both variables, for example:
A = 0.5;B = 3.5;
Activate the extmode_example model window. Select Update Diagram from the Edit menu, or press Ctrl+D. As soon as Simulink has updated the block parameters, the new gain values are downloaded to the target program, and the effect of the gain change becomes visible on the scopes.
You can also enter gain values directly into the Gain blocks. To do this, open the Block Parameters dialog box for Gain block A or B in the model. Enter a new numerical value for the gain and click Apply. As soon as you click Apply, the new value is downloaded to the target program and the effect of the gain change becomes visible on the scope. Similarly, you can change the frequency, amplitude, or phase of the sine wave signal by opening the Block Parameters dialog box for the Sine Wave block and entering a new numerical value..
Note You cannot change the sample time of the Sine Wave block. Block sample times are part of the structural definition of the model and are part of the generated code. Therefore, if you want to change a block sample time, you must stop the external mode simulation, reset the block's sample time, and rebuild the executable. |
To simultaneously disconnect host/target communication and end execution of the target program, pull down the Simulation menu and select Stop Real-Time Code. You can also do this from the External Mode Control Panel.
External Mode Interface Options. The ERT, GRT, GRT malloc, RSim, and Wind River Systems Tornado targets and the Real-Time Windows Target product support external mode. All targets that support it feature a set of external mode options on their respective target tab of the Configuration Parameters dialog box. This tab is normally named Interface). The next figure is from the GRT target dialog box, and is discussed below.

Note The xPC Target product also uses external mode communications. External mode in the xPC Target product is always on, and has no interface options. |
The Data exchange section at the bottom has the following elements:
Interface menu: Selects which of three mutually exclusive data interfaces to include in the generated code. Options are
None
C API
External mode
ASAP2
This chapter discusses only the External mode option. For information on other options, see Specifying Target Interfaces.
Once you select External mode from the Interface menu, the following options appear beneath:
Transport layer menu: Identifies messaging protocol for host/target communications; choices are tcpip and serial.
The default is tcpip. When you select a protocol, the MEX-file name that implements the protocol is shown to the right of the menu.
MEX-file arguments text field: Optionally enter a list of arguments to be passed to the transport layer MEX-file for communicating with executing targets; these will vary according to the protocol you use.
For more information on the transport options, see Target Interfacing and Choose a Communications Protocol for Client and Server Interfaces. You can add other transport protocols yourself by following instructions given in Create a Transport Layer for External Communication.
Static memory allocation check box: Controls how memory for external mode communication buffers in the target is allocated. When you select this option, the following one appears beneath it:
Static memory buffer size text field: Number of bytes to preallocate for external mode communications buffers in the target when Static memory allocation is used.
Note Selecting External mode from the Interface menu does not cause the Simulink model to operate in external mode (see External Mode Related Menu and Toolbar Items, below). Its function is to instrument the code generated for the target to support external mode. |
The Static memory allocation check box (for GRT and ERT targets) directs the Simulink Coder software to generate code for external mode that uses only static memory allocation ("malloc-free" code). When selected, it activates the Static memory buffer size edit field, in which you specify the size of the static memory buffer used by external mode. The default value is 1,000,000 bytes. Should you enter too small a value for your application, external mode issues an out-of-memory error when it tries to allocate more memory than you allowed. In such cases, increase the value in the Static memory buffer size field and regenerate the code.
External Mode Related Menu and Toolbar Items. To communicate with a target program, the model must be operating in external mode. To enable external mode, do either of the following:
Select External from the Simulation menu.
Select External from the simulation mode menu in the toolbar. The simulation mode menu is shown in the next figure.
Simulation Mode Menu Options and Target Connection Control (Host Disconnected from Target)

Once external mode is enabled, you can connect to and control the target program by doing any of the following:
Select Connect To Target from the Simulation menu.
Click the Connect To Target toolbar button, shown in the preceding figure.
Use the Ctrl+T keyboard shortcut.
Note When external mode is selected in the model window, the Ctrl+T keyboard shortcut is remapped from a toggle for Start and Stop (simulation) to a toggle for Connect To Target and Disconnect From Target. |
Selecting external mode in the model window controls execution only, and does not cause the Simulink Coder software to generate code for external mode. To do this, you must select External mode from the Interface menu on the Interface tab of the Configuration Parameters dialog box, as described in External Mode Interface Options.
Note You can enable external mode, and simultaneously connect to the target system, by using the External Mode Control Panel dialog box. See External Mode Control Panel. |
When a Simulink model is in external mode, the upper section of the Simulation menu contains external mode options. Initially, the Simulink model is disconnected from the target program, and the menu displays the options shown in the next figure.
Simulation Menu External Mode Options (Host Disconnected from Target)

The Connect To Target option establishes communication with the target program. When a connection is established, the target program might be executing model code, or it might be awaiting a command from the host to start executing model code. You can also accomplish this by clicking the Connect To Target toolbar button, as shown in Simulation Mode Menu Options and Target Connection Control (Host Disconnected from Target).
If the target program is executing model code, the Simulation menu contents change, as shown in the next figure.
Simulation Menu External Mode Options (Target Executing Model Code)

The Disconnect From Target option disconnects the Simulink model from the target program, which continues to run. The Stop Real-Time Code option terminates execution of the target program and disconnects the Simulink model from the target system.
If the target program is in a wait state, the Start Real-Time Code option is enabled, as shown in the next figure. The Start Real-Time Code option instructs the target program to begin executing the model code.
Simulation Menu External Mode Options (Target Awaiting Start Command)

The Simulink toolbar controls, shown in Simulation Mode Menu Options and Target Connection Control (Host Disconnected from Target), let you control the same external mode functions as the Simulation menu. The Simulink model editor displays external mode buttons to the left of the Simulation mode menu. Initially, the toolbar displays a Connect To Target button and a disabled Start real-time code button. Click the Connect To Target button to connect the Simulink engine to the target program.
When a connection is established, the target program might be executing model code, or it might be awaiting a command from the host to start executing model code.
If the target program is executing model code, the toolbar displays a Stop real-time code button and a Disconnect From Target button (shown in External Mode Toolbar Controls (Target Executing Model Code)). Click the Stop real-time code button to command the target program to stop executing model code and disconnect the Simulink engine from the target system. Click the Disconnect From Target button to disconnect the Simulink engine from the target program while leaving the target program running.
External Mode Toolbar Controls (Target Executing Model Code)

If the target program is in a wait state, the toolbar displays a Start real-time code button and a Disconnect From Target button (shown in External Mode Toolbar Controls (Target in Wait State)). Click the Start real-time code button to instruct the target program to start executing model code. Click the Disconnect From Target button to disconnect the Simulink engine from the target program.
External Mode Toolbar Controls (Target in Wait State)

External Mode Control Panel. The External Mode Control Panel, illustrated in the next figure, provides centralized control of all external mode features, including
Host/target connection, disconnection, and target program start/stop functions, and enabling of external mode
Arming and disarming the data upload trigger
External mode communications configuration
Uploading data to Floating Scopes
Timing of parameter downloads
Selection of signals from the target program to be viewed and monitored on the host
Configuration of data archiving features
Select External Mode Control Panel from the Tools menu on the Simulink model editor to open the External Mode Control Panel dialog box.

The following sections describe the features supported by the External Mode Control Panel.
Connecting, Starting, and Stopping.The External Mode Control Panel performs the same connect/disconnect and start/stop functions found in the Simulation menu and the Simulink toolbar (see External Mode Related Menu and Toolbar Items).
The Connect/Disconnect button connects to or disconnects from the target program. The button text changes in accordance with the state of the connection.
If external mode is not enabled at the time the Connect button is clicked, the External Mode Control Panel enables external mode automatically.
The Start/Stop real-time code button commands the target to start or terminate model code execution. The button is disabled until a connection to the target is established. The button text changes in accordance with the state of the target program.
Floating Scope Options.The Floating scope pane of the External Mode Control Panel controls when and for how long data is uploaded to Floating Scope blocks. When used under external mode, Floating Scopes
Do not appear in the signal and triggering GUI
Support manual triggering only
The behavior of wired scopes is not restricted in these ways.
The Floating scope pane contains a check box and an edit field:
Enable data uploading check box, which functions as an Arm trigger button for floating scopes. When the target is disconnected it controls whether or not to arm when connecting the floating scopes. When already connected it acts as a toggle button to arm/cancel the trigger.
Duration edit field, which specifies the duration for floating scopes. By default, it is set to auto, which causes whatever value is specified in the signal and triggering GUI (which by default is 1000 seconds) to be used.
Target Interfacing. The Simulink Coder product lets you implement client and server transport for external mode using either TCP/IP or serial protocols. You can use the socket-based external mode implementation provided by the Simulink Coder product with the generated code, provided that your target system supports TCP/IP. Otherwise, use or customize the serial transport layer option provided.
A low-level transport layer handles physical transmission of messages. Both the Simulink engine and the model code are independent of this layer. Both the transport layer and code directly interfacing to the transport layer are isolated in separate modules that format, transmit, and receive messages and data packets.
You specify the transport mechanism using the Transport layer menu in the Host/Target interface subpane of the Interface pane of the Configuration Parameters dialog box, shown below.

The Host/Target interface subpane also displays MEX-file name, the name of a MEX-file that implements host/target communications for the selected external mode transport layer. This is known as the external interface MEX-file. The default is ext_comm, the TCP/IP-based external interface file provided for use with the GRT, GRT malloc, ERT, RSim, and Tornado targets. If you select the serial transport option, the MEX-file name ext_serial_win32_com is displayed in this location.
Note Custom or third-party targets can use a custom transport layer and a different external interface MEX-file. For more information on creating a custom transport layer, see Create a Transport Layer for External Communication. For more information on specifying a TCP/IP or serial transport layer for a custom target, see Using the TCP/IP Implementation or Using the Serial Implementation. |
The MEX-file arguments edit field lets you optionally specify arguments that are passed to the external mode interface MEX-file for communicating with executing targets. The meaning of the MEX-file arguments depends on the MEX-file implementation.
For TCP/IP interfaces, ext_comm allows three optional arguments:
Network name of your target (for example, 'myPuter' or '148.27.151.12')
Verbosity level (0 for no information or 1 for detailed information)
TCP/IP server port number (an integer value between 256 and 65535, with a default of 17725)
For serial transport, ext_serial_win32_comm allows three optional arguments:
Verbosity level (0 for no information or 1 for detailed information)
Serial port ID (for example, 1 for COM1, and so on)
Baud rate (selected from the set 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, with a default baud rate of 57600)
See Choose a Communications Protocol for Client and Server Interfaces for details on MEX-file transport architecture and arguments.
External Signal Uploading and Triggering. Clicking the Signal & triggering button of the External Mode Control Panel activates the External Signal & Triggering dialog box, as shown in the next figure.

The External Signal & Triggering dialog box displays a list of all blocks and subsystems in your model that support external mode signal uploading. See External Mode Compatible Blocks and Subsystems for information on which types of blocks are external mode compatible.
The External Signal & Triggering dialog box lets you select the signals that are collected from the target system and viewed in external mode. It also lets you select a signal that triggers uploading of data when certain signal conditions are met, and define the triggering conditions.
Default Operation.The preceding figure shows the default settings of the External Signal & Triggering dialog box. The default operation of the External Signal & Triggering dialog box is designed to simplify monitoring the target program. If you use the default settings, you do not need to preconfigure signals and triggers. Simply start the target program and connect the Simulink engine to it. All external mode compatible blocks will be selected and the trigger will be armed. Signal uploading begins immediately upon connection to the target program.
The default configuration is
Arm when connecting to target: on
Trigger Mode: normal
Trigger Source: manual
Select all: on
All external mode compatible blocks in your model appear in the Signal selection list of the External Signal & Triggering dialog box. You use this list to select signals to be viewed. An X appears to the left of each selected block's name.
The Select all check box selects all signals. By default, Select all is on.
If Select all is off, you can select or deselect individual signals using the on and off radio buttons. To select a signal, click the desired list entry and click the on radio button. To deselect a signal, click the desired list entry and click the off radio button. Alternatively, you can double-click a signal in the list to toggle between selection and deselection.
The Clear all button deselects all signals.
Trigger Options.The Trigger panel located at the bottom left of the External Signal & Triggering dialog contains options that control when and how signal data is collected (uploaded) from the target system. These options are
Source: manual or signal. Selecting manual directs external mode to start logging data when the Arm trigger button on the External Mode Control Panel is clicked.
Selecting signal tells external mode to start logging data when a selected trigger signal satisfies trigger conditions specified in the Trigger signal panel. When the trigger conditions are satisfied (that is, the signal crosses the trigger level in the specified direction) a trigger event occurs. If the trigger is armed, external mode monitors for the occurrence of a trigger event. When a trigger event occurs, data logging begins.
Arm when connecting to target: If this option is selected, external mode arms the trigger automatically when the Simulink engine connects to the target. If the trigger source is manual, uploading begins immediately. If the trigger mode is signal, monitoring of the trigger signal begins immediately, and uploading begins upon the occurrence of a trigger event.
If Arm when connecting to target is not selected, you must manually arm the trigger by clicking the Arm trigger button in the External Mode Control Panel.
Duration: The number of base rate steps for which external mode logs data after a trigger event. For example, if the fastest rate in the model is 1 second and a signal sampled at 1 Hz is being logged for a duration of 10 seconds, then external mode will collect 10 samples. If a signal sampled at 2 Hz is logged, 20 samples will be collected.
Mode: normal or one-shot. In normal mode, external mode automatically rearms the trigger after each trigger event. In one-shot mode, external mode collects only one buffer of data each time you arm the trigger. See Data Archiving for more details on the effect of the Mode setting.
Delay: The delay represents the amount of time that elapses between a trigger occurrence and the start of data collection. The delay is expressed in base rate steps, and can be positive or negative. A negative delay corresponds to pretriggering. When the delay is negative, data from the time preceding the trigger is collected and uploaded.
You can designate one signal as a trigger signal. To select a trigger signal, select signal from the Trigger Source menu. This activates the Trigger signal panel (see the next figure). Then, click the desired entry in the Signal selection list and click the Trigger signal button.
When a signal is selected as a trigger, a T appears to the left of the block's name in the Signal selection list. In the next figure, the Scope A signal is the trigger. Scope B is also selected for viewing, as indicated by the X to the left of the block name.
External Signal & Triggering Window with Trigger Selected

After selecting the trigger signal, you can define the trigger conditions and set the Port and Element fields in the Trigger signal panel.
Setting Trigger Conditions.Note The Trigger signal panel and the Port and Element fields of the External Signal & Triggering dialog box are enabled only when trigger Source is set to signal. |
By default, any element of the first input port of the specified trigger block can cause the trigger to fire (that is, Port 1, any element). You can modify this behavior by adjusting the Port and Element fields located on the right side of the Trigger signal panel. The Port field accepts a number or the keyword last. The Element field accepts a number or the keywords any and last.
The Trigger Signal panel defines the conditions under which a trigger event will occur.
Level: Specifies a threshold value. The trigger signal must cross this value in a designated direction to fire the trigger. By default, the level is 0.
Direction: rising, falling, or either. This specifies the direction in which the signal must be traveling when it crosses the threshold value. The default is rising.
Hold-off: Applies only to normal mode. Expressed in base rate steps, Hold-off is the time between the termination of one trigger event and the rearming of the trigger.
Data Archiving. In external mode, you can use the Simulink Scope and To Workspace blocks to archive data to disk. Clicking the Data Archiving button of the External Mode Control Panel opens the External Data Archiving dialog box, which supports the following features.
Folder Notes.Use this option to add annotations that pertain to a collection of related data files in a folder. Clicking the Edit directory note button opens the MATLAB editor. Place comments that you want saved to a file in the specified folder in this window. By default, the comments are saved to the folder last written to by data archiving.
File Notes.Clicking Edit file note opens a file finder window that is, by default, set to the last file to which you have written. Selecting any MAT-file opens an edit window. Add or edit comments in this window that you want saved with your individual MAT-file.
Automated Data Archiving.Clicking the Enable Archiving check box activates the automated data archiving features of external mode. To understand how the archiving features work, consider the handling of data when archiving is not enabled. There are two cases, one-shot and normal mode.
In one-shot mode, after a trigger event occurs, each selected block writes its data to the workspace just as it would at the end of a simulation. If another one-shot is triggered, the existing workspace data is overwritten.
In normal mode, external mode automatically rearms the trigger after each trigger event. Consequently, you can think of normal mode as a series of one-shots. Each one-shot in this series, except for the last, is referred to as an intermediate result. Since the trigger can fire at any time, writing intermediate results to the workspace generally results in unpredictable overwriting of the workspace variables. For this reason, the default behavior is to write only the results from the final one-shot to the workspace. The intermediate results are discarded. If you know that enough time exists between triggers for inspection of the intermediate results, then you can override the default behavior by checking the Write intermediate results to workspace check box. This option does not protect the workspace data from being overwritten by subsequent triggers.
The options in the External Data Archiving dialog box support automatic writing of logging results, including intermediate results, to disk. Data archiving provides the following settings:
Directory: Specifies the folder in which data is saved. External mode appends a suffix if you select Increment directory when trigger armed.
File: Specifies the filename in which data is saved. External mode appends a suffix if you select Increment file after one-shot.
Increment directory when trigger armed: External mode uses a different folder for writing log files each time that you click the Arm trigger button. The folders are named incrementally, for example, dirname1, dirname2, and so on.
Increment file after one-shot: New data buffers are saved in incremental files: filename1, filename2, and so on. This happens automatically in normal mode.
Append file suffix to variable names: Whenever external mode increments filenames, each file contains variables with identical names. Selecting Append file suffix to variable name results in each file containing unique variable names. For example, external mode will save a variable named xdata in incremental files (file_1, file_2, and so on) as xdata_1, xdata_2, and so on. This is useful if you want to load the MAT-files into the workspace and compare variables at the MATLAB command prompt. Without the unique names, each instance of xdata would overwrite the previous one in the MATLAB workspace.
Write intermediate results to workspace: Select this option if you want the Simulink Coder software to write all intermediate results to the workspace.
The next figure shows the External Data Archiving dialog box with archiving enabled.

Unless you select Enable archiving, entries for the Directory and File fields are not accepted.
Parameter Downloading. The Batch download check box on the External Mode Control Panel enables or disables batch parameter changes.
By default, batch download is not enabled. If batch download is not enabled, changes made directly to block parameters by using parameter dialog boxes are sent to the target when you click the OK or Apply button. Changes to MATLAB workspace variables are sent when an Update diagram is performed.
If batch download is enabled, the Download button is enabled. Changes made to block parameters are stored locally until you click the Download button. When you click the Download button, the changes are sent in a single transmission.
When parameter changes have been made and are awaiting batch download, the External Mode Control Panel displays the message Parameter changes pending... to the right of the download button. (See the next figure.) This message disappears after the Simulink engine receives notification from the target that the new parameters have been installed in the parameter vector of the target system.
The External Mode Control Panel with the batch download option activated appears in the next figure.
External Mode Control Panel in Batch Download Mode

Compatible Blocks. In external mode, you can use the following types of blocks to receive and view signals uploaded from the target program:
Floating Scope and Scope blocks
Spectrum Scope and Vector Scope blocks from the DSP System Toolbox product
Blocks from the Gauges Blockset product
Display blocks
To Workspace blocks
User-written S-Function blocks
An external mode method is built into the S-function API. This method allows user-written blocks to support external mode. See matlabroot/simulink/simstruc.h.
XY Graph blocks
In addition to these types of blocks, you can designate certain subsystems as Signal Viewing Subsystems and use them to receive and view signals uploaded from the target program. See Signal Viewing Subsystems for more information.
You select external mode compatible blocks and subsystems, and arm the trigger, by using the External Signal & Triggering dialog box. By default, all such blocks in a model are selected, and a manual trigger is set to be armed when connected to the target program.
Signal Viewing Subsystems. A Signal Viewing Subsystem is an atomic subsystem that encapsulates processing and viewing of signals received from the target system. A Signal Viewing Subsystem runs only on the host, generating no code in the target system. Signal Viewing Subsystems run in all simulation modes — normal, accelerated, and external.
Signal Viewing Subsystems are useful in situations where you want to process or condition signals before viewing or logging them, but you do not want to perform these tasks on the target system. By using a Signal Viewing Subsystem, you can generate smaller and more efficient code on the target system.
Like other external mode compatible blocks, Signal Viewing Subsystems are displayed in the External Signal & Triggering dialog box.
To declare a subsystem to be a Signal Viewing Subsystem,
Select the Treat as atomic unit option in the Block Parameters dialog box.
See Subsystems for more information on atomic subsystems.
Use the following set_param command to turn the SimViewingDevice property on,
set_param('blockname', 'SimViewingDevice','on')
where 'blockname' is the name of the subsystem.
Make sure the subsystem meets the following requirements:
It must be a pure sink block. That is, it must contain no Outport blocks or Data Store blocks. It can contain Goto blocks only if the corresponding From blocks are contained within the subsystem boundaries.
It must have no continuous states.
The following model, sink_examp, contains an atomic subsystem, theSink.

The subsystem theSink, shown in the next figure, applies a gain and an offset to its input signal and displays it on a Scope block.

If theSink is declared as a Signal Viewing Subsystem, the generated target program includes only the code for the Sine Wave block. If theSink is selected and armed in the External Signal & Triggering dialog box, the target program uploads the sine wave signal to theSink during simulation. You can then modify the parameters of the blocks within theSink and observe their effect upon the uploaded signal.
If theSink were not declared as a Signal Viewing Subsystem, its Gain, Constant, and Sum blocks would run as subsystem code on the target system. The Sine Wave signal would be uploaded to the Simulink engine after being processed by these blocks, and viewed on sink_examp/theSink/Scope2. Processing demands on the target system would be increased by the additional signal processing, and by the downloading of changes in block parameters from the host.
Supported Blocks for Data Archiving. In external mode, you can use the following types of blocks to archive data to disk:
Scope blocks
To Workspace blocks
You configure data archiving by using the External Data Archiving dialog box, as described in Data Archiving.
About External Mode Communications. This section describes how the Simulink engine and a target program communicate, and how and when they transmit parameter updates and signal data to each other.
Depending on the setting of the Inline parameters option when the target program is generated, there are differences in the way parameter updates are handled. Download Mechanism describes the operation of external mode communications with Inline parameters off. Inlined and Tunable Parameters describes the operation of external mode with Inline parameters on.
Download Mechanism. In external mode, the Simulink engine does not simulate the system represented by the block diagram. By default, when external mode is enabled, the Simulink engine downloads all parameters to the target system. After the initial download, the engine remains in a waiting mode until you change parameters in the block diagram or until the engine receives data from the target.
When you change a parameter in the block diagram, the Simulink engine calls the external interface MEX-file, passing new parameter values (along with other information) as arguments. The external interface MEX-file contains code that implements one side of the interprocess communication (IPC) channel. This channel connects the Simulink process (where the MEX-file executes) to the process that is executing the external program. The MEX-file transfers the new parameter values by using this channel to the external program.
The other side of the communication channel is implemented within the external program. This side writes the new parameter values into the target's parameter structure (model_P).
The Simulink side initiates the parameter download operation by sending a message containing parameter information to the external program. In the terminology of client/server computing, the Simulink side is the client and the external program is the server. The two processes can be remote, or they can be local. Where the client and server are remote, a protocol such as TCP/IP is used to transfer data. Where the client and server are local, a serial connection or shared memory can be used to transfer data.
The next figure shows this relationship. The Simulink engine calls the external interface MEX-file whenever you change parameters in the block diagram. The MEX-file then downloads the parameters to the external program by using the communication channel.
External Mode Architecture

Inlined and Tunable Parameters. By default, all parameters (except those listed in External Mode Limitations) in an external mode program are tunable; that is, you can change them by using the download mechanism described in this section.
If you select the Inline parameters option (on the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box), the Simulink Coder code generator embeds the numerical values of model parameters (constants), instead of symbolic parameter names, in the generated code. Inlining parameters generates smaller and more efficient code. However, inlined parameters, because they effectively become constants, are not tunable.
The Simulink Coder software lets you improve overall efficiency by inlining most parameters, while at the same time retaining the flexibility of run-time tuning for selected parameters that are important to your application. When you inline parameters, you can use the Model Parameter Configuration dialog box to remove individual parameters from inlining and declare them to be tunable. In addition, the Model Parameter Configuration dialog box offers you options for controlling how parameters are represented in the generated code.
For more information on tunable parameters, see Parameters.
Automatic Parameter Uploading on Host/Target Connection.Each time the Simulink engine connects to a target program that was generated with Inline parameters on, the target program uploads the current value of its tunable parameters (if any) to the host. These values are assigned to the corresponding MATLAB workspace variables. This procedure synchronizes the host and target with respect to parameter values.
All workspace variables required by the model must be initialized at the time of host/target connection. Otherwise the uploading cannot proceed and an error results. Once the connection is made, these variables are updated to reflect the current parameter values on the target system.
Automatic parameter uploading takes place only if the target program was generated with Inline parameters on. Download Mechanism describes the operation of external mode communications with Inline parameters off.
Introduction. The Simulink Coder product provides code to implement both the client and server side of external mode communication using either TCP/IP or serial protocols. You can use the socket-based external mode implementation provided by the Simulink Coder product with the generated code, provided that your target system supports TCP/IP. If not, use or customize the serial transport layer option provided.
A low-level transport layer handles physical transmission of messages. Both the Simulink engine and the model code are independent of this layer. Both the transport layer and code directly interfacing to the transport layer are isolated in separate modules that format, transmit, and receive messages and data packets.
See Target Interfacing for information on selecting a transport layer.
Using the TCP/IP Implementation. You can use TCP/IP-based client/server implementation of external mode with real-time programs on The Open Group UNIX or PC systems. For help in customizing external mode transport layers, see Create a Transport Layer for External Communication.
To use Simulink external mode over TCP/IP, you must
Make sure that the external interface MEX-file for your target's TCP/IP transport is specified.
Targets provided by MathWorks specify the name of the external interface MEX-file in matlabroot/toolbox/simulink/simulink/extmode_transports.m. The name of the interface appears as uneditable text in the Host/Target interface section of the Interface pane of the Configuration Parameters dialog box. The TCP/IP default is ext_comm.
To specify a TCP/IP transport for a custom target, you must add an entry of the following form to an sl_customization.m file on the MATLAB path:
function sl_customization(cm)
cm.ExtModeTransports.add('stf.tlc', 'transport', 'mexfile', 'Level1');
%end functionwhere
stf.tlc is the name of the system target file for which the transport will be registered (for example, 'mytarget.tlc')
transport is the transport name to display in the Transport layer menu on the Interface pane of the Configuration Parameters dialog box (for example, 'tcpip')
mexfile is the name of the transport's associated external interface MEX-file (for example, 'ext_comm')
You can specify multiple targets and/or transports with additional cm.ExtModeTransports.add lines, for example:
function sl_customization(cm)
cm.ExtModeTransports.add('mytarget.tlc', 'tcpip', 'ext_comm', 'Level1');
cm.ExtModeTransports.add('mytarget.tlc', 'serial', ...
'ext_serial_win32_comm', 'Level1');
%end functionBe sure that the template makefile is configured to link the source files for the TCP/IP server code and that it defines the compiler flags when building the generated code.
Build the external program.
Run the external program.
Set the Simulink model to external mode and connect to the target.
The next figure shows the structure of the TCP/IP-based implementation.
TCP/IP-Based Client/Server Implementation for External Mode

In the External Target Interface dialog box, you can specify optional arguments that are passed to the external mode interface MEX-file for communicating with executing targets.
Target network name: the network name of the computer running the external program. By default, this is the computer on which the Simulink product is running. The name can be
String delimited by single quotes, such as 'myPuter'
IP address delimited by single quotes, such as '148.27.151.12'
Verbosity level: controls the level of detail of the information displayed during the data transfer. The value is either 0 or 1 and has the following meaning:
0 — No information
1 —
Detailed information
TCP/IP server port number: The default value is 17725. You can change the port number to a value between 256 and 65535 to avoid a port conflict.
The arguments are positional and must be specified in order. For example, if you want to specify the verbosity level (the second argument), then you must also specify the target network name (the first argument). Arguments can be delimited by white space or commas. For example:
'148.27.151.12' 1 30000
You can specify command-line options to the external program when you launch it. See Run the External Program for more information.
Using the Serial Implementation. Controlling host/target communications on a serial channel is similar to controlling host/target communications on a TCP/IP channel.
To use Simulink external mode over a serial channel, you must
Execute the target and host on a Microsoft Windows platform.
Make sure that the external interface MEX-file for your target's serial transport is specified.
Targets provided by MathWorks specify the name of the external interface MEX-file in matlabroot/toolbox/simulink/simulink/extmode_transports.m. The name of the interface appears as uneditable text in the Host/Target interface section of the Interface pane of the Configuration Parameters dialog box. The serial default is serial.
To specify a serial transport for a custom target, you must add an entry of the following form to an sl_customization.m file on the MATLAB path:
function sl_customization(cm)
cm.ExtModeTransports.add('stf.tlc', 'transport', 'mexfile', 'Level1');
%end functionwhere
stf.tlc is the name of the system target file for which the transport will be registered (for example, 'mytarget.tlc')
transport is the transport name to display in the Transport layer menu on the Interface pane of the Configuration Parameters dialog box (for example, 'serial')
mexfile is the name of the transport's associated external interface MEX-file (for example, 'ext_serial_win32_comm')
You can specify multiple targets and/or transports with additional cm.ExtModeTransports.add lines, for example:
function sl_customization(cm)
cm.ExtModeTransports.add('mytarget.tlc', 'tcpip', 'ext_comm', 'Level1');
cm.ExtModeTransports.add('mytarget.tlc', 'serial', ...
'ext_serial_win32_comm', 'Level1');
%end functionBe sure that the template makefile is configured to link the source files for the serial server code and that it defines the compiler flags when building the generated code.
Build the external program.
Run the external program.
Set the Simulink model to external mode and connect to the target.
MEX-File Optional Arguments for Serial Transport.
In the MEX-file arguments field of the Interface pane of the Configuration Parameters dialog box, you can specify arguments that are passed to the external mode interface MEX-file for communicating with the executing targets. For serial transport, the optional arguments to ext_serial_win32_comm are
Verbosity level: controls the level of detail of the information displayed during the data transfer. The value is either 0 or 1 and has the following meaning:
0 — No information
1 —
Detailed information
Serial port ID (for example, 1 for COM1, and so on)
If the target program is executing on the same machine as the host and communications is through a loopback serial cable, the target's port ID must differ from that of the host (as specified in the MEX-file arguments edit field).
When you start the target program using a serial connection, you must specify the port ID to use to connect it to the host. Do this by including the -port command-line option. For example,
mytarget.exe -port 2 -w
Baud rate (selected from the set 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, with a default baud rate of 57600)
The arguments are positional and must be specified in order. For example, if you want to specify the serial port ID (the second argument), then you must also specify the verbosity level (the first argument). Arguments can be delimited by white space or commas. For example:
1 1 115200
You can specify command-line options to the external program when you launch it. The following section provides details on using command-line arguments.
Run the External Program. The external program must be running before you can use the Simulink product in external mode. To run the external program, you type a command of the form
model -opt1 ... -optN
where model is the name of the external program and -opt1 ... -optN are options. (See Command-Line Options for the External Program.) In the examples in this section, the name of the external program is assumed to be ext_example.
Running the External Program Under the Windows Environment.In the Windows environment, you can run the external programs in either of the following ways:
Open a Command Prompt window. At the command prompt, type the name of the target executable, followed by any options, as in the following example:
ext_example -tf inf -w
Alternatively, you can launch the target executable from the MATLAB command prompt. In this case the command must be preceded by an exclamation point (!) and followed by an ampersand (&), as in the following example:
!ext_example -tf inf -w &
The ampersand (&) causes the operating system to spawn another process to run the target executable. If you do not include the ampersand, the program still runs, but you will be unable to enter commands at the MATLAB command prompt or manually terminate the executable.
Running the External Program Under the UNIX Environment.
In the UNIX environment, you can run the external programs in either of the following ways:
Open an Xterm window. At the command prompt, type the name of the target executable, followed by any options, as in the following example:
ext_example -tf inf -w
Alternatively, you can launch the target executable from the MATLAB command prompt. In the UNIX environment, if you start the external program from the MATLAB command prompt, you must run it in the background so that you can still access the Simulink environment. The command must be preceded by an exclamation point (!) and followed by an ampersand (&), as in the following example:
!ext_example -tf inf -w &
runs the executable from the MATLAB command prompt by spawning another process to run it.
Command-Line Options for the External Program.
External mode target executables generated by the Simulink Coder code generator support the following command-line options:
-tf n option
The -tf option overrides the stop time set in the Simulink model. The argument n specifies the number of seconds the program will run. The value inf directs the model to run indefinitely. In this case, the model code will run until the target program receives a stop message from the Simulink engine.
The following example sets the stop time to 10 seconds.
ext_example -tf 10
When integer-only ERT targets are built and executed in external mode, the stop time parameter (-tf) is interpreted by the target as the number of base rate ticks rather than the number of seconds to execute. See in the Embedded Coder documentation.
Note The -tf option works with GRT, GRT malloc, ERT, RSim, and Tornado targets. If you are creating a custom target and want to support the -tf option, you must implement the option yourself. See Create a Transport Layer for External Communication for more information. |
-w option: Instructs the target program to enter a wait state until it receives a message from the host. At this point, the target is running, but not executing the model code. The start message is sent when you select Start Real-Time Code from the Simulation menu or click the Start real-time code button in the External Mode Control Panel.
Use the -w option if you want to view data from time step 0 of the target program execution, or if you want to modify parameters before the target program begins execution of model code.
-port n option: Specifies the TCP/IP port number, n, for the target program. The port number of the target program must match that of the host. The default port number is 17725. The port number must be a value between 256 and 65535.
Note The -tf, -w, and -port options are supported by the TCP/IP and serial transport layer modules shipped with the Simulink Coder product (although -port is interpreted differently by each). The -baud option is serial only. By default, these modules are linked into external mode target executables. If you are implementing a custom external mode transport layer and want to support these options, you must implement them in your code. |
Implement an External Mode Protocol Layer. If you want to implement your own transport layer for external mode communication, you must modify certain code modules provided by the Simulink Coder product and create a new external interface MEX-file. This advanced topic is described in detail in Create a Transport Layer for External Communication.
You can run external-mode applications from the MATLAB command line or programmatically in scripts. Use the get_param and set_param commands to retrieve and set the values of model simulation command-line parameters, such as SimulationMode and SimulationCommand, and external mode command-line parameters, such as ExtModeCommand and ExtModeTrigType. (For more information on using get_param and set_param to tune model parameters, see Tune Parameters.)
The following sequence of model simulation commands assumes that a Simulink model is open and that you have loaded a target program to which the model will connect using external mode.
Change the Simulink model to external mode:
set_param(gcs, 'SimulationMode', 'external')
Connect the open model to the loaded target program:
set_param(gcs, 'SimulationCommand', 'connect')
Start running the target program:
set_param(gcs, 'SimulationCommand', 'start')
Stop running the target program:
set_param(gcs, 'SimulationCommand', 'stop')
Disconnect the target program from the model:
set_param(gcs, 'SimulationCommand', 'disconnect')
The next table lists external mode command-line parameters that you can use in get_param and set_param commands. The table provides brief descriptions, valid values (bold type highlights defaults), and a mapping to External Mode dialog box equivalents.
Note For external mode parameters that are equivalent to Interface pane options in the Configuration Parameters dialog box, see the ExtMode table entries in Parameter Command-Line Information Summary. |
External Mode Command-Line Parameters
| Parameter and Values | Dialog Box Equivalent | Description |
|---|---|---|
| ExtModeAddSuffixToVar off, on | External Data Archiving: Append file suffix to variable names check box | Increment variable names for each incremented filename. |
| ExtModeArchiveDirName string | External Data Archiving: Directory text field | Save data in specified folder. |
| ExtModeArchiveFileName string | External Data Archiving: File text field | Save data in specified file. |
| ExtModeArchiveMode string - off, on | External Data Archiving: Enable archiving check box | Activate automated data archiving features. |
| ExtModeArmWhenConnect off, on | External Signal & Triggering: Arm when connecting to target check box | Arm the trigger as soon as the Simulink Coder software connects to the target. |
| ExtModeAutoIncOneShot off, on | External Data Archiving: Increment file after one-shot check box | Save new data buffers in incremental files. |
| ExtModeAutoUpdateStatusClock (MicrosoftWindows platforms
only) off, on | Not available | Continuously upload and display target time on the model window status bar. |
| ExtModeBatchMode off, on | External Mode Control Panel: Batch download check box | Enable or disable downloading of parameters in batch mode. |
| ExtModeChangesPending off, on | Not available | When ExtModeBatchMode is enabled, indicates whether any parameters remain in the queue of parameters to be downloaded to the target. |
| ExtModeCommand string | Not available | Issue an external mode command to the target program. |
| ExtModeConnected off, on | External Mode Control Panel: Connect/Disconnect button | Indicate the state of the connection with the target program. |
| ExtModeEnableFloating off, on | External Mode Control Panel: Enable data uploading check box | Enable or disable the arming and canceling of triggers when a connection is established with floating scopes. |
| ExtModeIncDirWhenArm off, on | External Data Archiving: Increment directory when trigger armed check box | Write log files to incremental folders each time the trigger is armed. |
| ExtModeLogAll off, on | External Signal & Triggering: Select all check box | Upload all available signals from the target to the host. |
| ExtModeLogCtrlPanelDlg string | Not available | Return a handle to the External Mode Control Panel dialog box or –1 if the dialog box does not exist. |
| ExtModeParamChangesPending off, on | Not available | When the Simulink Coder software is connected to the target and ExtModeBatchMode is enabled, indicates whether any parameters remain in the queue of parameters to be downloaded to the target. More efficient than ExtModeChangesPending because it checks for a connection to the target. |
| ExtModeSkipDownloadWhenConnect off, on | Not available | Connect to the target program without downloading parameters. |
| ExtModeTrigDelay integer (0) | External Signal & Triggering: Delay text field | Specify the amount of time that elapses between a trigger occurrence and the start of data collection. |
| ExtModeTrigDirection string - rising, falling, either | External Signal & Triggering: Direction menu | Specify the direction in which the signal must be traveling when it crosses the threshold value. |
| ExtModeTrigDuration integer (1000) | External Signal & Triggering: Duration text field | Specify the number of base rate steps for which external mode is to log data after a trigger event. |
| ExtModeTrigDurationFloating string - integer (auto) | External Mode Control Panel: Duration text field | Specify the duration for floating scopes. If auto is specified, the value of ExtModeTrigDuration is used. |
| ExtModeTrigElement string - integer, any, last | External Signal & Triggering: Element text field | Specify the elements of the input port of the specified trigger block that can cause the trigger to fire. |
| ExtModeTrigHoldOff integer (0) | External Signal & Triggering: Hold-off text field | Specify the base rate steps between when a trigger event terminates and the trigger is rearmed. |
| ExtModeTrigLevel integer (0) | External Signal & Triggering: Level text field | Specify the threshold value the trigger signal must cross to fire the trigger. |
| ExtModeTrigMode string - normal, oneshot | External Signal & Triggering: Mode menu | Specify whether the trigger is to rearm automatically after each trigger event or whether only one buffer of data is to be collected each time the trigger is armed. |
| ExtModeTrigPort string - integer (1), last | External Signal & Triggering: Port text field | Specify the input port of the specified trigger block for which elements can cause the trigger to fire. |
| ExtModeTrigType string - manual, signal | External Signal & Triggering: Source menu | Specify whether to start logging data when the trigger is armed or when a specified trigger signal satisfies trigger conditions. |
| ExtModeUploadStatus string - inactive, armed, uploading | Not available | Return the status of the external mode upload mechanism — inactive, armed, or uploading. |
| ExtModeWriteAllDataToWs off, on | External Data Archiving: Write intermediate results to workspace check box | Write all intermediate results to the workspace. |
Limitations on Changing Parameters. In general, you cannot change a parameter if doing so results in a change in the structure of the model. For example, you cannot change
The number of states, inputs, or outputs of any block
The sample time or the number of sample times
The integration algorithm for continuous systems
The name of the model or of any block
The parameters to the Fcn block
If you cause any of these changes to the block diagram, then you must rebuild the program with newly generated code.
However, you can change parameters in transfer function and state space representation blocks in specific ways:
The parameters (numerator and denominator polynomials) for the Transfer Fcn (continuous and discrete) and Discrete Filter blocks can be changed (as long as the number of states does not change).
Zero entries in the State-Space and Zero Pole (both continuous and discrete) blocks in the user-specified or computed parameters (that is, the A, B, C, and D matrices obtained by a zero-pole to state-space transformation) cannot be changed once external simulation is started.
In the State-Space block, if you specify the matrices in the controllable canonical realization, then all changes to the A, B, C, D matrices that preserve this realization and the dimensions of the matrices are allowed.
If the Simulink block diagram does not match the external program, the Simulink engine displays an error informing you that the checksums do not match (that is, the model has changed since you generated code). This means that you must rebuild the program from the new block diagram (or reload another one) to use external mode.
If the external program is not running, the Simulink engine displays an error informing you that it cannot connect to the external program.
Limitation on Mixing 32-bit and 64-bit Architectures. When you use external mode, the machine running the Simulink product and the machine running the target executable must have matching bit architectures, either 32-bit or 64-bit. This is because the Simulink Coder software varies a model's checksum based on whether it is configured for a 32-bit or 64-bit platform.
If you attempt to connect from a 32-bit machine to a 64-bit machine or vice versa, the external mode connection fails.
Limitations on Uploading Data. External mode does not support uploading data values for fixed-point or enumerated types into workspace parameters.
Limitations on Uploading Variable-Size Signals. External mode does not support uploading variable-size signals for the following targets:
xPC Target
Texas Instruments C2000™
Limitations on Archiving Data. External mode supports the Scope and To Workspace blocks for archiving data to disk. However, external mode does not support scopes other than the Scope block for archiving data. For example, you cannot use Floating Scope blocks or Signal and Scope Manager viewer objects to archive data in external mode.
About Logging Data. Simulink Coder MAT-file data logging facility enables a generated program to save system states, outputs, and simulation time at each model execution time step. The data is written to a MAT-file, named (by default) model.mat, where model is the name of your model. In this example, data generated by the model rtwdemo_f14.mdl is logged to the file rtwdemo_f14.mat. Refer to Build a Generic Real-Time Program for instructions on setting up rtwdemo_f14.mdl in a working folder if you have not done so already.
To configure data logging, click Data Import/Export in the center pane of the Model Explorer. The process is the same as configuring a Simulink model to save output to the MATLAB workspace. For each workspace return variable you define and enable, the Simulink Coder software defines a parallel MAT-file variable. For example, if you save simulation time to the variable tout, your generated program logs the same data to a variable named rt_tout. You can change the prefix rt_ to a suffix (_rt), or eliminate it entirely. You do this by selecting Code Generation in the center pane of the Model Explorer, then clicking the Interface tab.
Note Simulink lets you log signal data from anywhere in a model via the Log signal data option in the Signal Properties dialog box (accessed via context menu by right-clicking signal lines). The Simulink Coder software does not use this method of signal logging in generated code. To log signals in generated code, you must either use the Data Import/Export options described below or include To File or To Workspace blocks in your model. |
In this example, you modify the rtwdemo_f14 model so that the generated program saves the simulation time and system outputs to the file rtwdemo_f14.mat. Then you load the data into the MATLAB workspace and plot simulation time against one of the outputs. The rtwdemo_f14 model should be open and configured as described in Build a Generic Real-Time Program.
Data Logging During Simulation. To use the data logging feature:
Open Model Explorer by selecting Model Explorer from the model's View menu.
In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.
Click Configuration (Active) in the left pane.
Click Data Import/Export in the center pane. The Data Import/Export pane, which appears at the right, lets you specify which outport data is to be saved to the workspace and what variable names to use for it.
Select the Time option. This tells Simulink to save time step data during simulation as a variable named tout. You can enter a different name to distinguish different simulation runs (for example using different step sizes), but take the default for this example. Selecting Time enables the Simulink Coder code generator to create code that logs the simulation time to a MAT-file.
Select the Output option. This tells Simulink to save output signal data during simulation as a variable named yout. Selecting Output enables the Simulink Coder code generator to create code that logs the root Output blocks (Angle of Attack and Pilot G Force) to a MAT-file.
If any other options are enabled, clear them. Set Decimation to 1 and Format to Array. The figure below shows the dialog.

Open the Pilot G Force Scope block of the model, then run the model by choosing Simulation > Start in the model window. The resulting Pilot G Force scope display is shown below.

Verify that the simulation time and outputs have been saved to the MATLAB workspace in MAT-files. At the MATLAB prompt, type:
whos *out
Simulink displays:
Name Size Bytes Class Attributes tout 601x1 4808 double yout 601x2 9616 double
Verify that Pilot G Force was logged by plotting simulation time versus that variable. At the MATLAB prompt, type:
plot(tout,yout(:,2))
The resulting plot is shown below.

Data Logging from Generated Code. In the second part of this example, you build and run a Simulink Coder executable of the rtwdemo_f14 model that outputs a MAT-file containing the simulation time and outputs you previously examined. Even though you have already generated code for the rtwdemo_f14 model, you must now regenerate that code because you have changed the model by enabling data logging. The steps below explain this procedure.
To avoid overwriting workspace data with data from simulation runs, the Simulink Coder code generator modifies identifiers for variables logged by Simulink. You can control these modifications from the Model Explorer:
Open Model Explorer by selecting Model Explorer from the model's View menu.
In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.
Click Configuration (Active) in the left pane.
In the center pane, click Code Generation. The Code Generation pane appears to the right.
Click the Interface tab.
Set MAT-file variable name modifier to _rt. This adds the suffix _rt to each variable that you selected to be logged in the first part of this example (tout, yout).
Clear the Generate code only check box, if it is currently selected. The pane should look like this:

To generate code and build an executable, click the Build button.
When the build concludes, run the executable with the command:
!rtwdemo_f14
The program now produces two message lines, indicating that the MAT-file has been written.
** starting the model ** ** created rtwdemo_f14.mat **
Load the MAT-file data created by the executable and look at the workspace variables from simulation and the generated program by typing:
load rtwdemo_f14.mat whos tout* yout*
Simulink displays:
Name Size Bytes Class Attribute tout 601x1 4808 double tout_rt 601x1 4808 double yout 601x2 9616 double yout_rt 601x2 9616 double
Note that all arrays have the same number of elements.
Observe that the variables tout_rt (time) and yout_rt (Pilot G Force and Angle of Attack) have been loaded from the file. Plot Pilot G Force as a function of time.
plot(tout_rt,yout_rt(:,2))
The resulting plot is identical to the plot you produced in step 10 of the previous part of this example:

Multiple techniques are available by which a program generated by the Simulink Coder software can save data to a MAT-file for analysis. See also Log Data for Analysis for a data logging tutorial.
Note Data logging is available only for targets that have access to a file system. In addition, only the RSim target executables are capable of accessing MATLAB workspace data. |
The Data Import/Export pane enables a generated program to save system states, outputs, and simulation time at each model execution time step. The data is written to a MAT-file, named (by default) model.mat.
Before using this data logging feature, you should learn how to configure a Simulink model to return output to the MATLAB workspace. This is discussed in Exporting Simulation Data in the Simulink documentation.
For each workspace return variable that you define and enable, the code generator defines a MAT-file variable. For example, if your model saves simulation time to the workspace variable tout, your generated program logs the same data to a variable named (by default) rt_tout.
The code generated by the code generator logs the following data:
All root Outport blocks
The default MAT-file variable name for system outputs is rt_yout.
The sort order of the rt_yout array is based on the port number of the Outport block, starting with 1.
All continuous and discrete states in the model
The default MAT-file variable name for system states is rt_xout.
Simulation time
The default MAT-file variable name for simulation time is rt_tout.
Override the Default MAT-File Name. The MAT-file name defaults to model.mat. To specify a different file name,
In the model window, select Simulation > Configuration Parameters. The dialog box opens.
Click Code Generation.
Append the following option to the existing text in the Make command field:
OPTS="-DSAVEFILE=filename"
Override the Default MAT-File Variable Names. By default, the code generation software prefixes the string rt_ to the variable names for system outputs, states, and simulation time to form MAT-file variable names. To change this prefix,
In the model window, select Simulation > Configuration Parameters. The dialog box opens.
Click Code Generation.
Select grt.tlc for System target file.
Select Code Generation > Interface
Select a prefix (rt_) or suffix (_rt) from the MAT-file variable name modifier field, or choose none for no prefix (other targets may or may not have this option).
Override the Default MAT-File Buffer Size. The size of the buffer for MAT-file data logging defaults to 1024 bytes. To specify a different buffer size,
In the model window, select Simulation > Configuration Parameters. The dialog box opens.
Click Code Generation.
Append the following option to the existing text in the Make command field:
OPTS="-DDEFAULT_BUFFER_SIZE=n"
where n specifies a buffer size in bytes.
The code generated by the code generator also logs data from these sources:
All Scope blocks that have the Save data to workspace parameter enabled
You must specify the variable name and data format in each Scope block's dialog box.
All To Workspace blocks in the model
You must specify the variable name and data format in each To Workspace block's dialog box.
The variables are written to model.mat, along with any variables logged from the Workspace I/O pane.
You can also log data to a To File block. The generated program creates a separate MAT-file (distinct from model.mat) for each To File block in the model. The file contains the block's time and input variable(s). You must specify the filename, variable names, decimation, and sample time in the To File block's dialog box.
Note Models referenced by Model blocks do not perform data logging in that context except for states, which you can include in the state logged for top models. Code generated by the Simulink Coder software for referenced models does not perform data logging to MAT-files. |
When logging data in single-tasking and multitasking systems, you will notice differences in the logging of
Noncontinuous root Outport blocks
Discrete states
In multitasking mode, the logging of states and outputs is done after the first task execution (and not at the end of the first time step). In single-tasking mode, the code generated by the build procedure logs states and outputs after the first time step.
See Data Logging in Single-Tasking and Multitasking Model Execution for more details on the differences between single-tasking and multitasking data logging.
Note The rapid simulation target (RSim) provides enhanced logging options. See Rapid Simulations for more information. |
A tunable parameter is a block parameter whose value can be changed at run-time. A tunable parameter is inherently noninlined. Consequently, when Inlined parameters is off, all parameters are members of model_P, and thus are tunable. A tunable expression is an expression that contains one or more tunable parameters.
When you declare a parameter tunable, you control whether or not the parameter is stored within model_P. You also control the symbolic name of the parameter in the generated code.
When you declare a parameter tunable, you specify
The storage class of the parameter.
The storage class property of a parameter specifies how the Simulink Coder product declares the parameter in generated code.
The term "storage class," as used in the Simulink Coder product, is not synonymous with the term storage class specifier, as used in the C language.
A storage type qualifier, such as const or volatile. This is simply a string that is included in the variable declaration.
(Implicitly) the symbolic name of the variable or field in which the parameter is stored. The Simulink Coder product derives variable and field names from the names of tunable parameters.
The Simulink Coder product generates a variable or struct storage declaration for each tunable parameter. Your choice of storage class controls whether the parameter is declared as a member of model_P or as a separate global variable.
You can use the generated storage declaration to make the variable visible to external legacy code. You can also make variables declared in your code visible to the generated code. You are responsible for linking your code to generated code modules.
You can use tunable parameters or expressions in your root model and in masked or unmasked subsystems, subject to certain restrictions. (See Tunable Expressions.)
Override Inlined Parameters for Tuning. When the Inline parameters option is selected, you can use the Model Parameter Configuration dialog box to remove individual parameters from inlining and declare them to be tunable. This allows you to improve overall efficiency by inlining most parameters, while at the same time retaining the flexibility of run-time tuning for selected parameters. Another way you can achieve the same result is by using Simulink data objects; see Parameters for specific details.
The mechanics of declaring tunable parameters are discussed in Declare Tunable Parameters.
The Simulink Coder product defines four storage classes for tunable parameters. You must declare a tunable parameter to have one of the following storage classes:
SimulinkGlobal (Auto): This is the default storage class. The Simulink Coder product stores the parameter as a member of model_P. Each member of model_P is initialized to the value of the corresponding workspace variable at code generation time.
ExportedGlobal: The generated code instantiates and initializes the parameter and model.h exports it as a global variable. An exported global variable is independent of the model_P data structure. Each exported global variable is initialized to the value of the corresponding workspace variable at code generation time.
ImportedExtern: model_private.h declares the parameter as an extern variable. Your code must supply the variable definition and initializer.
ImportedExternPointer: model_private.h declares the variable as an extern pointer. Your code must supply the pointer variable definition and initializer, if any.
The generated code for model.h includes model_private.h to make the extern declarations available to subsystem files.
As an example of how the storage class declaration affects the code generated for a parameter, consider the next figure.

The workspace variable Kp sets the gain of the Gain1 block. Assume that the value of Kp is 3.14. The following table shows the variable declarations and the code generated for the gain block when Kp is declared as a tunable parameter. An example is shown for each storage class.
Note The Simulink Coder product uses column-major ordering for two-dimensional signal and parameter data. When interfacing your hand-written code to such signals or parameters by using ExportedGlobal, ImportedExtern, or ImportedExternPointer declarations, make sure that your code observes this ordering convention. |
The symbolic name Kp is preserved in the variable and field names in the generated code.
Storage Class | Generated Variable Declaration and Code |
|---|---|
SimulinkGlobal (Auto) | typedef struct _Parameters_tunable_sin
Parameters_tunable_sin;
struct _Parameters_tunable_sin {
real_T Kp;
};
Parameters_tunable_sin tunable_sin_P = {
3.14
};
.
.
tunable_sin_Y.Out1 = rtb_u *
tunable_sin_P.Kp;
|
ExportedGlobal | real_T Kp = 3.14; . . tunable_sin_Y.Out1 = rtb_u * Kp; |
ImportedExtern | extern real_T Kp; . . tunable_sin_Y.Out1 = rtb_u * Kp; |
ImportedExtern Pointer | extern real_T *Kp; . . tunable_sin_Y.Out1 = rtb_u * (*Kp); |
Declare Workspace Variables as Tunable Parameters. To declare tunable parameters,
Click Add to table . The variables then appear as tunable parameters in the Global (tunable) parameters pane.
Optionally, select (or enter) a storage type qualifier, such as const or volatile for the parameter.
Click Apply, or click OK to apply changes and close the dialog box.
Declare New Tunable Parameters. To declare tunable parameters,
Specify a name for the parameter.
Optionally, select (or enter) a storage type qualifier, such as const or volatile for the parameter.
Click Apply, or click OK to apply changes and close the dialog box.
Declare Tunable Parameters Using the Model Configuration Parameter Dialog Box. The Model Parameter Configuration dialog box lets you select base workspace variables and declare them to be tunable parameters in the current model. Using controls in the dialog box, you move variables from a source list to a global (tunable) parameter list for a model.
To open the dialog box,
Select the Inline parameters check box on the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box. This activates a Configure button, as shown below.

Click Configure to open the Model Configuration Parameter dialog box.

Note The Model Configuration Parameter dialog box cannot tune parameters within referenced models. See Parameterizing Model References for tuning techniques that work with referenced models. |
Select Workspace Variables. The Source list pane displays a menu and a scrolling table of numerical workspace variables. To select workspace variables,
From the menu, select the source of variables you want listed.
| To List... | Choose... |
|---|---|
| All variables in the MATLAB workspace that have numeric values | MATLAB workspace |
| Only variables in the MATLAB workspace that have numeric values and are referenced by the model | Referenced workspace variables |
A list of workspace variables appear in the Source List pane.
Select one or more variables from the source list. This enables the Add to table button.
Click Add to table to add the selected variables to the tunable parameters list in the Global (tunable) parameters pane. In the Source list, the names of variables added to the tunable parameters list are displayed in bold type (see the preceding figure).
To update the list of variables to reflect the current state of the workspace, at any time, click Refresh list . For example, you might use Refresh list if you define or remove variables in the workspace while the Model Parameter Configuration dialog box is open.
Create New Tunable Parameters. To create a new tunable parameter,
In the Global (tunable) parameters pane, click New.
In the Name field, enter a name for the parameter.
If you enter a name that matches the name of a workspace variable in the Source list pane, that variable is declared tunable and appears in italics in the Source list.
Click Apply.
The model does not need to be using a parameter before you create it. You can add references to the parameter later.
Note If you edit the name of an existing variable in the list, you actually create a new tunable variable with the new name. The previous variable is removed from the list and loses its tunability (that is, it is inlined). |
Set Tunable Parameter Properties. To set the properties of tunable parameters listed in the Global (tunable) parameters pane, select a parameter and then specify a storage class and, optionally, a storage type qualifier.
| Property | Description |
|---|---|
| Storage class | Select one of the following to be used for code generation:
See Tunable Parameter Storage Classes for definitions. |
| Storage type qualifier | For variables with any storage class except SimulinkGlobal (Auto), you can add a qualifier (such as const or volatile) to the generated storage declaration. To do so, you can select a predefined qualifier from the list or add qualifiers not in the list. The code generator does not check the storage type qualifier for validity, and includes the qualifier string in the generated code without checking syntax . |
Remove Unused Tunable Parameters. To remove unused tunable parameters from the table in the Global (tunable) parameters pane, click Remove. All removed variables are inlined if the Inlined parameters option is enabled.
The Simulink Coder product supports the use of tunable variables in expressions. An expression that contains one or more tunable parameters is called a tunable expression.
Tunable Expressions in Masked Subsystems. Tunable expressions are allowed in masked subsystems. You can use tunable parameter names or tunable expressions in a masked subsystem dialog box. When referenced in lower-level subsystems, such parameters remain tunable.
As an example, consider the masked subsystem in the next figure. The masked variable k sets the gain parameter of theGain.

Suppose that the base workspace variable b is declared tunable with SimulinkGlobal (Auto) storage class. The next figure shows the tunable expression b*3 in the subsystem's mask dialog box.
Tunable Expression in Subsystem Mask Dialog Box

The Simulink Coder product produces the following output computation for theGain. The variable b is represented as a member of the global parameters structure, model_P. (For clarity in showing the individual Gain block computation, expression folding is off in this example.)
/* Gain: '<S1>/theGain' */ rtb_theGain_C = rtb_SineWave_n * ((subsys_mask_P.b * 3.0)); /* Outport: '<Root>/Out1' */ subsys_mask_Y.Out1 = rtb_theGain_C;
As this example shows, for GRT targets, the parameter structure is mangled to create the structure identifier model_P (subject to the identifier length constraint). This is done to avoid namespace clashes in combining code from multiple models using model reference. ERT-based targets provide ways to customize identifier names.
When expression folding is on, the above code condenses to
/* Outport: '<Root>/Out1' incorporates: * Gain: '<S1>/theGain' */ subsys_mask_Y.Out1 = rtb_SineWave_n * ((subsys_mask_P.b * 3.0));
Expressions that include variables that were declared or modified in mask initialization code are not tunable.
As an example, consider the subsystem above, modified as follows:
The mask initialization code is
t = 3 * k;
The parameter k of the myGain block is 4 + t.
Workspace variable b = 2. The expression b * 3 is plugged into the mask dialog box as in the preceding figure.
Since the mask initialization code can run only once, k is evaluated at code generation time as
4 + (3 * (2 * 3) )
The Simulink Coder product inlines the result. Therefore, despite the fact that b was declared tunable, the code generator produces the following output computation for theGain. (For clarity in showing the individual Gain block computation, expression folding is off in this example.)
/* Gain Block: <S1>/theGain */ rtb_temp0 *= (22.0);
Tunable Expression Limitations. Currently, there are certain limitations on the use of tunable variables in expressions. When an unsupported expression is encountered during code generation a warning is issued and the equivalent numeric value is generated in the code. The limitations on tunable expressions are
Complex expressions are not supported, except where the expression is simply the name of a complex variable.
The use of certain operators or functions in expressions containing tunable operands is restricted. Restrictions are applied to four categories of operators or functions, classified in the following table:
| Category | Operators or Functions |
|---|---|
1 | + - .* ./ < > <= >= == ~= & | |
2 | * / |
3 | abs, acos, asin, atan, atan2, boolean, ceil, cos, cosh, exp, floor, log, log10, sign, sin, sinh, sqrt, tan, tanh, |
4 | single, int8, int16, int32, uint8, uint16, uint32 |
5 | : .^ ^ [] {} . \ .\ ' .' ; , |
The rules applying to each category are as follows:
Category 1 is unrestricted. These operators can be used in tunable expressions with any combination of scalar or vector operands.
Category 2 operators can be used in tunable expressions where at least one operand is a scalar. That is, scalar/scalar and scalar/matrix operand combinations are supported, but not matrix/matrix.
Category 3 lists all functions that support tunable arguments. Tunable arguments passed to these functions retain their tunability. Tunable arguments passed to any other functions lose their tunability.
Category 4 lists the casting functions that do not support tunable arguments. Tunable arguments passed to these functions lose their tunability.
Note The Simulink Coder product casts values using MATLAB typecasting rules. The MATLAB typecasting rules are different from C code typecasting rules. For example, using the MATLAB typecasting rules, int8(3.7) returns the result 4, while in C code int8(3.7) returns the result 3. See Data Type Conversion in the MATLAB reference documentation for more information on MATLAB typecasting. |
Category 5 operators are not supported.
Expressions that include variables that were declared or modified in mask initialization code are not tunable.
The Fcn block does not support tunable expressions in code generation.
Model workspace parameters can take on only the Auto storage class, and thus are not tunable. See Parameterizing Model References for tuning techniques that work with referenced models.
Non-double expressions are not supported.
Blocks that access parameters only by address support the use of tunable parameters, if the parameter expression is a simple variable reference. When an operation such as a data type conversion or a math operation is applied, the Simulink Coder product creates a nontrivial expression that cannot be accessed by address, resulting in an error during the build process.
The following blocks have a Realization parameter that affects the tunability of their parameters:
Transfer Fcn
State-Space
Discrete State-Space
The Realization parameter must be set by using the MATLAB set_param function, as in the following example.
set_param(gcb,'Realization','auto')
The following values are defined for the Realization parameter:
general: The block's parameters are preserved in the generated code, permitting parameters to be tuned.
sparse: The block's parameters are represented in the code by transformed values that increase the computational efficiency. Because of the transformation, the block's parameters are no longer tunable.
auto: This setting is the default. A general realization is used if one or more of the block's parameters are tunable. Otherwise sparse is used.
Code Reuse for Subsystems with Mask Parameters. The Simulink Coder product can generate reusable (reentrant) code for a model containing identical atomic subsystems. Selecting the Reusable function option for Function packaging enables such code reuse, and causes a single function with arguments to be generated that is called when any of the identical atomic subsystem executes. See Reusable Function Option for details and restrictions on the use of this option.
Mask parameters become arguments to reusable functions. However, for reuse to occur, each instance of a reusable subsystem must declare the same set of mask parameters. If, for example subsystem A has mask parameters b and K, and subsystem B has mask parameters c and K, then code reuse is not possible, and the Simulink Coder product will generate separate functions for A and B.
If you are using tunable workspace parameters, you need to be aware of potential issues regarding data types. A workspace parameter is tunable when the following conditions exist:
You select the Inline parameters option on the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box
The parameter has a storage class other than Auto
When generating code for tunable workspace parameters, the Simulink Coder product checks and compares the data types used for a particular parameter in the workspace and in Block Parameter dialog boxes.
| If... | The Simulink Coder Product... |
|---|---|
| The data types match | Uses that data type for the parameter in the generated code. |
| You do not explicitly specify a data type other than double in the workspace | Uses the data type specified by the block in the generated
code. If multiple blocks share a parameter, they must all specify
the same data type. If the data type varies between blocks, the product
generates an error similar to the following:Variable 'K' is used in incompatible ways in the dialog fields of the following: cs_params/Gain, cs_params/Gain1. The variable'value is being used both directly and after a transformation. Only one of these usages is permitted for any given variable. |
| You explicitly specify a data type other than double in the workspace | Uses the data type from the workspace for the parameter. The block typecasts the parameter to the block specific data type before using it. |
Guidelines for Specifying Data Types. The following table provides guidelines on specifying data types for tunable workspace parameters.
| If You Want to... | Then Specify Data Types in... |
|---|---|
| Minimize memory usage (int8 instead of single) | The workspace explicitly |
| Avoid typecasting | Blocks only |
| Interface to legacy or custom code | The workspace explicitly |
| Use the same parameter for multiple blocks that specify different data types | The workspace explicitly |
The Simulink Coder product enforces limitations on the use of data types other than double in the workspace, as explained in Limitations on Specifying Data Types in the Workspace Explicitly.
Limitations on Specifying Data Types in the Workspace Explicitly. When you explicitly specify a data type other than double in the workspace, blocks typecast the parameter to another data type. This is an issue for blocks that use pointer access for their parameters. Blocks cannot use pointer access if they need to typecast the parameter before using it (because of a data type mismatch). Another case in which this occurs is for workspace variables with bias or fractional slope. Two possible solutions to these problems are
Remove the explicit data type specification in the workspace for parameters used in such blocks.
Modify the block so that it uses the parameter with the same data type as specified in the workspace. For example, the Lookup Table block uses the data types of its input signal to determine the data type that it uses to access the X-breakpoint parameter. You can prevent the block from typecasting the run-time parameter by converting the input signal to the data type used for X-breakpoints in the workspace. (Similarly, the output signal is used to determine the data types used to access the lookup table Y data.)
When parameters are MATLAB workspace variables, the Model Parameter Configuration dialog box is the recommended way to see or set the properties of tunable parameters. In addition to that dialog box, you can also use MATLAB get_param and set_param commands.
Note You can also use Simulink.Parameter objects for tunable parameters. See Configure Parameter Objects for Code Generation for details. |
The following commands return the tunable parameters and corresponding properties:
get_param(gcs, 'TunableVars')
get_param(gcs, 'TunableVarsStorageClass')
get_param(gcs, 'TunableVarsTypeQualifier')
The following commands declare tunable parameters or set corresponding properties:
set_param(gcs, 'TunableVars', str)
The argument str (string) is a comma-separated list of variable names.
set_param(gcs, 'TunableVarsStorageClass', str)
The argument str (string) is a comma-separated list of storage class settings.
The valid storage class settings are
Auto
ExportedGlobal
ImportedExtern
ImportedExternPointer
set_param(gcs, 'TunableVarsTypeQualifier', str)
The argument str (string) is a comma-separated list of storage type qualifiers.
The following example declares the variable k1 to be tunable, with storage class ExportedGlobal and type qualifier const. The number of variables and number of specified storage class settings must match. If you specify multiple variables and storage class settings, separate them with a comma.
set_param(gcs, 'TunableVars', 'k1') set_param(gcs, 'TunableVarsStorageClass','ExportedGlobal') set_param(gcs, 'TunableVarsTypeQualifier','const')
Other configuration parameters you can get and set are listed in Configuration Parameters for Simulink Models in the Simulink Coder Reference.
The Simulink Coder product includes
Support for developing a Target Language Compiler API for tuning parameters independent of external mode. See Parameter Functions in the Target Language Compiler documentation for information.
A C application program interface (API) for tuning parameters independent of external mode. See Data Interchange Using the C API for information.
An interface for exporting ASAP2 files, which you customize to use parameter objects. For details, see ASAP2 Data Measurement and Calibration.
The C API allows you to write host-based or target-based code that interacts with signals, states, root-level inputs/outputs, and parameters in your target-based application code.
Some Simulink Coder applications must interact with signals, states, root-level inputs/outputs, or parameters in the generated code for a model. For example, calibration applications monitor and modify parameters. Signal monitoring or data logging applications interface with signal, state, and root-level input/output data. Using the Simulink Coder C API, you can build target applications that log signals, states, and root-level inputs/outputs, monitor signals, states, and root-level inputs/outputs, and tune parameters, while the generated code executes.
The C API minimizes its memory footprint by sharing information common to signals, states, root-level inputs/outputs, and parameters in smaller structures. Signal, state, root-level input/output, and parameter structures include an index into the structure map, allowing multiple signals, states, root-level inputs/outputs, or parameters to share data.
When you configure a model to use the C API, the Simulink Coder code generator generates two additional files, model_capi.c (or .cpp) and model_capi.h, where model is the name of the model. The code generator places the two C API files in the build folder, based on settings in the Configuration Parameters dialog box. The C API source code file contains information about global block output signals, states, root-level inputs/outputs, and global parameters defined in the generated code model source code. The C API header file is an interface header file between the model source code and the generated C API. You can use the information in these C API files to create your application. Among the files generated are those shown in the next figure.
Generated Files with C API Selected

To generate C API files for your model:
Select the C API interface for your model. There are two ways to select the C API interface for your model, as described in the following sections.
Generate code for your model.
After generating code, you can examine the files model_capi.c (or .cpp) and model_capi.h in the model build folder.
Select C API with the Configuration Parameters Dialog Box.
Open your model, and launch either the Configuration Parameters dialog box or Model Explorer.
Go to the Code Generation > Interface pane and, in the Data exchange subpane, select C API as the value for the Interface parameter. The Generate C API for: signals, Generate C API for: parameters, Generate C API for: states, and Generate C API for: root-level I/O check boxes are displayed.

Select options:
If you want to generate C API code for global block output signals, select the Generate C API for: signals check box.
If you want to generate C API code for global block parameters, select the Generate C API for: parameters check box.
If you want to generate C API code for discrete and continuous states, select the Generate C API for: states check box.
If you want to generate C API code for root-level inputs and outputs, select the Generate C API for: root-level I/O check box.
If you select all four check boxes, support for accessing signals, parameters, states, and root-level I/O will appear in the C API generated code.
Select C API from the MATLAB Command Line. From the MATLAB command line, you can use the set_param function to select or clear the C API check boxes on the Interface pane of the Configuration Parameters dialog box. At the MATLAB command line, enter one or more of the following commands, where modelname is the name of your model.
To select Generate C API for: signals, enter:
set_param('modelname','RTWCAPISignals','on')To clear Generate C API for: signals, enter:
set_param('modelname','RTWCAPISignals','off')To select Generate C API for: parameters, enter:
set_param('modelname','RTWCAPIParams','on')To clear Generate C API for: parameters, enter:
set_param('modelname','RTWCAPIParams','off')To select Generate C API for: states, enter:
set_param('modelname','RTWCAPIStates','on')To clear Generate C API for: states, enter:
set_param('modelname','RTWCAPIStates','off')To select Generate C API for: root-level I/O, enter:
set_param('modelname','RTWCAPIRootIO','on')To clear Generate C API for: root-level I/O, enter:
set_param('modelname','RTWCAPIRootIO','off')Generate C API and ASAP2 Files. The C API and ASAP2 interfaces are not mutually exclusive. Although the Interface option on the Code Generation > Interface pane of the Configuration Parameters dialog box allows you to select either the ASAP2 or C API interface, you can instruct the Simulink Coder code generator to generate files for both interfaces. For details, see Generate ASAP2 and C API Files.
About C API Files. The model_capi.c (or .cpp) file provides external applications with a consistent interface to model data. Depending on your configuration settings, the data could be a signal, state, root-level input or output, or parameter. In this document, the term data item refers to either a signal, a state, a root-level input or output, or a parameter. The C API uses structures that provide an interface to the data item properties. The interface packages the properties of each data item in a data structure. If the model contains multiple data items, the interface generates an array of data structures. The members of a data structure map to data properties.
To interface with data items, an application requires the following properties for each data item:
Name
Block path
Port number (for signals and root-level inputs/outputs only)
Address
Data type information: native data type, data size, complexity, and other attributes
Dimensions information: number of rows, number of columns, and data orientation (scalar, vector, matrix, or n-dimensional)
Fixed-point information: slope, bias, scale type, word length, exponent, and other attributes
Sample-time information (for signals, states, and root-level inputs/outputs only): sample time, task identifier, frames
As illustrated in the next figure, the properties of data item A, for example, are located in data structure DS_A. The properties of data item B are located in data structure DS_B.

Some property values can be unique to each data item, and there are some property values that several data items can share in common. Name, for example, has a unique value for each data item. The interface places the unique property values directly in the structure for the data item. The name value of data item A is in DS_A, and the name value of data item B is in DS_B.
But data type could be a property whose value several data items have in common. The ability of some data items to share a property allows the C API to have a reuse feature. In this case, the interface places only an index value in DS_A and an index value in DS_B. These indices point to a different data structure, DS_C, that contains the actual data type value. The next figure shows this scheme with more detail.

The figure shows three signals. signal1 and signal2 share the same data type, double. Instead of specifying this data type value in each signal data structure, the interface provides only an index value, 0, in the structure. "double" is described by entry 0 in the rtDataTypeMap array, which is referenced by both signals. Additionally, property values can be shared between signals, states, root-level inputs/outputs, and parameters, so states, root-level inputs/outputs, and parameters also might reference the double entry in the rtDataTypeMap array. This reuse of information reduces the memory size of the generated interface.
Structure Arrays Generated in C API Files. As with data type, the interface maps other common properties (such as address, dimension, fixed-point scaling, and sample time) into separate structures and provides an index in the structure for the data item. For a complete list of structure definitions, refer to the file matlabroot/rtw/c/src/rtw_capi.h (where matlabroot represents the root of your MATLAB installation folder). This file also describes each member in a structure. The structure arrays generated in the model_capi.c (or .cpp) file are of structure types defined in the rtw_capi.h file. Here is a brief description of the structure arrays generated in model_capi.c (or .cpp):
rtBlockSignals is an array of structures that contains information about global block output signals in the model. Each element in the array is of type struct rtwCAPI_Signals. The members of this structure provide the signal name, block path, block port number, address, and indices to the data type, dimension, fixed-point, and sample-time structure arrays.
rtBlockParameters is an array of structures that contains information about the tunable block parameters in the model by block name and parameter name. Each element in the array is of type struct rtwCAPI_BlockParameters. The members of this structure provide the parameter name, block path, address, and indices to data type, dimension, and fixed-point structure arrays.
rtBlockStates is an array of structures that contains information about discrete and continuous states in the model. Each element in the array is of type struct rtwCAPI_States. The members of this structure provide the state name, block path, type (continuous or discrete), and indices to the address, data type, dimension, fixed-point, and sample-time structure arrays.
rtRootInputs is an array of structures that contains information about root-level inputs in the model. Each element in the array is of type struct rtwCAPI_Signals. The members of this structure provide the root-level input name, block path, block port number, address, and indices to the data type, dimension, fixed-point, and sample-time structure arrays.
rtRootOutputs is an array of structures that contains information about root-level outputs in the model. Each element in the array is of type struct rtwCAPI_Signals. The members of this structure provide the root-level output name, block path, block port number, address, and indices to the data type, dimension, fixed-point, and sample-time structure arrays.
rtModelParameters is an array of structures that contains information about all workplace variables that one or more blocks or Stateflow charts in the model reference as block parameters. Each element in the array is of data type rtwCAPI_ModelParameters. The members of this structure provide the variable name, address, and indices to data type, dimension, and fixed-point structure arrays.
rtDataAddrMap is an array of base addresses of signals, states, root-level inputs/outputs, and parameters that appear in the rtBlockSignals, rtBlockParameters, rtBlockStates, and rtModelParameters arrays. Each element of the rtDataAddrMap array is a pointer to void (void*).
rtDataTypeMap is an array of structures that contains information about the various data types in the model. Each element of this array is of type struct rtwCAPI_DataTypeMap. The members of this structure provide the data type name, size of the data type, and information on whether or not the data is complex.
rtDimensionMap is an array of structures that contains information about the various data dimensions in the model. Each element of this array is of type struct rtwCAPI_DimensionMap. The members of this structure provide information on the number of dimensions in the data, the orientation of the data (whether it is scalar, vector, or a matrix), and the actual dimensions of the data.
rtFixPtMap is an array of structures that contains fixed-point information about the signals, states, root-level inputs/outputs, and parameters. Each element of this array is of type struct rtwCAPI_FixPtMap. The members of this structure provide information about the data scaling, bias, exponent, and whether or not the fixed-point data is signed. If the model does not have fixed-point data (signal, state, root-level input/output, or parameter), the Simulink Coder software assigns NULL or zero values to the elements of the rtFixPtMap array.
rtSampleTimeMap is an array of structures that contains sampling information about the global signals, states, and root-level inputs/outputs in the model. (This array contains no information about parameters.) Each element of this array is of type struct rtwCAPI_SampleTimeMap. The members of this structure provide information about the sample period, offset, and whether or not the data is frame-based or sample-based.
Generate Example C API Files. The next three sections, C API Signals, C API States, C API Root-Level Inputs and Outputs, and C API Parameters, discuss generated C API structures using the demo model rtwdemo_capi as an example. To generate code from the demo model, do the following:
Open the model by clicking the rtwdemo_capi link above or by typing rtwdemo_capi on the MATLAB command line. The model appears as shown in the next figure.

If you want to generate C API structures for root-level inputs/outputs in rtwdemo_capi, open the Configuration Parameters dialog box, go to the Code Generation > Interface pane, and make sure that the option Generate C API for: root-level I/O is selected.
Generate code for the model by double-clicking Generate Code Using Simulink Coder.
This model has three global block output signals that will appear in C API generated code:
top_sig1, which is a test point at the output of the Gain1 block in the top model
sig2_eg, which appears in the top model and is defined in the base workspace as a Simulink.Signal object having storage class ExportedGlobal
bot_sig1, which appears in the submodel rtwdemo_capi_bot and is defined as a Simulink.Signal object having storage class SimulinkGlobal
The model also has two discrete states that will appear in the C API generated code:
top_state, which is defined for the Delay1 block in the top model
bot_state, which is defined for the Discrete Filter block in the submodel
The model has root-level inputs/outputs that will appear in the C API generated code if you select the option Generate C API for: root-level I/O:
Four root-level inputs, In1 through In4
Six root-level outputs, Out1 through Out6
Additionally, the model has five global block parameters that will appear in C API generated code:
Kp (top model Gain1 block and submodel Gain2 block share)
Ki (submodel Gain3 block)
p1 (lookup table lu1d)
p2 (lookup table lu2d)
p3 (lookup table lu3d)
C API Signals. The rtwCAPI_Signals structure captures signal information including the signal name, address, block path, output port number, data type information, dimensions information, fixed-point information, and sample-time information.
Here is the section of code in rtwdemo_capi_capi.c that provides information on C API signals for the top model in rtwdemo_capi:
/* Block output signal information */
static const rtwCAPI_Signals rtBlockSignals[] = {
/* addrMapIndex, sysNum, blockPath,
* signalName, portNumber, dataTypeIndex, dimIndex, fxpIndex, sTimeIndex
*/
{ 0, 0, "rtwdemo_capi/Gain1",
"top_sig1", 0, 0, 0, 0, 0 },
{ 1, 0, "rtwdemo_capi/lu2d",
"sig2_eg", 0, 0, 1, 0, 0 },
{
0, 0, (NULL), (NULL), 0, 0, 0, 0, 0
}
};Note To better understand the code, read the comments in the file. For example, notice the comment that begins on the third line in the preceding code. This comment lists the members of the rtwCAPI_Signals structure, in order. This tells you the order in which the assigned values for each member appear for a signal. In this example, the comment tells you that signalName is the fourth member of the structure. The following lines describe the first signal: { 0, 0, "rtwdemo_capi/Gain1",
"top_sig1", 0, 0, 0, 0, 0 },From these lines you infer that the name of the first signal is top_sig1. |
Each array element, except the last, describes one output port for a block signal. The final array element is a sentinel, with all elements set to null values. For example, examine the second signal, described by the following code:
{ 1, 0, "rtwdemo_capi/lu2d",
"sig2_eg", 0, 0, 1, 0, 0 },This signal, named sig2_eg, is the output signal of the first port of the block rtwdemo_capi/lu2d. (This port is the first port because the zero-based index for portNumber displayed on the second line is assigned the value 0.)
The address of this signal is given by addrMapIndex, which, in this example, is displayed on the first line as 1. This provides an index into the rtDataAddrMap array, found later in rtwdemo_capi_capi.c:
/* Declare Data Addresses statically */
static void* rtDataAddrMap[] = {
&rtwdemo_capi_B.top_sig1, /* 0: Signal */
&sig2_eg[0], /* 1: Signal */
&rtwdemo_capi_DWork.top_state, /* 2: Discrete State */
&rtP_Ki, /* 3: Model Parameter */
&rtP_Kp, /* 4: Model Parameter */
&rtP_p1[0], /* 5: Model Parameter */
&rtP_p2[0], /* 6: Model Parameter */
&rtP_p3[0], /* 7: Model Parameter */
};The index of 1 points to the second element in the rtDataAddrMap array. From the rtDataAddrMap array, you can infer that the address of this signal is &sig2_eg[0].
This level of indirection supports multiple code instances of the same model. For multiple instances, the signal information remains constant, except for the address. In this case, the model is a single instance. Therefore, the rtDataAddrMap is declared statically. If you choose to generate reusable code, an initialize function is generated that initializes the addresses dynamically per instance. (For details on generating reusable code, see Set Up Support for Code Reuse and Entry Point Functions and Scheduling in the Embedded Coder documentation.)
The dataTypeIndex provides an index into the rtDataTypeMap array, found later in rtwdemo_capi_capi.c, indicating the data type of the signal:
/* Data Type Map - use dataTypeMapIndex to access this structure */
static const rtwCAPI_DataTypeMap rtDataTypeMap[] = {
/* cName, mwName, numElements, elemMapIndex, dataSize, slDataId, *
* isComplex, isPointer */
{ "double", "real_T", 0, 0, sizeof(real_T), SS_DOUBLE, 0, 0 }
};Because the index is 0 for sig2_eg, the index points to the first structure element in the array. You can infer that the data type of the signal is double. The value of isComplex is 0, indicating that the signal is not complex. Rather than providing the data type information directly in the rtwCAPI_Signals structure, a level of indirection is introduced. The indirection allows multiple signals that share the same data type to point to one map structure, saving memory for each signal.
The dimIndex (dimensions index) provides an index into the rtDimensionMap array, found later in rtwdemo_capi_capi.c, indicating the dimensions of the signal. Because this index is 1 for sig2_eg, the index points to the second element in the rtDimensionMap array:
/* Dimension Map - use dimensionMapIndex to access elements of ths structure*/
static const rtwCAPI_DimensionMap rtDimensionMap[] = {
/* dataOrientation, dimArrayIndex, numDims, vardimsIndex */
{ rtwCAPI_SCALAR, 0, 2, 0 },
{ rtwCAPI_VECTOR, 2, 2, 0 },
...
};From this structure, you can infer that this is a nonscalar signal having a dimension of 2. The dimArrayIndex value, 2, provides an index into rtDimensionArray, found later in rtwdemo_capi_capi.c:
/* Dimension Array- use dimArrayIndex to access elements of this array */
static const uint_T rtDimensionArray[] = {
1, /* 0 */
1, /* 1 */
2, /* 2 */
...
};The fxpIndex (fixed-point index) provides an index into the rtFixPtMap array, found later in rtwdemo_capi_capi.c, indicating any fixed-point information about the signal. Your code can use the scaling information to compute the real-world value of the signal, using the equation V=SQ+B, where V is "real-world" (that is, base-10) value, S is user-specified slope, Q is "quantized fixed-point value" or "stored integer," and B is user-specified bias. (For details, see Scaling in the Fixed-Point Toolbox™ documentation.)
Because this index is 0 for sig2_eg, the signal has no fixed-point information. A fixed-point map index of zero always means that the signal has no fixed-point information.
The sTimeIndex (sample-time index) provides the index to the rtSampleTimeMap array, found later in rtwdemo_capi_capi.c, indicating task information about the signal. If you log multirate signals or conditionally executed signals, the sampling information can be useful.
Note model_capi.c (or .cpp) includes rtw_capi.h. Any source file that references the rtBlockSignals array also must include rtw_capi.h. |
C API States. The rtwCAPI_States structure captures state information including the state name, address, block path, type (continuous or discrete), data type information, dimensions information, fixed-point information, and sample-time information.
Here is the section of code in rtwdemo_capi_capi.c that provides information on C API states for the top model in rtwdemo_capi:
/* Block states information */
static const rtwCAPI_States rtBlockStates[] = {
/* addrMapIndex, contStateStartIndex, blockPath,
* stateName, pathAlias, dWorkIndex, dataTypeIndex, dimIndex,
* fixPtIdx, sTimeIndex, isContinuous
*/
{ 2, -1, "rtwdemo_capi/Delay1",
"top_state", "", 0, 0, 0, 0, 0, 0 },
{
0, -1, (NULL), (NULL), (NULL), 0, 0, 0, 0, 0, 0
}
};Each array element, except the last, describes a state in the model. The final array element is a sentinel, with all elements set to null values. In this example, the C API code for the top model displays one state:
{ 2, -1, "rtwdemo_capi/Delay1",
"top_state", "", 0, 0, 0, 0, 0, 0 },This state, named top_state, is defined for the block rtwdemo_capi/Delay1. The value of isContinuous is zero, indicating that the state is discrete rather than continuous. The other fields correspond to the like-named signal equivalents described in C API Signals, as follows:
The address of the signal is given by addrMapIndex, which, in this example, is 2. This is an index into the rtDataAddrMap array, found later in rtwdemo_capi_capi.c. Because the index is zero based, 2 corresponds to the third element in rtDataAddrMap, which is &rtwdemo_capi_DWork.top_state.
The dataTypeIndex provides an index into the rtDataTypeMap array, found later in rtwdemo_capi_capi.c, indicating the data type of the parameter. The value 0 corresponds to a double, noncomplex parameter.
The dimIndex (dimensions index) provides an index into the rtDimensionMap array, found later in rtwdemo_capi_capi.c. The value 0 corresponds to the first entry, which is { rtwCAPI_SCALAR, 0, 2, 0 }.
The fixPtIndex (fixed-point index) provides an index into the rtFixPtMap array, found later in rtwdemo_capi_capi.c, indicating any fixed-point information about the parameter. As with the corresponding signal attribute, a fixed-point map index of zero always means that the parameter has no fixed-point information.
C API Root-Level Inputs and Outputs. The rtwCAPI_Signals structure captures root-level input/output information including the input/output name, address, block path, port number, data type information, dimensions information, fixed-point information, and sample-time information. (This structure also is used for block output signals, as previously described in C API Signals.)
Here is the section of code in rtwdemo_capi_capi.c that provides information on C API root-level inputs/outputs for the top model in rtwdemo_capi:
/* Root Inputs information */
static const rtwCAPI_Signals rtRootInputs[] = {
/* addrMapIndex, sysNum, blockPath,
* signalName, portNumber, dataTypeIndex, dimIndex, fxpIndex, sTimeIndex
*/
{ 3, 0, "rtwdemo_capi/In1",
"", 1, 0, 0, 0, 0 },
{ 4, 0, "rtwdemo_capi/In2",
"", 2, 0, 0, 0, 0 },
{ 5, 0, "rtwdemo_capi/In3",
"", 3, 0, 0, 0, 0 },
{ 6, 0, "rtwdemo_capi/In4",
"", 4, 0, 0, 0, 0 },
{
0, 0, (NULL), (NULL), 0, 0, 0, 0, 0
}
};
/* Root Outputs information */
static const rtwCAPI_Signals rtRootOutputs[] = {
/* addrMapIndex, sysNum, blockPath,
* signalName, portNumber, dataTypeIndex, dimIndex, fxpIndex, sTimeIndex
*/
{ 7, 0, "rtwdemo_capi/Out1",
"", 1, 0, 0, 0, 0 },
{ 8, 0, "rtwdemo_capi/Out2",
"", 2, 0, 0, 0, 0 },
{ 9, 0, "rtwdemo_capi/Out3",
"", 3, 0, 0, 0, 0 },
{ 10, 0, "rtwdemo_capi/Out4",
"", 4, 0, 0, 0, 0 },
{ 11, 0, "rtwdemo_capi/Out5",
"sig2_eg", 5, 0, 1, 0, 0 },
{ 12, 0, "rtwdemo_capi/Out6",
"", 6, 0, 1, 0, 0 },
{
0, 0, (NULL), (NULL), 0, 0, 0, 0, 0
}
};For information about interpreting the values in the rtwCAPI_Signals structure, see the previous section C API Signals.
C API Parameters. The rtwCAPI_BlockParameters and rtwCAPI_ModelParameters structures capture parameter information including the parameter name, block path (for block parameters), address, data type information, dimensions information, and fixed-point information. Each element in an rtBlockParameters or rtModelParameters array (except the last element) corresponds to a tunable parameter in the model.
The setting of the Inline parameters option on the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box determines how information is generated into the rtBlockParameters and rtModelParameters arrays in model_capi.c (or .cpp), as follows:
If you clear Inline parameters:
The rtBlockParameters array contains an entry for every modifiable parameter of every block in the model.
The rtModelParameters array contains only Stateflow data of machine scope. The Simulink Coder software assigns its elements only NULL or zero values in the absence of such data.
If you select Inline parameters:
The rtBlockParameters array is empty. The Simulink Coder software assigns its elements only NULL or zero values.
The rtModelParameters array contains entries for all workspace variables that are referenced as tunable Simulink block parameters or Stateflow data of machine scope.
Here is the rtBlockParameters array that is generated by default in rtwdemo_capi_capi.c:
/* Individual block tuning is not valid when inline parameters is *
* selected. An empty map is produced to provide a consistent *
* interface independent of inlining parameters. *
*/
static const rtwCAPI_BlockParameters rtBlockParameters[] = {
/* addrMapIndex, blockPath,
* paramName, dataTypeIndex, dimIndex, fixPtIdx
*/
{
0, (NULL), (NULL), 0, 0, 0
}
};In this example, only the final, sentinel array element is generated, with all members of the structure rtwCAPI_BlockParameters set to NULL and zero values. This is because the Inline parameters option is selected by default for the rtwdemo_capi demo model. If you clear this check box, the block parameters are generated in the rtwCAPI_BlockParameters structure.
Here is the rtModelParameters array that is generated by default in rtwdemo_capi_capi.c:
/* Tunable variable parameters */
static const rtwCAPI_ModelParameters rtModelParameters[] = {
/* addrMapIndex, varName, dataTypeIndex, dimIndex, fixPtIndex */
{ 3, "Ki", 0, 0, 0 },
{ 4, "Kp", 0, 0, 0 },
{ 5, "p1", 0, 2, 0 },
{ 6, "p2", 0, 3, 0 },
{ 7, "p3", 0, 4, 0 },
{ 0, (NULL), 0, 0, 0 }
};In this example, the rtModelParameters array contains entries for each variable that is referenced as a tunable Simulink block parameter.
For example, the varName (variable name) of the fourth parameter is p2. The other fields correspond to the like-named signal equivalents described in C API Signals, as follows:
The address of the fourth parameter is given by addrMapIndex, which, in this example, is 6. This is an index into the rtDataAddrMap array, found later in rtwdemo_capi_capi.c. Because the index is zero based, 6 corresponds to the seventh element in rtDataAddrMap, which is &rtwP_p2[0].
The dataTypeIndex provides an index into the rtDataTypeMap array, found later in rtwdemo_capi_capi.c, indicating the data type of the parameter. The value 0 corresponds to a double, noncomplex parameter.
The dimIndex (dimensions index) provides an index into the rtDimensionMap array, found later in rtwdemo_capi_capi.c. The value 3 corresponds to the fourth entry, which is { rtwCAPI_MATRIX_COL_MAJOR, 6, 2, 0 }.
The fixPtIndex (fixed-point index) provides an index into the rtFixPtMap array, found later in rtwdemo_capi_capi.c, indicating any fixed-point information about the parameter. As with the corresponding signal attribute, a fixed-point map index of zero always means that the parameter has no fixed-point information.
Map C API Data Structures to the Real-Time Model Data Structure. The real-time model data structure encapsulates model data and associated information that describes the model fully. When you select the C API feature and generate code, the Simulink Coder code generator adds another member to the real-time model data structure generated in model.h:
/*
* DataMapInfo:
* The following substructure contains information regarding
* structures generated in the model's C API.
*/
struct {
rtwCAPI_ModelMappingInfo mmi;
} DataMapInfo;This member defines mmi (for model mapping information) of type struct rtwCAPI_ModelMappingInfo. The structure is located in matlabroot/rtw/c/src/rtw_modelmap.h (where matlabroot represents the root of your MATLAB installation folder). The mmi substructure defines the interface between the model and the C API files. More specifically, members of mmi map the real-time model data structure to the structures in model_capi.c (or .cpp).
Initializing values of mmi members to the arrays accomplishes the mapping, as shown in Map Model to C API Arrays of Structures. Each member points to one of the arrays of structures in the generated C API file. For example, the address of the rtBlockSignals array of structures is allocated to the first member of the mmi substructure in model.c (or .cpp), using the following code in the rtw_modelmap.h file:
/* signals */
struct {
rtwCAPI_Signals const *signals; /* Signals Array */
uint_T numSignals; /* Num Signals */
rtwCAPI_Signals const *rootInputs; /* Root Inputs array */
uint_T numRootInputs; /* Num Root Inputs */
rtwCAPI_Signals const *rootOutputs; /* Root Outputs array */
uint_T numRootOutputs;/* Num Root Outputs */
} Signals;The model initialize function in model.c (or .cpp) performs the initializing by calling the C API initialize function. For example, the following code is generated in the model initialize function for demo model rtwdemo_capi:
/* Initialize DataMapInfo substructure containing ModelMap for C API */ rtwdemo_capi_InitializeDataMapInfo(rtwdemo_capi_M);
Map Model to C API Arrays of Structures

Note This figure lists the arrays in the order that their structures appear in rtw_modelmap.h, which differs slightly from their generated order in model_capi.c. |
The C API provides you with the flexibility of writing your own application code to interact with model signals, states, root-level inputs/outputs, and parameters. Your target-based application code is compiled with the Simulink Coder generated code into an executable. The target-based application code accesses the C API structure arrays in model_capi.c (or .cpp). You might have host-based code that interacts with your target-based application code. Or, you might have other target-based code that interacts with your target-based application code. The files rtw_modelmap.h and rtw_capi.h, located in matlabroot/rtw/c/src (where matlabroot represents the root of your MATLAB installation folder), provide macros for accessing the structures in these arrays and their members.
This section provides examples to help you get started writing application code to interact with model signals, states, root-level inputs/outputs, and parameters.
Use the C API to Access Model Signals and States. Here is an example application that logs global signals and states in a model to a text file. This code is intended as a starting point for accessing signal and state addresses. You can extend the code to perform signal logging and monitoring, state logging and monitoring, or both.
This example uses the following macro and function interfaces:
rtmGetDataMapInfo macro
Accesses the model mapping information (MMI) substructure of the real-time model structure. In the following macro call, rtM is the pointer to the real-time model structure in model.c (or .cpp):
rtwCAPI_ModelMappingInfo* mmi = &(rtmGetDataMapInfo(rtM).mmi);
rtmGetTPtr macro
Accesses the absolute time information for the base rate from the timing substructure of the real-time model structure. In the following macro call, rtM is the pointer to the real-time model structure in model.c (or .cpp):
rtmGetTPtr(rtM)
Custom functions capi_StartLogging, capi_UpdateLogging, and capi_TerminateLogging, provided via the files rtwdemo_capi_datalog.h and rtwdemo_capi_datalog.c. These files are located in matlabroot/toolbox/rtw/rtwdemos, where matlabroot represents the root of your MATLAB installation folder.
capi_StartLogging initializes signal and state logging.
capi_UpdateLogging logs a signal and state value at each time step.
capi_TerminateLogging terminates signal and state logging and writes the logged values to a text file.
You can integrate these custom functions into generated model code using any or all of the following methods:
Code Generation > Custom Code pane of the Configuration Parameters dialog box
Custom Code library blocks
TLC custom code functions
This tutorial uses the Code Generation > Custom Code pane and the System Outputs block from the Custom Code library to insert calls to the custom functions into model.c (or .cpp), as follows:
capi_StartLogging is called in the MdlStart function (or if an ert.tlc target is selected for the model, in the model_initialize function).
capi_UpdateLogging is called in the model_output function.
capi_TerminateLogging is called in the model_terminate function.
The following excerpts of generated code from model.c (rearranged to reflect their order of execution) show how the function interfaces are used.
void MdlStart(void)
{
/* user code (Start function Trailer) */
/* C API Custom Logging Function: Start Signal and State logging via C-API.
* capi_StartLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(rtwdemo_capi_M).mmi);
printf("** Started state/signal logging via C API **\n");
capi_StartLogging(MMI, MAX_DATA_POINTS);
}
...
}
...
/* Model output function */
static void rtwdemo_capi_output(int_T tid)
{
...
/* user code (Output function Trailer) */
/* C API Custom Logging Function: Update Signal and State logging buffers.
* capi_UpdateLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(rtwdemo_capi_M).mmi);
capi_UpdateLogging(MMI, rtmGetTPtr(rtwdemo_capi_M));
}
...
}
...
/* Model terminate function */
void rtwdemo_capi_terminate(void)
{
/* user code (Terminate function Trailer) */
/* C API Custom Logging Function: Dump Signal and State buffers into a text file.
* capi_TerminateLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
capi_TerminateLogging("rtwdemo_capi_ModelLog.txt");
printf("** Finished state/signal logging. Created rtwdemo_capi_ModelLog.txt **\n");
}
}The following procedure illustrates how you can use the C API macro and function interfaces to log global signals and states in a model to a text file.
At the MATLAB command line, enter rtwdemo_capi to open the demo model.
Open the Configuration Parameters dialog box and go to the Code Generation pane.
For the System target file parameter, select grt.tlc. (Alternatively, if you are licensed for Embedded Coder software, you can select ert.tlc. Make sure that you also select ert.tlc for the referenced model rtwdemo_capi_bot.)
Note Selecting a system target file other than grt.tlc or disabling some C API options (signals, parameters, or states) in the top model requires corresponding changes in the referenced model. Because the demo models have read-only access, you must save the updated referenced model with a different name and modify the top model to reference the renamed model. |
Go to the Interface pane.
In the Data exchange subpane, for the Interface parameter, verify that C API is selected.
Additionally, verify that the options Generate C API for: signals and Generate C API for: states are selected. This example also leaves Generate C API for: parameters selected. If you clear any of the options, make sure that the settings match between the top model and the referenced model.

If you are using the ert.tlc target, verify that the options MAT-file logging and Support: complex numbers are selected.
If you modified any option settings in this step, click Apply.
Use the Custom Code pane to embed your custom application code in the generated code. Select the Custom Code pane, and then click Include directories. The Include directories input field is displayed.
In the Include directories field, type matlabroot/toolbox/rtw/rtwdemos, where matlabroot represents the root of your MATLAB installation folder.
In the Include list of additional subpane, click Source files, and type rtwdemo_capi_datalog.c, as shown below.

In the Include custom C code in generated subpane, click Source file, and type or copy and paste the following include statement:
#include "rtwdemo_capi_datalog.h"
In the Initialize function field, type or copy and paste the following application code:
/* C API Custom Logging Function: Start Signal and State logging via C-API.
* capi_StartLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(rtwdemo_capi_M).mmi);
printf("** Started state/signal logging via C API **\n");
capi_StartLogging(MMI, MAX_DATA_POINTS);
}In the Terminate function field, type or copy and paste the following application code:
/* C API Custom Logging Function: Dump Signal and State buffers into a text file.
* capi_TerminateLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
capi_TerminateLogging("rtwdemo_capi_ModelLog.txt");
printf("** Finished state/signal logging. Created rtwdemo_capi_ModelLog.txt **\n");
}Click Apply.
In the MATLAB Command Window, enter custcode to open the Simulink Coder Custom Code library. At the top level of the rtwdemo_capi model, add a System Outputs block.
Double-click the System Outputs block to open the System Outputs Function Custom Code dialog box. In the System Outputs Function Exit Code field, type or copy and paste the following application code:
/* C API Custom Logging Function: Update Signal and State logging buffers.
* capi_UpdateLogging: Function prototype in rtwdemo_capi_datalog.h
*/
{
rtwCAPI_ModelMappingInfo *MMI = &(rtmGetDataMapInfo(rtwdemo_capi_M).mmi);
capi_UpdateLogging(MMI, rtmGetTPtr(rtwdemo_capi_M));
}Click OK.
On the Code Generation pane, verify that the Build button is visible. If it is not visible, clear the option Generate code only and click Apply.
Click Build to build the model and generate an executable file. For example, on a Windows system, the build generates the executable file rtwdemo_capi.exe.
In the MATLAB Command Window, enter the command !rtwdemo_capi to run the executable file. During execution, signals and states are logged using the C API and then written to the text file rtwdemo_capi_ModelLog.txt in your working folder.
>> !rtwdemo_capi ** starting the model ** ** Started state/signal logging via C API ** ** Logging 2 signal(s) and 2 state(s). In this demo, only scalar named signals/states are logged ** ** Finished state/signal logging. Created rtwdemo_capi_ModelLog.txt **
Examine the text file in the MATLAB editor or any text editor. Here is an excerpt of the signal and state logging output.
******** Signal Log File ******** Number of Signals Logged: 2 Number of points (time steps) logged: 51 Time bot_sig1 (Referenced Model) top_sig1 0 70 4 0.2 70 4 0.4 70 4 0.6 70 4 0.8 70 4 1 70 4 1.2 70 4 1.4 70 4 1.6 70 4 1.8 70 4 2 70 4 ... ******** State Log File ******** Number of States Logged: 2 Number of points (time steps) logged: 51 Time bot_state (Referenced Model) top_state 0 0 0 0.2 70 4 0.4 35 4 0.6 52.5 4 0.8 43.75 4 1 48.13 4 1.2 45.94 4 1.4 47.03 4 1.6 46.48 4 1.8 46.76 4 2 46.62 4 ...
Use the C API to Access Model Parameters. Here is an example application that prints the parameter values of all tunable parameters in a model to the standard output. This code is intended as a starting point for accessing parameter addresses. You can extend the code to perform parameter tuning. The application:
Uses the rtmGetDataMapInfo macro to access the mapping information in the mmi substructure of the real-time model structure
rtwCAPI_ModelMappingInfo* mmi = &(rtmGetDataMapInfo(rtM).mmi);
where rtM is the pointer to the real-time model structure in model.c (or .cpp).
Uses rtwCAPI_GetNumModelParameters to get the number of model parameters in mapped C API:
uint_T nModelParams = rtwCAPI_GetNumModelParameters(mmi);
Uses rtwCAPI_GetModelParameters to access the array of all model parameter structures mapped in C API:
rtwCAPI_ModelParameters* capiModelParams = \ rtwCAPI_GetModelParameters(mmi);
Loops over the capiModelParams array to access individual parameter structures. A call to the function capi_PrintModelParameter displays the value of the parameter.
The example application code is provided below:
{
/* Get CAPI Mapping structure from Real-Time Model structure */
rtwCAPI_ModelMappingInfo* capiMap = \
&(rtmGetDataMapInfo(rtwdemo_capi_M).mmi);
/* Get number of Model Parameters from capiMap */
uint_T nModelParams = rtwCAPI_GetNumModelParameters(capiMap);
printf("Number of Model Parameters: %d\n", nModelParams);
/* If the model has Model Parameters, print them using the
application capi_PrintModelParameter */
if (nModelParams == 0) {
printf("No Tunable Model Parameters in the model \n");
}
else {
unsigned int idx;
for (idx=0; idx < nModelParams; idx++) {
/* call print utility function */
capi_PrintModelParameter(capiMap, idx);
}
}
}The print utility function is located in matlabroot/rtw/c/src/rtw_capi_examples.c (where matlabroot represents the root of your MATLAB installation folder). This file contains utility functions for accessing the C API structures.
To become familiar with the example code, try building a model that displays all the tunable block parameters and MATLAB variables. You can use rtwdemo_capi.mdl, the C API demo model. The following steps apply to both grt.tlc and ert.tlc targets, unless otherwise indicated.
At the MATLAB command line, enter rtwdemo_capi to open the demo model.
Open the Configuration Parameters dialog box and go to the Optimization > Signals and Parameters pane.
If you are licensed for Embedded Coder software and you want to use the ert.tlc target instead of the default grt.tlc, go to the Code Generation pane and use the System target file field to select an ert.tlc target.
Use the Custom Code pane to embed your custom application code in the generated code. Select the Custom Code pane, and then click Initialize function. The Initialize function input field is displayed.
In the Initialize function input field, type or copy and paste the example application code shown above step 1. This embeds the application code in the MdlStart function. (If you are using ert.tlc, the code appears in the model_initialize function.)
Click Include directories, and type matlabroot/rtw/c/src, where matlabroot represents the root of your MATLAB installation folder.
In the Include list of additional subpane, click Source files, and type rtw_capi_examples.c.

Click Apply.
If you are using the ert.tlc target, go to the Code Generation > Interface pane, select the following options, and then click Apply.
In the Interface list, C API
MAT-file logging
Support: complex numbers
Go to the Code Generation pane and clear the Generate code only check box if it is not already cleared.
Click Build. The Simulink Coder code generator generates the executable file rtwdemo_capi.exe in your current working folder.
At the MATLAB command line, enter !rtwdemo_capi to run the executable file. Running the program displays parameter information in the Command Window.
>> !rtwdemo_capi ** starting the model ** Number of Model Parameters: 5 Ki = 7 Kp = 4 p1 = 0.8147 0.9058 0.127 p2 = 0.9649 0.9706 0.4854 0.1576 0.9572 0.8003 p3 = ans(:,:,1) = 0.1419 0.9157 0.9595 0.03571 0.4218 0.7922 0.6557 0.8491 ans(:,:,2) = 0.934 0.7577 0.3922 0.1712 0.6787 0.7431 0.6555 0.706 >>
The C API feature has the following limitations.
The following code formats are not supported:
S-function
Accelerated simulation
For ERT-based targets, the C API requires that support for floating-point code be enabled.
Local block output signals are not supported.
Local Stateflow parameters are not supported.
The following custom storage class objects are not supported:
Objects without the package csc_registration file
BitPackBoolean objects, grouped custom storage classes, and objects defined by using macros
Customized data placement is disabled when you are using the C API. The interface looks for global data declaration in model.h and model_private.h. Declarations placed in any other file by customized data placement result in code that does not compile.
Note Custom Storage Class objects take effect in code generation only if you use the ERT target and clear the Ignore custom storage classes check box in the Configuration Parameters dialog box. |
ASAP2 is a data definition standard proposed by the Association for Standardization of Automation and Measuring Systems (ASAM). ASAP2 is a non-object-oriented description of the data used for measurement, calibration, and diagnostic systems. For more information on ASAM and the ASAP2 standard, see the ASAM Web site at http://www.asam.net.
The Simulink Coder product lets you export an ASAP2 file containing information about your model during the code generation process.
To make use of ASAP2 file generation, you should become familiar with the following topics:
ASAM and the ASAP2 standard and terminology. See the ASAM Web site at http://www.asam.net.
Simulink data objects. Data objects are used to supply information not contained in the model. For an overview, see Working with Data in the Simulink documentation.
Storage and representation of signals and parameters in generated code. See Data, Function, and File Definition.
Signal and parameter objects and their use in code generation. See Data, Function, and File Definition.
You can run an interactive demo of ASAP2 file generation. To open the demo at the MATLAB command prompt, enter the following command:
rtwdemo_asap2
Note Simulink Coder support for ASAP2 file generation is version-neutral. By default, the software generates ASAP2 version 1.31 format, but the generated model information is generally compatible with all ASAP2 versions. ASAP2 file generation also is neutral with respect to the specific needs of ASAP2 measurement and calibration tools. The software provides customization APIs that you can use to customize ASAP2 file generation to generate any ASAP2 version and to meet the specific needs of your ASAP2 tools. |
ASAP2 file generation is available to all Simulink Coder target configurations. You can select these target configurations from the System Target File Browser. For example,
The Generic Real-Time Target (grt.tlc) lets you generate an ASAP2 file as part of the code generation and build process.
Any of the Embedded Coder (ert.tlc) target selections also lets you generate an ASAP2 file as part of the code generation and build process.
The ASAM-ASAP2 Data Definition Target (asap2.tlc) lets you generate only an ASAP2 file, without building an executable.
Procedures for generating ASAP2 files by using these target configurations are given in Generate an ASAP2 File.
Define ASAP2 Information for Parameters and Signals. The ASAP2 file generation process requires information about your model's parameters and signals. Some of this information is contained in the model itself. You must supply the rest by using Simulink data objects and corresponding properties.
You can use built-in Simulink data objects to provide the information. For example, you can use Simulink.Signal objects to provide MEASUREMENT information and Simulink.Parameter objects to provide CHARACTERISTIC information. Also, you can use data objects from data classes that are derived from Simulink.Signal and Simulink.Parameter to provide the information. For details, see Working with Data in the Simulink documentation.
The following table contains the minimum set of data attributes required for ASAP2 file generation. Some data attributes are defined in the model; others are supplied in the properties of objects. For attributes that are defined in Simulink.Signal or Simulink.Parameter objects, the table gives the associated property name.
Data Attribute | Defined In | Property Name |
|---|---|---|
Name (symbol) | Data object | Inherited from the handle of the data object to which parameter or signal name resolves |
Description | Data object | Description |
Data type | Model | Not applicable |
Scaling | Model | Data type (for signals) Inherited from value (for parameters) |
Minimum allowable value | Data object | Min |
Maximum allowable value | Data object | Max |
Units | Data object | DocUnits |
Memory address (optional) | Data object | MemoryAddress_ASAP2 (optional; see Memory Address Attribute.) |
Memory Address Attribute. If the memory address attribute is unknown before code generation, the code generator inserts an ECU Address placeholder string in the generated ASAP2 file. You can substitute an actual address for the placeholder by postprocessing the generated file. See the file matlabroot/toolbox/rtw/targets/asap2/asap2/asap2post.m for an example. asap2post.m parses through the linker map file that you provide and replaces the placeholder strings in the ASAP2 file with the actual memory addresses. Since linker map files vary from compiler to compiler, you might need to modify the regular expression code in asap2post.m to match the format of the linker map you use.
Note If Embedded Coder is licensed and installed on your system, and if you are generating ELF (Executable and Linkable Format) files for your embedded target, you can use the rtw.asap2SetAddress function to automate ECU address replacement. For more information, see Automatic ECU Address Replacement for ASAP2 Files (Embedded Coder). |
If the memory address attribute is known before code generation, it can be defined in the data object. By default, the MemoryAddress_ASAP2 property does not exist in the Simulink.Signal or Simulink.Parameter data object classes. If you want to add the attribute, add a property called MemoryAddress_ASAP2 to a custom class that is a subclass of the Simulink or ASAP2 class. For information on subclassing Simulink data classes, see Define Level-1 Data Classes Using Data Class Designer in the Simulink documentation.
Note In previous releases, for ASAP2 file generation, you had to define objects explicitly as ASAP2.Signal and ASAP2.Parameter. This is no longer a limitation. As explained above, you can use built-in Simulink objects for generating an ASAP2 file. If you have been using an earlier release, you can continue to use the ASAP2 objects. If one of these ASAP2 objects was created in the previous release, and you use it in this release, the MATLAB Command Window displays a warning the first time the objects are loaded. |
The following table indicates the Simulink object properties that have replaced the ASAP2 object properties of the previous release:
Differences Between ASAP2 and Simulink Parameter and Signal Object Properties
ASAP2 Object Properties (Previous) | Simulink Object Properties (Current) |
|---|---|
Automatic ECU Address Replacement for ASAP2 Files (Embedded Coder). If Embedded Coder is licensed and installed on your system, and if you are generating ELF (Executable and Linkable Format) files for your embedded target, you can use the rtw.asap2SetAddress function to automate the replacement of ECU Address placeholder memory address values with actual addresses in the generated ASAP2 file.
If the memory address attribute is unknown before code generation, the code generator inserts an ECU Address placeholder string in the generated ASAP2 file, as shown in the example below.
/begin CHARACTERISTIC
/* Name */ Ki
/* Long Identifier */ ""
/* Type */ VALUE
/* ECU Address */ 0x0
/*ECU_Address@Ki@ */To substitute actual addresses for the ECU Address placeholders, postprocess the generated ASAP2 file using the rtw.asap2SetAddress function. The general syntax is as follows:
rtw.asap2SetAddress(ASAP2File, InfoFile)
where the arguments are strings specifying the name of the generated ASAP2 file and the name of the generated executable ELF file or DWARF debug information file for the model. When called, rtw.asap2SetAddress extracts the actual ECU address from the specified ELF or DWARF file and replaces the placeholder in the ASAP2 file with the actual address, for example:
/begin CHARACTERISTIC /* Name */ Ki /* Long Identifier */ "" /* Type */ VALUE /* ECU Address */ 0x40009E60
Define ASAP2 Information for Lookup Tables. Simulink Coder software generates ASAP2 descriptions for lookup table data and its breakpoints. The software represents 1-D table data as CURVE information, 2-D table data as MAP information, and breakpoints as AXIS_DESCR and AXIS_PTS information. You can model lookup tables using any of the following Simulink Lookup Table blocks:
Direct Lookup Table (n-D) — 1 and 2 dimensions
Interpolation Using Prelookup — 1 and 2 dimensions
1–D Lookup Table
2–D Lookup Table
n-D Lookup Table — 1 and 2 dimensions
The software supports the following types of lookup table breakpoints (axis points):
| Breakpoint Type | Generates |
|---|---|
| Tunable and shared among multiple table axes (common axis) | COM_AXIS |
| Fixed and nontunable (fixed axis) | One of these variants of FIX_AXIS:
|
| Tunable but not shared among multiple tables (standard axis) | STD_AXIS |
When you configure the blocks for ASAP2 code generation:
For table data, use a Simulink.Parameter data object with a non-Auto storage class.
For tunable breakpoint data that is shared among multiple table axes (COM_AXIS), use a Simulink.Parameter data object with a non-Auto storage class.
For fixed, nontunable breakpoint data (FIX_AXIS), use workspace variables or arrays specified in the block parameters dialog box. The breakpoints should be stored as integers in the code, so the data type should be a built-in integer type (int8, int16, int32, uint8, uint16, or uint32), a fixed-point data type, or an equivalent alias type.
For tunable breakpoint data that is not shared among multiple tables (STD_AXIS):
Create a Simulink.Bus object to define the struct packaging (names and order of the fields). The fields of the parameter structure must correspond to the lookup table data and each axis of the lookup table block. For example, in an n-D Lookup Table block with 2 dimensions, the structure must contain only three fields. This bus object describes the record layout for the lookup characteristic.
Create a Simulink.Parameter object to represent a tunable parameter.
Create table and axis values.
Optionally, specify the Units, Minimum, and Maximum properties for the parameter object. The properties will be applied to table data only.
Here is an example of an n-D Lookup Table record generated into an ASAP2 file in Standard Axis format:
/begin CHARACTERISTIC
/* Name */ STDAxisParam
...
/* Record Layout */ Lookup1D_X_WORD_Y_FLOAT32_IEEE
...
begin AXIS_DESCR
/* Description of X-Axis Points */
/* Axis Type */ STD_AXIS
...
/end AXIS_DESCR
/end CHARACTERISTIC
/begin RECORD_LAYOUT Lookup1D_X_WORD_Y_FLOAT32_IEEE
AXIS_PTS_X 1 WORD INDEX_INCR DIRECT
FNC_VALUES 2 FLOAT32_IEEE COLUMN_DIR DIRECT
/end RECORD_LAYOUTNote The demo model rtwdemo_asap2 illustrates ASAP2 file generation for Lookup Table blocks, including both tunable (COM_AXIS) and fixed (FIX_AXIS) lookup table breakpoints. |
About Generating ASAP2 Files. You can generate an ASAP2 file from your model in one of the following ways:
Use the Generic Real-Time Target or a Embedded Coder target to generate an ASAP2 file as part of the code generation and build process.
Use the ASAM-ASAP2 Data Definition Target to generate only an ASAP2 file, without building an executable.
This section discusses how to generate an ASAP2 file by using the targets that have built-in ASAP2 support. For an example, see the ASAP2 demo, rtwdemo_asap2.
Use Generic Real-Time Target or Embedded Coder Target. The procedure for generating a model's data definition in ASAP2 format using the Generic Real-Time Target or an Embedded Coder target is as follows:
Create the desired model. Use parameter names and signal labels to refer to corresponding CHARACTERISTIC records and MEASUREMENT records , respectively.
Define the desired parameters and signals in the model to be Simulink.Parameter and Simulink.Signal objects in the MATLAB workspace. A convenient way of creating multiple signal and parameter data objects is to use the Data Object Wizard. Alternatively, you can create data objects one at a time from the MATLAB command line. For details on how to use the Data Object Wizard, see Data Object Wizard in the Simulink documentation.
For each data object, configure the Storage class property to a setting other than Auto or SimulinkGlobal. This declares the data object as global in the generated code. For example, a storage class setting of ExportedGlobal configures the data object as unstructured global in the generated code.
Configure the remaining properties as desired for each data object.
On the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box, select the Inline parameters check box.
You should not configure the parameters associated with your data objects as Simulink global (tunable) parameters in the Model Parameter Configuration dialog box. If a parameter that resolves to a Simulink data object is configured using the Model Parameter Configuration dialog box, the dialog box configuration is ignored. You can, however, use the Model Parameter Configuration dialog box to configure other parameters in your model.
On the Code Generation pane, click Browse to open the System Target File Browser. In the browser, select Generic Real-Time Target or any embedded real-time target and click OK.
In the Interface field on the Interface pane, select ASAP2.

Select the Generate code only check box on the Code Generation pane.
The Simulink Coder code generator writes the ASAP2 file to the build folder. By default, the file is named model.a2l, where model is the name of the model. The ASAP2 filename is controlled by the ASAP2 setup file. For details see Customize an ASAP2 File.
Use the ASAM-ASAP2 Data Definition Target. The procedure for generating a model's data definition in ASAP2 format using the ASAM-ASAP2 Data Definition Target is as follows:
Create the desired model. Use parameter names and signal labels to refer to corresponding CHARACTERISTIC records and MEASUREMENT records , respectively.
Define the desired parameters and signals in the model to be Simulink.Parameter and Simulink.Signal objects in the MATLAB workspace. A convenient way of creating multiple signal and parameter data objects is to use the Data Object Wizard. Alternatively, you can create data objects one at a time from the MATLAB command line. For details on how to use the Data Object Wizard, see Data Object Wizard in the Simulink documentation.
For each data object, configure the Storage class property to a setting other than Auto or SimulinkGlobal. This causes the data object to be declared as global in the generated code. For example, a storage class setting of ExportedGlobal configures the data object as unstructured global in the generated code.
Configure the remaining properties as desired for each data object.
On the Optimization > Signals and Parameters pane of the Configuration Parameters dialog box, select the Inline parameters check box.
You should not configure the parameters associated with your data objects as Simulink global (tunable) parameters in the Model Parameter Configuration dialog box. If a parameter that resolves to a Simulink data object is configured using the Model Parameter Configuration dialog box, the dialog box configuration is ignored. You can, however, use the Model Parameter Configuration dialog box to configure other parameters in your model.
On the Code Generation pane, click Browse to open the System Target File Browser. In the browser, select ASAM-ASAP2 Data Definition Target and click OK.
Select the Generate code only check box on the Code Generation pane.
The Simulink Coder code generator writes the ASAP2 file to the build folder. By default, the file is named model.a2l, where model is the name of the model. The ASAP2 filename is controlled by the ASAP2 setup file. For details see Customize an ASAP2 File.
Generate ASAP2 Files for Referenced Models. The build process can generate an ASAP2 file for each referenced model in a model reference hierarchy. In the generated ASAP2 file, MEASUREMENT records represent signals and states inside the referenced model.
To generate ASAP2 files for referenced models, select ASAP2 file generation for the top model and for each referenced model in the reference hierarchy. For example, if you are using the Generic Real-Time Target or an Embedded Coder target, follow the procedure described in Use Generic Real-Time Target or Embedded Coder Target for the top model and each referenced model.
Merge ASAP2 Files Generated for Top and Referenced Models. Use function rtw.asap2MergeMdlRefs to merge the ASAP2 files generated for top and referenced models. The function has the following syntax:
[status,info]=rtw.asap2MergeMdlRefs(topModelName,asap2FileName)
topModelName is the name of the model containing referenced models.
asap2FileName is the name you specify for the merged ASAP2 file.
Optional:: status returns true (logical 0) if the merge is successful and false (logical 1) otherwise.
Optional:: info returns additional information about merge failure if status is false. Otherwise, it returns an empty string.
Consider the following example.
[status,info]=rtw.asap2MergeMdlRefs('myTopMdl','merged.a2l')This command merges the ASAP2 files generated for the top model myTopMdl and its referenced models in the file merged.a2l.
The demo model rtwdemo_asap2 provides an example of merging ASAP2 files.
The following table outlines the basic structure of the ASAP2 file and describes the Target Language Compiler (TLC) functions and files used to create each part of the file:
Static parts of the ASAP2 file are shown in bold.
Function calls are indicated by %<FunctionName()>.
The ASAP2 and C API interfaces are not mutually exclusive. Although the Interface option on the Code Generation > Interface pane of the Configuration Parameters dialog box allows you to select either the ASAP2 or C API interface, you can instruct the Simulink Coder product to generate files for both interfaces by doing the following:
On the Code Generation > Interface pane of the Configuration Parameters dialog box, select C API for the Interface option.

In the MATLAB Command Window, with the model open, specify the following command:
>> set_param(gcs,'GenerateASAP2','on')
Click Generate or Build. The code generator generates the following ASAP2 and C API files:
model.a2l — ASAP2 description file
model_capi.c — C API source file
model_capi.h — C API header file
For more information about using the C API interface, see Data Interchange Using the C API.
The Simulink Coder product provides a TLC function library that lets you create a global data map record. The global data map record, when generated, is added to the CompiledModel structure in the model.rtw file. The global data map record is a database containing all information required for accessing memory in the generated code, including
Signals (Block I/O)
Parameters
Data type work vectors (DWork)
External inputs
External outputs
Use of the global data map requires knowledge of the Target Language Compiler and of the structure of the model.rtw file. See the Target Language Compiler documentation for information on these topics.
The TLC functions that are required to generate and access the global data map record are contained in matlabroot/rtw/c/tlc/mw/globalmaplib.tlc. The comments in the source code fully document the global data map structures and the library functions.
The global data map structures and functions might be modified or enhanced in future releases.
![]() | Simulation and Code Comparison | Performance | ![]() |

Learn more about Simulink through this collection of videos, articles, technical literature and the Getting Started with Simulink Guide.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |