Main Content

External Mode Simulation with TCP/IP

Set up and run an external mode simulation that uses a TCP/IP or serial (RS-232) communication channel between the development computer and the selected hardware board.

  1. Create and configure a simple model.

  2. Build, deploy and start the target executable file.

  3. Tune parameters.

Create and Configure Model

In this part of the example, you create a simple model, ex_extModeExample. You also create a folder called ext_mode_example to store the model and the generated executable.

To create the folder and the model:

  1. From the MATLAB® command line, type:

    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. Be sure to label the Gain and Scope blocks.

    Scope block A displays the output of Gain block A, and Scope block B displays the output of Gain block B.

  4. Define and assign two MATLAB workspace variables, A and B:

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

    Use the Function Block Parameters dialog box to configure the Gain block.

  6. Open Gain block B and set its Gain parameter to the variable B.

    When the target application is built and connected to Simulink in external mode, you can download new gain values to the executing target application. To do this, you can assign new values to workspace variables A and B, or edit the values in the block parameters dialog box. For more information, see Tune Parameters.

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

    Scope block A and Scope block B display the simulation output signals.

  8. Save the model as ex_extModeExample.

Build Target Executable

Set up the model and code generation parameters required for an external mode target application. Then, generate code and build the target application.

  1. From the Apps tab on the Simulink toolstrip, click Run on Hardware Board.

  2. In the Run on Hardware Board pop-up, set Hardware board to a supported AMD Zynq® hardware board.

  3. In the Prepare section, click Hardware Settings. The Configuration Parameters dialog box opens, displaying Hardware Implementation settings that are determined by the system target file.

  4. On the Solver pane:

    1. In the Type field, select Fixed-step.

    2. In the Solver field, select discrete (no continuous states).

    3. Click Solver details. In the Fixed-step size field, specify 0.1.

    4. Click Apply.

  5. On the Hardware Implementation > Hardware board settings > External Mode pane, set Communication interface to TCP/IP.

  6. Click OK. Then save the model.

Run Target Application

You now run the ex_extModeExample target executable and use Simulink as an interactive front end to the running target application. The executable file is in your working folder. Run the target application and establish communication between Simulink and the target.

To run the target application:

  1. On the Hardware tab, in the Run on Hardware section, click Monitor & Tune. Then:

    1. In the Stop Time field, specify inf, which makes the model run until the target application receives a stop message from Simulink.

    2. Under Step By Step Commands, click Deploy.

    The target application begins execution, and enters a wait state.

  2. Open the Scope blocks in the model. Signals are not visible on the scopes until you begin model execution.

  3. On the Hardware tab, in the Run on Hardware section, click Monitor & Tune. Then, under Step By Step Commands, click Connect. This action initiates a handshake between Simulink and the target application. When Simulink and the target are connected, the Connect button changes to Disconnect.

  4. In the Run on Hardware section, click , which starts execution of the generated model code. The two scopes in your model display the outputs of Gain blocks A and B.

You have established communication between Simulink and the running target application. You can now tune block parameters in Simulink and observe the effects of parameter changes.

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 you update the block diagram, the new values are downloaded to the target application.

  1. On the Hardware tab, in the Prepare section, click Batch Mode.

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

    A = 0.5;
    B = 3.5;
  3. On the Hardware tab, in the Prepare section, click Update All Parameters. Simulink updates the block parameters and downloads the new gain values to the target application.

Under certain conditions, you can also tune the expressions that you use to specify block parameter values. To change an expression during simulation, use the block parameter dialog box:

  1. In the Sine Wave block dialog box, set Amplitude to 0.5.

  2. Click Apply or OK. Simulink downloads the new block parameter value to the target application.

To simultaneously disconnect Simulink from the host/target communication and end execution of the target application, on the Hardware tab, in the Run on Hardware section, click Stop.

You cannot change the sample time of the Sine Wave block during simulation. 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 sample time of the block, and rebuild the executable.

Block parameter tunability during external mode simulation depends on the way that the generated code represents block parameters.

For example, in the Gain A block dialog box, you cannot change the expression A in the Gain parameter during simulation. Instead, you must change the value of the variable A in the base workspace. You cannot change the expression because the generated code does not allocate storage in memory for the Gain parameter. Instead, the code creates a field A in a structure:

/* Parameters (auto storage) */
struct P_ex_extModeExample_T_ {
  real_T A;                            /* Variable: A
                                        */
  real_T B;                            /* Variable: B
                                        */
  real_T SineWave_Amp;                 /* Expression: 1
                                        */
  real_T SineWave_Bias;                /* Expression: 0
                                        */
  real_T SineWave_Freq;                /* Expression: 1
                                        */
  real_T SineWave_Phase;               /* Expression: 0
                                        */
};

The generated code algorithm uses that field in the code that represents the block Gain A. In this case, the global structure variable ex_extModeExample_P uses the type P_ex_extModeExample_T_:

ex_extModeExample_B.GainA = ex_extModeExample_P.A * rtb_SineWave;

When you change the value of A in the base workspace, the simulation downloads the new value to the field A in the target application.

You can change the expressions in the Sine Wave block parameters during simulation because the generated code creates a field in the global structure ex_extModeExample_P to represent each parameter in the block. When you change an expression in the block dialog box, the simulation first evaluates the new expression. The simulation then downloads the resulting numeric value to the corresponding structure field in the target application.

See Create Tunable Calibration Parameter in the Generated Code.

Control Memory Allocation for Communication Buffers in Target

If you select the Code Generation > Interface > Static memory allocation check box (for GRT and ERT targets), the code generator produces code for external mode that uses only static memory allocation (“malloc-free” code). Selecting Static memory allocation enables the Static memory buffer size parameter. Use this parameter to specify the size of the external mode static memory buffer. The default value is 1,000,000 bytes. If you enter too small a value for your program, the external mode simulation issues an out-of-memory error when it tries to allocate more memory than specified. In such cases, increase the value in the Static memory buffer size field and regenerate the code.

To determine how much memory to allocate, enable verbose mode on the target (by including OPTS="-DVERBOSE" on the make command line). As it executes, external mode displays the amount of memory it tries to allocate and the amount of memory available to it each time it attempts an allocation. If an allocation fails, you can use this console log to determine the required value for the Static memory buffer size field.

Control External Mode Simulation Through External Mode Control Panel

The External Mode Control Panel provides centralized control of external mode operations, including:

To open the External Mode Control Panel dialog box, on the Hardware tab, in the Prepare section, click Control Panel.

Connect, Start, and Stop

The External Mode Control Panel performs the same connect/disconnect and start/stop functions found on the Hardware tab on the Simulink toolstrip, see Summary of Graphical Controls for External Mode Simulation.

Clicking the Connect button connects your model to a waiting or running target application. While you are connected, the button changes to a Disconnect button. Disconnect disconnects your model from the target environment, but does not halt real-time code running in the target environment.

Clicking the Start Real-Time Code button commands the target to start running real-time code. While real-time code is running in the target environment, the button changes to a Stop Real-Time Code button. Stop Real-Time Code stops target application execution and disconnects your model from the target environment.

Upload Target Application Signal Data to Host

The External Mode Control Panel allows you to trigger and cancel data uploads to the host. The destination for the uploaded data can be a scope block, Display block, To Workspace block, or another block or subsystem listed in Blocks and Subsystems Compatible with External Mode.

The Arm Trigger and Cancel Trigger buttons provide manual control of data uploading to compatible blocks or subsystems, except floating scopes. (For floating scopes, use the Floating scope section of the External Mode Control Panel.)

  • To trigger data uploading to compatible blocks or subsystems, click the Arm Trigger button. The button changes to Cancel Trigger.

  • To cancel data uploading, click the Cancel Trigger button. The button reverts to Arm Trigger.

You can trigger data uploads manually or automatically. To configure signals and triggers for data uploads, see Configure Host Monitoring of Target Application Signal Data.

A subset of external mode compatible blocks, including Scope, Time Scope, and To Workspace, allow you to log uploaded data to disk. To configure data archiving, see Configure Host Archiving of Target Application Signal Data.

The Floating scope section of the External Mode Control Panel controls when and for how long data is uploaded to Floating Scope blocks. When used in external mode, floating scopes:

  • Do not appear in the External Signal & Triggering dialog box.

  • Do not log data to external mode archiving.

  • Support manual triggering only.

The Floating scope section contains the following parameters:

  • Enable data uploading option, which functions as an Arm Trigger button for floating scopes. When the target is disconnected, the option controls whether to arm the trigger when connecting the floating scopes. When the target is connected, the option acts as a toggle button to arm or cancel the trigger.

    • To trigger data uploading to floating scopes, select Enable data uploading.

    • To cancel data uploading to floating scopes, clear Enable data uploading.

  • Duration edit field, which specifies the number of base-rate steps for which external mode logs floating scopes data after a trigger event. By default, it is set to auto, which causes the duration value set in the External Signal & Triggering dialog box to be used. The default duration value is 1000 base rate steps.

Download Parameters to Target Application

The Batch download option on the External Mode Control Panel enables or disables batch parameter changes.

By default, batch download is disabled. If batch download is disabled, when you click OK or Apply, changes made directly to block parameters by editing block parameter dialog boxes are sent to the target. When you perform an Update Diagram, changes to MATLAB workspace variables are sent.

If you select Batch download, the Download button is enabled. Until you click Download, changes made to block parameters are stored locally. When you click Download, the changes are sent in a single transmission.

When parameter changes are awaiting batch download, the External Mode Control Panel displays the message Parameter changes pending... to the right of the Download button. This message remains visible until the Simulink engine receives notification that the new parameters have been installed in the parameter vector of the target system.

The External Mode Control Panel dialog box appears with the Batch download option activated and parameter changes pending.

Configure Host Monitoring of Target Application Signal Data

Role of Trigger in Signal Data Uploading

In external mode, uploading target application signal data to the host depends on a trigger. The trigger is a set of conditions that must be met for data uploading to begin. The trigger can be armed or not armed.

  • When the trigger is armed, the software checks for the trigger conditions that allow data uploading to begin.

  • If the trigger is not armed, the software does not check for the trigger conditions and data uploading cannot begin.

  • The trigger can be armed automatically, when the host connects to the target, or manually, by clicking the Arm Trigger button on the External Mode Control Panel.

When the trigger is armed and the trigger conditions are met, the trigger fires and data uploading begins.

When data has been collected for a defined duration, the trigger event completes and data uploading stops. The trigger can then rearm, or remain unarmed until you click the Arm Trigger button.

To select the target application signals to upload and configure how uploads are triggered, see Configure Signal Data Uploading.

Configure Signal Data Uploading

Clicking the Signal & Triggering button of the External Mode Control Panel opens the External Signal & Triggering dialog box.

Use the External Signal and Triggering dialog box to select the signals that are collected from the target system.

The External Signal & Triggering dialog box displays a list of blocks and subsystems in your model that support external mode signal uploading. For information on which types of blocks are external mode compatible, see Blocks and Subsystems Compatible with External Mode.

In the External Signal & Triggering dialog box, you can select the signals that are collected from the target system and viewed in external mode. You can also select a trigger signal, which triggers uploading of data based on meeting certain signal conditions, and define the triggering conditions.

Default Trigger Options

The preceding figure shows the default settings of the External Signal & Triggering dialog box. The default operation of the External Signal & Triggering dialog box simplifies monitoring the target application. If you use the default settings, you do not need to preconfigure signals and triggers. You start the target application and connect the Simulink engine to it. External mode compatible blocks are selected and the trigger is armed. Signal uploading begins immediately upon connection to the target application.

The default configuration of trigger options is:

  • Select all: on

  • Source: manual

  • Mode: normal

  • Duration: 1000

  • Delay: 0

  • Arm when connecting to target: on

Select Signals to Upload

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 that you want to view. In the Selected column, an X appears for each selected block.

The Select all check box selects all signals. By default, Select all is selected.

If Select all is cleared, you can select or clear individual signals using the on and off options. To select a signal, click its list entry and select the on option. To clear a signal, click its list entry and select the off option.

The Clear all button clears all signals.

Configure Trigger Options

As described in Role of Trigger in Signal Data Uploading, signal data uploading depends on a trigger. The trigger defines conditions that must be met for uploading to begin. Also, the trigger must be armed for data uploading to begin. When the trigger is armed and trigger conditions are met, the trigger fires and uploading begins. When data has been collected for a defined duration, the trigger event completes and data uploading stops.

To control when and how signal data is collected (uploaded) from the target system, configure the following Trigger options in the External Signal & Triggering dialog box.

  • Source: manual or signal. Controls whether a button or a signal triggers data uploading.

    Selecting manual directs external mode to use the Arm Trigger button on the External Mode Control Panel as the trigger to start uploading data. When you click Arm Trigger, data uploading begins.

    Selecting signal directs external mode to use a trigger signal as the trigger to start uploading data. When the trigger signal satisfies trigger conditions (that is, the signal crosses the trigger level in the specified direction), a trigger event occurs. (Specify trigger conditions in the Trigger signal section.) If the trigger is armed, external mode monitors for the occurrence of a trigger event. When a trigger event occurs, data uploading begins.

  • Mode: normal or one-shot. Controls whether the trigger rearms after a trigger event completes.

    In normal mode, external mode automatically rearms the trigger after each trigger event. The next data upload begins when the trigger fires.

    In one-shot mode, external mode collects only one buffer of data each time you arm the trigger.

    For more information on the Mode setting, see Configure Host Archiving of Target Application Signal Data.

  • Duration: Specifies the number of base rate steps for which external mode uploads data after a trigger event (default is 1000). For example, if Duration is set to 1000, and the base (fastest) rate of the model is one second:

    • For a signal sampled at the base rate, one second (1.0 Hz), external mode collects 1000 contiguous samples during a trigger event.

    • For a signal sampled at two seconds (0.5 Hz), external mode collects 500 samples during a trigger event.

  • Delay: Specifies a delay to be applied to data collection. The delay represents the amount of time that elapses between a trigger event and the start of data collection. The delay is expressed in base rate steps. It can be positive or negative (default is 0). A negative delay corresponds to pretriggering. When the delay is negative, data from the time preceding the trigger event is collected and uploaded.

  • Arm when connecting to target: Selected or cleared. Whether a button or a signal triggers data uploading (as defined by Source), the trigger must be armed to allow data uploading to begin.

    If you select this option, connecting to the target arms the trigger.

    • If the trigger Source is manual, data uploading begins immediately.

    • If the trigger Source is signal, monitoring of the trigger signal begins immediately. Data uploading begins when the trigger signal satisfies trigger conditions (as defined in the Trigger signal section).

    If you clear Arm when connecting to target, manually arm the trigger by clicking the Arm Trigger button on the External Mode Control Panel.

When simulating in external mode, each rate in the model creates a buffer on the target. Each entry in the buffer is big enough to hold all of the data required of every signal in that rate for one time step (time plus data plus external mode indices identifying the signal). The number of entries in the circular buffer is determined by the external mode trigger Duration parameter (ExtModeTrigDuration). The memory allocated on the target for buffering signals is proportional to the Duration and the number of signals uploading. The Duration also provides an indication of the number of base rate steps with log data after a trigger event in external mode.

The Duration value specifies the number of contiguous points of data to be collected in each buffer of data. You should enter a Duration value equal to the number of continuous sample points that you need to collect rather than relying on a series of buffers to be continuous. If you enter a value less than the total number of sample points, you may lose sample points during the time spent transferring values from the data buffer to the MATLAB workspace. The Simulink software maintains point continuity only within one buffer. Between buffers, because of transfer time, some samples may be omitted.

The Duration value can affect the Limit data points to last value of Scope and To Workspace blocks. The number of sample points that the blocks save to the MATLAB workspace is the smaller of the two values. To set the number of sample points that the blocks save, clear Limit data points to last. Then, use Duration to specify the number of sample points saved.

Select Trigger Signal

You can designate one signal as a trigger signal. To select a trigger signal, from the Source menu in the Trigger options section, select signal. This action enables the parameters in the Trigger signal section. Then, select a signal in the Signal selection list, and click the Trigger Signal button.

When you select a signal to be a trigger, a T appears in the Trigger column of 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 in the Selected column.

Use the External Signal and Triggering dialog box to select the signals that are collected from the target system.

After selecting the trigger signal, you can use the Trigger signal section to define the trigger conditions and set the trigger signal Port and Element parameters.

Set Trigger Conditions

Use the Trigger signal section of the External Signal & Triggering dialog box to set trigger conditions and attributes. Trigger signal parameters are enabled only when the trigger parameter Source is set to signal in the Trigger options section.

By default, any element of the first input port of a 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 values in the Trigger signal section. The Port field accepts a number or the keyword last. The Element field accepts a number or the keywords any or last.

In the Trigger signal section, you also define the conditions under which a trigger event occurs.

  • Direction: rising, falling, or either. The direction in which the signal must be traveling when it crosses the threshold value. The default is rising.

  • Level: A value indicating the threshold the signal must cross in a designated direction to fire the trigger. By default, the level is 0.

  • Hold-off: Applies only to normal mode. Expressed in base rate steps, Hold-off is the time between the termination of one trigger event and the rearming of the trigger.

Modify Signal and Triggering Options While Connected

After you configure signal data uploading, and connect Simulink to a running target executable, you can modify signal and triggering options without disconnecting from the target.

If the trigger is armed (for example, if the trigger option Arm when connecting to the target is selected, which is the default), the External Signal & Triggering dialog box cannot be modified. To modify signal and triggering options:

  1. Open the External Mode Control Panel.

  2. Click Cancel Trigger. Triggering and display of uploaded data stops.

  3. Open the External Signal & Triggering dialog box and modify signal and trigger options as required. For example, in the Signal selection section, you can enable or disable a scope, and in the Trigger options section, change the trigger Mode, for example, from normal to one-shot.

  4. Click Arm Trigger. Triggering and display of uploaded data resumes, with your modifications.

    Use the External Signal and Triggering dialog box to modify signal and trigger options.

Configure Host Archiving of Target Application Signal Data

In external mode, you can use the Simulink Scope and To Workspace blocks to archive data to disk.

To understand how the archiving features work, consider the handling of data when archiving is not enabled. There are two cases, one-shot mode and normal mode.

  • In one-shot mode, after a trigger event occurs, each selected block writes its data to the workspace, 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. Because the trigger can fire at any time, writing intermediate results to the workspace can result 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, you can override the default behavior by selecting the Write intermediate results to workspace option. This option does not protect the workspace data from being overwritten by subsequent triggers.

If you use a Simulink Scope block to archive data to disk, open the Scope parameters dialog box and select the option Log data to workspace. The option is required for these reasons:

  • The data is first transferred from the scope data buffer to the MATLAB workspace, before being written to a MAT-file.

  • The Variable name entered in the Scope parameters dialog box is the same as the one in the MATLAB workspace and the MAT-file. Enabling the data to be saved enables a variable named with the Variable name parameter to be saved to a MAT-file.

Note

If you do not select the Scope block option Log data to workspace, the MAT-files for data logging are created, but they are empty.

The Enable Data Archiving dialog box supports:

  • Folder notes

  • File notes

  • Automated data archiving

On the External Mode Control Panel, click the Data Archiving button to open the Enable Data Archiving dialog box. If your model is connected to the target environment, disconnect it while you configure data archiving. To enable the other controls in the dialog box, select Enable archiving.

Use the Enable Data Archiving dialog box to enable archiving.

These operations are supported by the Enable Data Archiving dialog box.

Folder Notes

To add annotations for a collection of related data files in a folder, in the Enable Data Archiving dialog box, click Edit Directory Note. The MATLAB editor opens. 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

To add annotations for an individual data file, in the Enable Data Archiving dialog box, click Edit File Note. A file finder window opens, which by default is set to the last file to which you have written. Selecting a MAT-file opens an edit window. In this window, add or edit comments that you want saved with your individual MAT-file.

Automated Data Archiving

To configure automatic writing of logging results to disk, optionally including intermediate results, use the Enable archiving option and the controls it enables. The dialog box provides the following related controls:

  • Directory: Specifies the folder in which data is saved. If you select Increment directory when trigger armed, external mode appends a suffix.

  • File: Specifies the name of the file in which data is saved. If you select Increment file after one-shot, external mode appends a suffix.

  • Increment directory when trigger armed: Each time that you click the Arm Trigger button, external mode uses a different folder for writing log files. The folders are named incrementally, for example, dirname1, dirname2, and so on.

  • Increment file after one-shot: New data buffers are saved in incremental files: filename1, filename2, and so on. File incrementing happens automatically in normal mode.

  • Append file suffix to variable names: Whenever external mode increments file names, each file contains variables with identical names. Selecting Append file suffix to variable name results in each file containing unique variable names. For example, external mode saves a variable named xdata in incremental files (file_1, file_2, and so on) as xdata_1, xdata_2, and so on. This approach supports loading the MAT-files into the workspace and comparing variables at the MATLAB command prompt. Without the unique names, each instance of xdata would overwrite the previous one in the MATLAB workspace.

  • Write intermediate results to workspace: If you want the Simulink Coder™ software to write intermediate results to the workspace, select this option.

Summary of Graphical Controls for External Mode Simulation

You can control an XCP external mode simulation through:

  • The Hardware tab on the Simulink toolstrip. To display the Hardware tab, from the Apps tab on the Simulink toolstrip, click Run on Custom Hardware.

  • The External Mode Control Panel. To open this dialog box, in Simulink Editor, on the Hardware tab, in the Prepare section, click . Then under Signal Monitoring & Tracing, click Control Panel.

This table gives Hardware tab features that you can use to control an external mode simulation.

External Mode ActionHardware TabExternal Mode Control Panel Button
Connect your model to a waiting or running target applicationRun on Hardware >
Connect
button
Connect
Start running real-time code in the target environmentStart button Start Real-Time Code
Disconnect your model from the target environment (does not halt running real-time code)Run on Hardware >
Disconnect
button
Disconnect
Stop target application execution and disconnect your model from the target environmentStop button Stop Real-Time Code

Blocks and Subsystems Compatible with External Mode

Compatible Blocks

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

  • Floating Scope and Scope blocks

  • Spectrum Analyzer and Time Scope blocks from the DSP System Toolbox™ product

  • Display blocks

  • To Workspace blocks

  • User-written S-Function blocks

    An external mode method is built into the S-function API. This method allows user-written blocks to support external mode. See matlabroot/simulink/include/simstruc.h.

  • XY Graph blocks

You can designate certain subsystems as Signal Viewing Subsystems and use them to receive and view signals uploaded from the target application. 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, such blocks in a model are selected, and a manual trigger is set to be armed when connected to the target application.

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, and does not generate code in the target system. Signal Viewing Subsystems run in normal, accelerator, rapid accelerator, and external simulation modes.

Note

Signal Viewing Subsystems are inactive if placed inside a SIL or PIL component, such as a top model in SIL or PIL mode, a Model block in SIL or PIL mode, or a SIL or PIL block. However, a SIL or PIL component can feed a Signal Viewing Subsystem running in a supported mode.

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. In the Block Parameters dialog box, select the Treat as atomic unit option.

    For more information on atomic subsystems, see Generate Subsystem Code as Separate Function and Files.

  2. To turn the SimViewingDevice property on, use the set_param command:

    set_param('blockname', 'SimViewingDevice','on')

    '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 not contain 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 not have continuous states.

The model, sink_examp, contains an atomic subsystem, theSink.

The Sine Wave block provides input to the subsystem, theSink.

The subsystem theSink applies a gain and an offset to its input signal and displays it on a Scope block.

The Scope block displays the simulation output signal.

If theSink is declared as a Signal Viewing Subsystem, the generated target application includes only the code for the Sine Wave block. If theSink is selected and armed in the External Signal & Triggering dialog box, the target application uploads the sine wave signal to theSink during simulation. You can then modify the parameters of the blocks within theSink and observe the uploaded signal.

If theSink were not declared as a Signal Viewing Subsystem, its Gain, Constant, and Sum blocks would run as subsystem code on the target system. The Sine Wave signal would be uploaded to the Simulink engine after being processed by these blocks, and viewed on sink_examp/theSink/Scope2. Processing demands on the target system would be increased by the additional signal processing, and by the downloading of changes in block parameters from the host.

Supported Blocks for Data Archiving

In external mode, you can use the following types of blocks to archive data to disk:

  • Scope blocks

  • To Workspace blocks

You configure data archiving by using the Enable Data Archiving dialog box, as described in Configure Host Archiving of Target Application Signal Data.

Use External Mode Programmatically

You can run external mode simulations 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.

The following model simulation commands assume that a Simulink model is open and that you have loaded a target application 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 application:

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

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

    set_param(gcs,'SimulationCommand','stop')
  5. Disconnect the target application from the model:

    set_param(gcs,'SimulationCommand','disconnect')

To tune a workspace parameter, change its value at the command prompt. If the workspace parameter is a Simulink.Parameter object, assign the new value to the Value property.

myVariable = 5.23;
myParamObj.Value = 5.23;

To download the workspace parameter in external mode, you update the model diagram. The following model simulation command initiates a model update:

set_param(gcs,'SimulationCommand','update')

To trigger or cancel data uploading to scopes, use the ExtModeCommand values armFloating and cancelFloating, or armWired and cancelWired. For example, to trigger and then cancel data uploading to wired (nonfloating) scopes:

set_param(gcs,'ExtModeCommand','armWired')
set_param(gcs,'ExtModeCommand','cancelWired')

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. For external mode parameters that are equivalent to Interface pane options in the Configuration Parameters dialog box, see Model Configuration Parameters: Code Generation Interface.

External Mode Command-Line Parameters

Parameter and ValuesDialog Box EquivalentDescription
ExtModeAddSuffixToVar
off, on
Enable Data Archiving: Append file suffix to variable names check boxIncrement variable names for each incremented filename.
ExtModeArchiveDirName
character vector
Enable Data Archiving: Directory text fieldSave data in specified folder.
ExtModeArchiveFileName
character vector
Enable Data Archiving: File text fieldSave data in specified file.
ExtModeArchiveMode
character vector - off, auto, manual
Enable Data Archiving: Enable archiving check box

Activate automated data archiving features.

To specify manual, run set_param(gcs, 'ExtModeArchiveMode', 'manual').

Note that if you specify auto, ExtModeAutoIncOneShot is set to on.

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
Enable Data Archiving: Increment file after one-shot check boxSave new data buffers in incremental files.
ExtModeAutoUpdateStatusClock, for Windows® 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 parameters remain in the queue of parameters to be downloaded to the target.
ExtModeCommand
character vector - armFloating, armWired, cancelFloating, cancelWired
  • armFloating and cancelFloating are equivalent to selecting and clearing External Mode Control Panel check box Floating scope > Enable data uploading

  • armWired and cancelWired are equivalent to External Mode Control Panel buttons Arm Trigger and Cancel Trigger

Issue an external mode command to the target application.
ExtModeConnected
off, on
External Mode Control Panel: Connect/Disconnect buttonIndicate the state of the connection with the target application.
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
Enable 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 available signals from the target to the host.
ExtModeParamChangesPending
off, on
Not availableWhen the Simulink Coder software is connected to the target and ExtModeBatchMode is enabled, indicates whether 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 application without downloading parameters.
ExtModeTrigDelay
integer (0)
External Signal & Triggering: Delay text fieldSpecify the amount of time (expressed in base rate steps) that elapses between a trigger occurrence and the start of data collection.
ExtModeTrigDirection
character vector - 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
character vector - 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
character vector - 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
character vector - 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
character vector - 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
character vector - 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
character vector - inactive, armed, uploading
Not availableReturn the status of the external mode upload mechanism — inactive, armed, or uploading.
ExtModeWriteAllDataToWs
off, on
Enable Data Archiving: Write intermediate results to workspace check boxWrite intermediate results to the workspace.

Animate Stateflow Charts in External Mode

If you have Stateflow®, you can animate a chart in external mode. In external mode, you can animate states in a chart, and view test point signals in a floating scope or signal viewer.

Animate States During Simulation in External Mode

To animate states in a chart in external mode:

  1. Load the chart you want to animate to the target machine.

  2. In the Configuration Parameters dialog box, select the External mode check box.

  3. Open the External Mode Control Panel dialog box.

  4. Click Signal & Triggering.

  5. In the External Signal & Triggering dialog box, set these parameters.

    In:Select:
    Signal selection paneChart you want to animate
    Trigger options paneArm when connecting to target check box
    Trigger options panenormal from drop-down menu in Mode field
  6. Build the model to generate an executable file.

  7. Deploy the target application.

  8. Connect Simulink to the target application.

  9. Start execution of the generated model code. The chart highlights states as they execute.

View Test Point Data in Floating Scopes and Signal Viewers

When you simulate a chart in external mode, you can designate chart data of local scope to be test points and view the test point data in floating scopes and signal viewers.

To view test point data during simulation in external mode:

  1. Open the Model Explorer and for each data you want to view, follow these steps:

    1. In the middle Contents pane, select the state or local data of interest.

    2. In the right Dialog pane, select the Logging tab and select Test point check box.

  2. From a floating scope or signal viewer, click the signal selection button.

    The Signal Selector dialog box opens.

  3. In the Signal Selector Model hierarchy pane, select the chart.

  4. In the Signal Selector List contents menu, select Testpointed/Logged signals only and then select the signals you want to view.

  5. Simulate the model in external mode as described in Animate States During Simulation in External Mode.

    The scope or viewer displays the values of the test point signals as the simulation runs.

For more information, see Behavior of Scopes and Viewers with Rapid Accelerator Mode.

TCP/IP and Serial External Mode Limitations

FeatureDetails
Changing parameters

In general, you cannot change a parameter if doing so results in a change in the structure of the model. For example, you cannot change

  • The number of states, inputs, or outputs of a block

  • The sample time or the number of sample times

  • The integration algorithm for continuous systems

  • The name of the model or of a block

If you make these changes to the block diagram, then you must rebuild the program with newly generated code.

You can change parameters in transfer function and state space representation blocks in specific ways:

  • The parameters (numerator and denominator polynomials) for the Transfer Fcn (continuous and discrete) and Discrete Filter blocks can be changed (as long as the number of states does not change).

  • Zero entries in the State-Space and Zero Pole (both continuous and discrete) blocks in the user-specified or computed parameters (that is, the A, B, C, and D matrices obtained by a zero-pole to state-space transformation) cannot be changed once external simulation is started.

  • In the State-Space block, if you specify the matrices in the controllable canonical realization, then all changes to the A, B, C, D matrices that preserve this realization and the dimensions of the matrices are allowed.

If the Simulink block diagram does not match the external program, Simulink produces an error stating that the checksums do not match. The checksums take into account the top models, but not referenced models. Use the updated block diagram to rebuild the target application.

Uploading data

Uploading of data values for fixed-point or enumerated types to workspace parameters is not supported.

Signal value display in simulation

Graphical display of signal values in models (described in Display Signal Values in Model Diagrams) is not supported. For example, you cannot use the Data Display in Simulation menu selections Show Value Labels When Hovering, Toggle Value Labels When Clicked, and Show Value Label of Selected Port.

Tunable structure parameters

Uploading or downloading of tunable structure parameters is not supported.

Pure integer code

Pure integer code is supported.

If you do not specify -tf finalTime in the execution command, the target application runs the generated model code indefinitely, ignoring StopTime.

If you specify -tf finalTime in the execution command:

  • The finalTime value represents base rate clock ticks, not seconds.

  • The maximum value for finalTime, in ticks, is MAX_int32_T.

  • When the 16-bit or 32-bit tick counter overflows, the simulation time in Scope blocks returns to zero.

Archiving data

For archiving data to disk, Scope and To Workspace blocks are supported. However, other scopes are not supported for data archiving. For example, you cannot use Floating Scope blocks or Viewers and Generators Manager viewer objects to archive data.

Scopes in referenced models

In a model hierarchy, if the top model simulates in external mode and a referenced model simulates in normal or accelerator mode, scopes in the referenced model are not displayed.

However, if the top model is changed to simulate in normal mode, the behavior of scopes in the referenced models differs between normal and accelerator mode. Scopes in a referenced model simulating in normal mode are displayed, while scopes in a referenced model simulating in accelerator mode are not displayed.

Simulation start time

Nonzero simulation start times are not supported. In the Configuration Parameters dialog box, Solver pane, leave Start time set to the default value of 0.0.

File-scoped data

File-scoped data are not supported, for example, data items to which you apply the built-in custom storage class, FileScope. File-scoped data are not externally accessible.

Signals with custom storage classes

Uploading of signals with custom storage classes (CSC) is not supported.

Use of printf Statements

To show target application error and information messages on the target hardware display, you can use printf calls. For some target hardware, the use of printf statements can increase the external mode binary file size. To disable printf calls, specify the preprocessor macro definition EXTMODE_DISABLEPRINTF for your target application compiler.

Command-line arguments

You can use command-line arguments for running target applications. These limitations apply:

  • Parsing of the command-line arguments requires the sscanf function, which increases the program size for some target hardware.

  • Some target applications do not accept command-line arguments.

If your target hardware does not support the parsing of command-line arguments, specify the preprocessor macro definition EXTMODE_DISABLE_ARGS_PROCESSING=1 for your target application compiler.

To replace the -w option, you can use this command to specify that the target application enters and stays in a wait state until it receives a Connect message from Simulink:

set_param(modelName, 'OnTargetWaitForStart', 'on');
The build process provides the required option (-DON_TARGET_WAIT_FOR_START=1) to the compiler.

Row-major code generation

Code generated with the row-major format is not supported.

Related Topics