Skip to Main Content Skip to Search
Product Documentation

Data Exchange

Host/Target Communication

About Host/Target Communication

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

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.

Set Up an External Mode Communication Channel

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:

  1. Set up the model.

  2. Build the target executable.

  3. Run the external mode target program.

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

  1. Create the folder from the MATLAB command line by typing

    mkdir ext_mode_example
  2. Make ext_mode_example your working folder:

    cd ext_mode_example
  3. 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.

  4. Define and assign two variables A and B in the MATLAB workspace as follows:

    A = 2; B = 3;
  5. Open Gain block A and set its Gain parameter to the variable A.

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

  7. Verify operation of the model. Open the Scope blocks and run the model. When A = 2 and B = 3, the output looks like this.

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

  1. Open Model Explorer by selecting Model Explorer from the model's View menu.

  2. In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.

  3. Click Configuration (Active) in the left pane.

  4. Select Solver in the center pane. The Solver pane appears at the right.

  5. In the Solver Options pane:

    1. Select Fixed-step in the Type field.

    2. Select Discrete (no continuous states) in the Solver field.

    3. Specify 0.1 in the Fixed-step size field. (Otherwise, the Simulink Coder build process posts a warning and supplies a value when you generate code.)

  6. Click Apply. The dialog box appears below. Note that after you click Apply, the controls you changed again have a white background color.

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

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

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

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

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

  12. Click Apply to save the Interface settings.

  13. Save the model.

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

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.

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

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

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

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

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

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

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

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

  1. In the MATLAB Command Window, assign new values to both variables, for example:

    A = 0.5;B = 3.5;
  2. 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.

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

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

Use the External Mode User Interface

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.

The Data exchange section at the bottom has the following elements:

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:

Once external mode is enabled, you can connect to and control the target program by doing any of the following:

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.

Simulation Menu.  

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)

Toolbar Controls.  

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

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

The behavior of wired scopes is not restricted in these ways.

The Floating scope pane contains a check box and an edit field:

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.

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:

For serial transport, ext_serial_win32_comm allows three optional arguments:

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

Signal Selection.  

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

Trigger Signal Selection.  

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.  

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.

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:

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

External Mode Compatible Blocks and Subsystems

Compatible Blocks.  In external mode, you can use the following types of blocks to receive and view signals uploaded from the target program:

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,

  1. Select the Treat as atomic unit option in the Block Parameters dialog box.

    See Subsystems for more information on atomic subsystems.

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

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

You configure data archiving by using the External Data Archiving dialog box, as described in Data Archiving.

External Mode Communications

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.

Choose a Communications Protocol for Client and Server Interfaces

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

The next figure shows the structure of the TCP/IP-based implementation.

TCP/IP-Based Client/Server Implementation for External Mode

MEX-File Optional Arguments for TCP/IP Transport.  

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.

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

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

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:

Running the External Program Under the UNIX Environment.  

In the UNIX environment, you can run the external programs in either of the following ways:

Command-Line Options for the External Program.  

External mode target executables generated by the Simulink Coder code generator support the following command-line options:

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.

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.

Use External Mode Programmatically

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.

  1. Change the Simulink model to external mode:

    set_param(gcs, 'SimulationMode', 'external')
  2. Connect the open model to the loaded target program:

    set_param(gcs, 'SimulationCommand', 'connect')
  3. Start running the target program:

    set_param(gcs, 'SimulationCommand', 'start')
  4. Stop running the target program:

    set_param(gcs, 'SimulationCommand', 'stop')
  5. 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.

External Mode Command-Line Parameters

Parameter and ValuesDialog Box EquivalentDescription
ExtModeAddSuffixToVar
off, on
External Data Archiving: Append file suffix to variable names check boxIncrement variable names for each incremented filename.
ExtModeArchiveDirName
string
External Data Archiving: Directory text fieldSave data in specified folder.
ExtModeArchiveFileName
string
External Data Archiving: File text fieldSave data in specified file.
ExtModeArchiveMode
string - off, on
External Data Archiving: Enable archiving check boxActivate automated data archiving features.
ExtModeArmWhenConnect
off, on
External Signal & Triggering: Arm when connecting to target check boxArm 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 boxSave new data buffers in incremental files.
ExtModeAutoUpdateStatusClock (MicrosoftWindows platforms only)
off, on
Not availableContinuously upload and display target time on the model window status bar.
ExtModeBatchMode
off, on
External Mode Control Panel: Batch download check boxEnable or disable downloading of parameters in batch mode.
ExtModeChangesPending
off, on
Not availableWhen ExtModeBatchMode is enabled, indicates whether any parameters remain in the queue of parameters to be downloaded to the target.
ExtModeCommand
string
Not availableIssue an external mode command to the target program.
ExtModeConnected
off, on
External Mode Control Panel: Connect/Disconnect buttonIndicate the state of the connection with the target program.
ExtModeEnableFloating
off, on
External Mode Control Panel: Enable data uploading check boxEnable 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 boxWrite log files to incremental folders each time the trigger is armed.
ExtModeLogAll
off, on
External Signal & Triggering: Select all check boxUpload all available signals from the target to the host.
ExtModeLogCtrlPanelDlg
string
Not availableReturn a handle to the External Mode Control Panel dialog box or –1 if the dialog box does not exist.
ExtModeParamChangesPending
off, on
Not availableWhen 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 availableConnect to the target program without downloading parameters.
ExtModeTrigDelay
integer (0)
External Signal & Triggering: Delay text fieldSpecify 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 menuSpecify the direction in which the signal must be traveling when it crosses the threshold value.
ExtModeTrigDuration
integer (1000)
External Signal & Triggering: Duration text fieldSpecify 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 fieldSpecify 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 fieldSpecify 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 fieldSpecify the base rate steps between when a trigger event terminates and the trigger is rearmed.
ExtModeTrigLevel
integer (0)
External Signal & Triggering: Level text fieldSpecify the threshold value the trigger signal must cross to fire the trigger.
ExtModeTrigMode
string - normal, oneshot
External Signal & Triggering: Mode menuSpecify 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 fieldSpecify 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 menuSpecify 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 availableReturn the status of the external mode upload mechanism — inactive, armed, or uploading.
ExtModeWriteAllDataToWs
off, on
External Data Archiving: Write intermediate results to workspace check boxWrite all intermediate results to the workspace.

External Mode Limitations

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

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:

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:

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.

Logging

Log Data for Analysis

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.

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:

  1. Open Model Explorer by selecting Model Explorer from the model's View menu.

  2. In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.

  3. Click Configuration (Active) in the left pane.

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

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

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

      Note   The sort order of the yout array is based on the port number of the Outport blocks, starting with 1. Angle of Attack and Pilot G Force are logged to yout(:,1) and yout(:,2), respectively.

  7. If any other options are enabled, clear them. Set Decimation to 1 and Format to Array. The figure below shows the dialog.

  8. Click Apply to register your changes.

  9. Save the model.

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

  11. 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
  12. 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:

  1. Open Model Explorer by selecting Model Explorer from the model's View menu.

  2. In the Model Hierarchy pane, click the + sign preceding the model name to reveal its components.

  3. Click Configuration (Active) in the left pane.

  4. In the center pane, click Code Generation. The Code Generation pane appears to the right.

  5. Click the Interface tab.

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

  7. Clear the Generate code only check box, if it is currently selected. The pane should look like this:

  8. Click Apply to register your changes.

  9. Save the model.

  10. To generate code and build an executable, click the Build button.

  11. When the build concludes, run the executable with the command:

    !rtwdemo_f14
  12. The program now produces two message lines, indicating that the MAT-file has been written.

    ** starting the model ** 
    ** created rtwdemo_f14.mat ** 
  13. 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.

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

About Logging to MAT-Files

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.

Configure a Model to Log States, Time, and Output

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:

Override the Default MAT-File Name.  The MAT-file name defaults to model.mat. To specify a different file name,

  1. In the model window, select Simulation > Configuration Parameters. The dialog box opens.

  2. Click Code Generation.

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

  1. In the model window, select Simulation > Configuration Parameters. The dialog box opens.

  2. Click Code Generation.

  3. Select grt.tlc for System target file.

  4. Select Code Generation > Interface

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

  1. In the model window, select Simulation > Configuration Parameters. The dialog box opens.

  2. Click Code Generation.

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

Log Data with Scope and To Workspace Blocks

The code generated by the code generator also logs data from these sources:

The variables are written to model.mat, along with any variables logged from the Workspace I/O pane.

Log Data with To File Blocks

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.

Data Logging Differences in Single- and Multitasking Models

When logging data in single-tasking and multitasking systems, you will notice differences in the logging of

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.

Parameter Tuning

Tunable Parameter Storage

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

Tunable Parameter Storage Classes

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:

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.

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 Tunable Parameters

Declare Workspace Variables as Tunable Parameters.  To declare tunable parameters,

  1. Open the Model Parameter Configuration dialog box.

  2. In the Source list pane, select one or more variables.

  3. Click Add to table . The variables then appear as tunable parameters in the Global (tunable) parameters pane.

  4. Select a parameter in the Global (tunable) parameters pane.

  5. Select a storage class from the Storage class menu.

  6. Optionally, select (or enter) a storage type qualifier, such as const or volatile for the parameter.

  7. Click Apply, or click OK to apply changes and close the dialog box.

Declare New Tunable Parameters.  To declare tunable parameters,

  1. Open the Model Parameter Configuration dialog box.

  2. In the Global (tunable) parameters pane, click New.

  3. Specify a name for the parameter.

  4. Select a storage class from the Storage class menu.

  5. Optionally, select (or enter) a storage type qualifier, such as const or volatile for the parameter.

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

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

  2. Click Configure to open the Model Configuration Parameter dialog box.

Select Workspace Variables.  The Source list pane displays a menu and a scrolling table of numerical workspace variables. To select workspace variables,

  1. From the menu, select the source of variables you want listed.

    To List...Choose...
    All variables in the MATLAB workspace that have numeric valuesMATLAB workspace
    Only variables in the MATLAB workspace that have numeric values and are referenced by the modelReferenced workspace variables

    A list of workspace variables appear in the Source List pane.

  2. Select one or more variables from the source list. This enables the Add to table button.

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

      Note   If you selected a variable with a name that matches a block parameter that is not tunable and you click Add to table , a warning appears during simulation and code generation.

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,

  1. In the Global (tunable) parameters pane, click New.

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

  3. Click Apply.

The model does not need to be using a parameter before you create it. You can add references to the parameter later.

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.

PropertyDescription
Storage class

Select one of the following to be used for code generation:

  • SimulinkGlobal (Auto)

  • ExportedGlobal

  • ImportedExtern

  • ImportedExternPointer

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.

Tunable Expressions

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:

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

Linear Block Parameter Tunability

The following blocks have a Realization parameter that affects the tunability of their parameters:

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:

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.

Tunable Workspace Parameter Data Type Considerations

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:

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 matchUses that data type for the parameter in the generated code.
You do not explicitly specify a data type other than double in the workspaceUses 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 workspaceUses 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 typecastingBlocks only
Interface to legacy or custom codeThe workspace explicitly
Use the same parameter for multiple blocks that specify different data typesThe 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

Tune Parameters from the Command Line

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.

The following commands return the tunable parameters and corresponding properties:

The following commands declare tunable parameters or set corresponding properties:

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.

Interfaces for Tuning Parameters

The Simulink Coder product includes

Data Interchange Using the C API

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.

About Data Exchange and C API

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

Generate C API Files

To generate C API files for your model:

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

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

  1. Open your model, and launch either the Configuration Parameters dialog box or Model Explorer.

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

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

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

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

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:

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

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

      Note   The setting of Generate C API for: root-level I/O must match between the top model and the referenced model.

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

The model also has two discrete states that will appear in the C API generated code:

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:

Additionally, the model has five global block parameters that will appear in C API generated code:

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
  }
};

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.

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:

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:

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:

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

Use the C API in an Application

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:

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.

  1. At the MATLAB command line, enter rtwdemo_capi to open the demo model.

  2. Open the Configuration Parameters dialog box and go to the Code Generation pane.

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

  4. Go to the Interface pane.

    1. In the Data exchange subpane, for the Interface parameter, verify that C API is selected.

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

    3. If you are using the ert.tlc target, verify that the options MAT-file logging and Support: complex numbers are selected.

    4. If you modified any option settings in this step, click Apply.

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

  6. In the Include directories field, type matlabroot/toolbox/rtw/rtwdemos, where matlabroot represents the root of your MATLAB installation folder.

  7. In the Include list of additional subpane, click Source files, and type rtwdemo_capi_datalog.c, as shown below.

  8. 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"
  9. 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);
      }
  10. 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");
      }
  11. Click Apply.

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

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

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

  15. 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 **
  16. 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:

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.

  1. At the MATLAB command line, enter rtwdemo_capi to open the demo model.

  2. Open the Configuration Parameters dialog box and go to the Optimization > Signals and Parameters pane.

  3. Verify that the Inline parameters option is selected.

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

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

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

  7. Click Include directories, and type matlabroot/rtw/c/src, where matlabroot represents the root of your MATLAB installation folder.

  8. In the Include list of additional subpane, click Source files, and type rtw_capi_examples.c.

    Click Apply.

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

  10. Go to the Code Generation pane and clear the Generate code only check box if it is not already cleared.

  11. Click Build. The Simulink Coder code generator generates the executable file rtwdemo_capi.exe in your current working folder.

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

C API Limitations

The C API feature has the following limitations.

ASAP2 Data Measurement and Calibration

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.

About ASAP2 Data Measurement and Calibration

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:

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

Targets Supporting ASAP2

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,

Procedures for generating ASAP2 files by using these target configurations are given in Generate an ASAP2 File.

Define ASAP2 Information

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
(if fixed-point data type)

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.

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.

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)

LONGIG_ASAP2

Description

PhysicalMin_ASAP2

Min

PhysicalMax_ASAP2

Max

Units_ASAP2

DocUnits

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:

The software supports the following types of lookup table breakpoints (axis points):

Breakpoint TypeGenerates
Tunable and shared among multiple table axes (common axis)

COM_AXIS

Fixed and nontunable (fixed axis)

One of these variants of FIX_AXIS:

  • FIX_AXIS_PAR if breakpoints are integers with equidistant spacing

  • FIX_AXIS_PAR_DIST if breakpoints are integers with equidistant spacing and the equidistant spacing is a power of two

  • FIX_AXIS_PAR_LIST if breakpoints are integers with non-equidistant spacing

Tunable but not shared among multiple tables (standard axis)

STD_AXIS

When you configure the blocks for ASAP2 code generation:

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_LAYOUT

Generate an ASAP2 File

About Generating ASAP2 Files.  You can generate an ASAP2 file from your model in one of the following ways:

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:

  1. Create the desired model. Use parameter names and signal labels to refer to corresponding CHARACTERISTIC records and MEASUREMENT records , respectively.

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

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

      Note   If you set the storage class to Auto or SimulinkGlobal, or if you set the storage class to Custom and custom storage class settings cause the Simulink Coder code generator to generate a macro or non-addressable variable, the data object is not represented in the ASAP2 file.

  4. Configure the remaining properties as desired for each data object.

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

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

  7. In the Interface field on the Interface pane, select ASAP2.

  8. Select the Generate code only check box on the Code Generation pane.

  9. Click Apply.

  10. Click Generate code.

    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:

  1. Create the desired model. Use parameter names and signal labels to refer to corresponding CHARACTERISTIC records and MEASUREMENT records , respectively.

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

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

      Note   If you set the storage class to Auto or SimulinkGlobal, or if you set the storage class to Custom and custom storage class settings cause the Simulink Coder code generator to generate a macro or non-addressable variable, the data object is not represented in the ASAP2 file.

  4. Configure the remaining properties as desired for each data object.

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

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

  7. Select the Generate code only check box on the Code Generation pane.

  8. Click Apply.

  9. Click Generate code.

    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)

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.

Structure of the ASAP2 File

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:

File Section

Contents of asap2main.tlc

TLC File Containing Function Definition

File header

%<ASAP2UserFcnWriteFileHead()>

asap2userlib.tlc

/begin PROJECT ""

/begin PROJECT "%<ASAP2ProjectName>"

asap2setup.tlc

/begin HEADER ""
HEADER contents

/begin HEADER"%<ASAP2HeaderName>"
%<ASAP2UserFcnWriteHeader()>

asap2setup.tlc
asap2userlib.tlc

/end HEADER

/end HEADER

/begin MODULE ""
MODULE contents:

/begin MODULE "%<ASAP2ModuleName>"}

asap2setup.tlc
asap2userlib.tlc

- A2ML
- MOD_PAR
- MOD_COMMON
...

%<ASAP2UserFcnWriteHardwareInterface()>

Model-dependent MODULE contents:

%<SLibASAP2WriteDynamicContents()>
Calls user-defined functions:

asap2lib.tlc

- RECORD_LAYOUT
- CHARACTERISTIC
- ParameterGroups
- ModelParameters

...WriteRecordLayout_TemplateName()

  ...WriteCharacteristic_TemplateName()
  ...WriteCharacteristic_Scalar()

user/templates/...

- MEASUREMENT
- ExternalInputs
- BlockOutputs

...WriteMeasurement()

asap2userlib.tlc

- COMPU_METHOD

...WriteCompuMethod()

asap2userlib.tlc

/end MODULE

/end MODULE

File footer/tail

%<ASAP2UserFcnWriteFileTail()>

asap2userlib.tlc

Generate ASAP2 and C API Files

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:

  1. On the Code Generation > Interface pane of the Configuration Parameters dialog box, select C API for the Interface option.

  2. In the MATLAB Command Window, with the model open, specify the following command:

    >>  set_param(gcs,'GenerateASAP2','on')

      Note   If you select both the C API and ASAP2 data interfaces, only the C API options are displayed in the Configuration Parameters dialog box.

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

Direct Memory Access to Generated Code

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

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.

  


Related Products & Applications

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