Main Content

External Mode Simulation by Using XCP Communication

In an external mode simulation, you can tune parameters in real time and monitor target application signals. Using the Run on Custom Hardware app, you can set up and run on your development computer or custom hardware external mode simulations that use an XCP communication channel.

For an external mode simulation, you:

  1. Build the target application on your development computer.

  2. Deploy the target application to the target hardware.

  3. Connect Simulink® to the target application that runs on the target hardware.

  4. Start execution of generated code on the target hardware.

Run XCP External Mode Simulation on Development Computer

Configure and run an external mode simulation that uses the XCP communication protocol. During the simulation:

  • Monitor a signal by using a Scope block, a Dashboard block, and the Simulation Data Inspector.

  • Tune a parameter by using a Dashboard block.

Configure Signal Monitoring and Parameter Tuning for XCP

  1. Create a folder for this example.

    mkdir ext_mode_xcp_example
    cd ext_mode_xcp_example

  2. Open Simulink and create a simple model, xcpExample, which contains these blocks:

    • Sine Wave

    • Gain

    • Scope

    • Half Gauge

    • Knob

  3. Double-click the Sine Wave block. Set Sample time to 0.1, and then click OK.

  4. Double-click the Gain block. Set Gain to 2, and then click OK.

  5. Connect the Sine Wave block to the Gain block and name the connection, for example, Test Signal.

  6. Connect the Gain block to the Scope block and name the connection, for example, Output Signal.

  7. Configure Test Signal for logging:

    1. Select Test Signal.

    2. On the Signal tab, in the Monitor section, select Log Signals.

    If you do not enable signal logging, you cannot stream Test Signal to the Simulation Data Inspector.

  8. Configure the Half Gauge block to monitor the value of Test Signal:

    1. Double-click the Half Gauge block.

    2. In the Simulink Editor, select Test Signal.

    3. In the Block Parameters dialog box:

      • Connect the block to Test Signal.

      • In the Maximum field, enter a value, for example, 1.

    4. Click OK.

  9. Configure the Knob block to tune the Amplitude parameter of the Sine Wave block:

    1. Double-click the Knob block.

    2. In the Simulink Editor, select the Sine Wave block.

    3. In the Block Parameters dialog box:

      • Connect the block to the Amplitude parameter of the Sine Wave block.

      • In the Minimum and Maximum fields, enter values, for example, 0.1 and 1 respectively.

    4. Click OK.

  10. Save the model as xcpExample.

Specify Hardware and Prepare Model

  1. From the Apps tab on the Simulink toolstrip, in the Setup to Run on Hardware section, click Run on Custom Hardware. On the Run on Custom Hardware pop-up dialog box, click Finish.

  2. In the Hardware section, specify the system target file. For this example, use the default, grt.tlc. If you have Embedded Coder®, you can specify ert.tlc.

  3. In the Prepare gallery, under Model Configuration, 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, specify Fixed-step.

    2. Under Solver details, in the Fixed-step size field, specify a value, for example, 0.1.

  5. On the Code Generation > Optimization pane, set Default parameter behavior to Tunable.

  6. On the Code Generation > Interface pane, select the External mode check box.

  7. Set Transport layer to XCP on TCP/IP, which specifies ext_xcp for MEX-file name.

  8. You cannot disable the Static memory allocation check box. The Static memory buffer size value specifies the size of XCP slave memory that is allocated for signal logging. For this example, use the default value.

  9. If System target file is ert.tlc, on the Code Generation > Templates pane:

    • Select the Generate an example main program check box.

    • Set Target operating system to BareBoardExample.

      Using the documented APIs of the external mode abstraction layer that are available in matlabroot\toolbox\coder\xcp\src\target\ext_mode\include\ext_mode.h, the code generator creates an example that shows how you can provide XCP external mode target connectivity for a bare board that does not run an operating system.

  10. Click OK. Then save the model.

Build and Run Target Application

In the Run on Hardware section:

  1. To specify a nondefault value for the simulation stop time, in the Stop Time field, specify your value, for example, inf.

  2. Click . The software:

    1. Builds the target application:

      • In Windows®, the build process creates:

        • xcpExample.exe –– The executable file.

        • xcpExample.pdb –– A debugging symbols file for signals and parameters.

      • In Linux®, the build process places DWARF format debugging information in the created ELF executable file, xcpExample.

    2. Runs the target application as separate process on your development computer.

    3. Connects Simulink to the target application.

    4. Runs the generated model code.

    To perform the steps separately, click Monitor & Tune. Under Step By Step Commands, click:

    1. Build for Monitoring

    2. Deploy

    3. Connect

    4. Start

Monitor Signal and Tune Parameter

You can monitor Test Signal through the:

  • Scope block –– Double-click the block.

  • Simulation Data Inspector –– Click the Simulation Data Inspector button. When the Simulation Data Inspector opens, select the Test Signal check box, which displays streamed data.

  • Half-Gauge block.

To change the amplitude of the sine wave, rotate the pointer on the Knob block to the required value.

This table describes more ways of tuning tunable block parameters during a simulation.

ApproachDetails

Model Data Editor

To tune parameters through the Model Data Editor:

  1. On the Hardware tab of the Simulink Editor, in the Prepare section, click Tune Parameters, which opens the Model Data Editor.

  2. If you want to update multiple tunable parameters simultaneously, in the Prepare section, toggle on Hold Updates.

  3. On the Parameters tab of the Model Data Editor, in the Value column, specify new values for your tunable parameters.

  4. Toggle off Hold Updates or click Update All Parameters (Ctrl+D). Simulink downloads the new values to the target application simultaneously.

    If Hold Updates is off, then immediately after you specify a new value, Simulink downloads the new value to the target application.

For more information, see Model Data Editor.

Block Parameter dialog box

To tune parameters through the Block Parameter dialog box:

  1. For each block that you want to update:

    1. Double-click the block, which opens the Block Parameter dialog box.

    2. In the parameter fields, specify new parameter values.

    3. Click Apply or OK.

  2. If Hold Updates is on, toggle off Hold Updates or click Update All Parameters (Ctrl+D). Simulink downloads the new values to the target application simultaneously.

    If Hold Updates is off, then immediately after you click Apply or OK, Simulink downloads the new block values to the target application.

MATLAB® workspace

If block parameters are MATLAB workspace variables:

  1. In the Command Window, assign new values to the variables.

  2. On the Hardware tab of the Simulink Editor, in the Prepare section, click Update All Parameters (Ctrl+D). Simulink downloads the new values to the target application.

For more information, see Create and Edit Variables.

For more information about parameter tuning with generated code, see External Mode Simulation with TCP/IP or Serial Communication and Create Tunable Calibration Parameter in the Generated Code (Embedded Coder).

If your model contains a Stateflow® chart, you can view state activity. For more information, see Animate Stateflow Charts (Stateflow).

Stop Target Application

To stop the execution of generated model code before StopTime is reached and disconnect the target application, on the Simulink Editor toolbar, click the Stop button .

If you want to disconnect the target application from Simulink without stopping code execution, click . Then, under Step By Step Commands, click Disconnect.

Triggered Signal Monitoring for XCP External Mode Simulations

For XCP external mode simulations, you can configure a trigger that starts the uploading of target application data for signal monitoring in Simulink.

  1.  Create a simple model in a local folder.

  2. In the Simulink Editor, configure these signals for logging by right-clicking each signal and then selecting Log Selected Signals:

    • test_signal

    • test_carrier

    • test_output

    • cmp_output

  3. From the Apps tab on the Simulink toolstrip, in the Setup to Run on Hardware section, click Run on Custom Hardware. On the Run on Custom Hardware pop-up dialog box, click Finish.

  4. In the Prepare gallery, under Model Configuration, click Hardware Settings.

  5. On the Solver pane, in the Type field, specify Fixed-step.

  6. On the Code Generation > Interface pane, select the External mode check box.

  7. Set Transport layer to XCP on TCP/IP, which specifies ext_xcp for MEX-file name.

  8. Click OK. Then save the model.

  9. To open the External Signal & Triggering dialog box, from the Prepare gallery, under Signal Monitoring & Tracing, click Control Panel.

  10. In the Configuration section, click Signal & Triggering, which opens the External Signal & Triggering dialog box.

    Through this dialog box, you can select signals for monitoring and configure the trigger for uploading data from the target application. For this example, use the default settings. For example:

    • The Select all check box is selected — The dialog box displays an X in each row of the Selected column. You can monitor all logged signals during the simulation.

    • Source is set to manual –– The External Mode Control Panel provides manual control of data uploading, for example, the Arm Trigger button.

    • The Arm when connecting to target check box is selected — When you connect Simulink to the target application, the trigger is armed.

  11. Click OK.

  12. From the Hardware tab in the Simulink Editor, in the Run on Hardware section:

    1. In the Stop Time field, specify your value, for example, inf.

    2. Save the model.

    3. Click . The software:

      1. Builds the target application:

      2. Runs the target application as separate process on your development computer.

      3. Connects Simulink to the target application.

      4. Runs the generated model code.

To view the scope displays, double-click ScopeA and ScopeB.

To monitor signals in the Simulation Data Inspector, in the Review Results section, click the Data Inspector button.

From the External Mode Control Panel, you can suspend or resume signal logging and monitoring. In the Connection and triggering section, click Cancel Trigger or Arm Trigger respectively.

To stop the execution of the target application and disconnect Simulink from the target environment, click Stop Real-Time Code.

For information about signal monitoring and trigger options, see XCP External Mode Control Panel and XCP External Signal & Triggering Dialog Box.

Run XCP External Mode Simulation From Command Line

You can use commands to run XCP external mode simulations. To retrieve and set the values of model parameters, use the get_param and set_param commands.

To run these commands, you must have a Simulink model open and a target application running.

  1. Set the model simulation mode to external mode.

    set_param(gcs,'SimulationMode','external');

  2. Connect Simulink to the target application.

    set_param(gcs,'SimulationCommand','connect')

  3. Run generated model code.

    set_param(gcs,'SimulationCommand','start');

  4. To tune a parameter, change its workspace variable value through a line command. For example, if a block parameter value is specified as a Simulink.Parameter object, assign the new value to the Value property.

    myParamObj.Value = 5.23;

  5. To download the new value to the target application, update the model.

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

  6. Stop the target application and disconnect Simulink from the target environment.

    set_param(gcs,'SimulationCommand','stop');

    To disconnect Simulink from the target application without stopping execution of generated code, use this command:

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

The set_param commands that use the 'SimulationCommand' argument are asynchronous. If you run the commands successively from a script, each command starts without waiting for the previous command to complete. To check that each command is complete, in the script, use the get_param command with the 'SimulationStatus' argument. For example, for steps 1 to 3, specify these commands in the script:

set_param(gcs,'SimulationMode','external');
set_param(gcs,'SimulationCommand','connect');

isExternalSimulationActive = false;
while ~isExternalSimulationActive
    simStatus = get_param(gcs, 'SimulationStatus');
    isExternalSimulationActive = strcmp(simStatus, 'external');
end
set_param(gcs,'SimulationCommand','start');

For more information, see Run Simulations Programmatically.

The Diagnostic Viewer displays error messages produced by the get_param and set_param commands.

Target Application Arguments

You can run your target application with optional arguments. You can pass the optional arguments to your target application through your custom launcher implementation.

ArgumentDescription
-w

Specify that the target application enters and stays in a wait state until it receives a message from Simulink.

If you do not specify -w, the target application executes model code immediately. The model code runs with parameter values from the time when you built the model.

-tf time

Override the model parameter StopTime.

Specify time in:

  • Seconds if PurelyIntegerCode is set to 'off'.

  • Base rate steps if PurelyIntegerCode is set to 'on'.

-tf inf specifies that the model runs indefinitely when model code is executed.

For host-based external mode simulations, you can specify additional rtiostream (Embedded Coder) arguments.

ArgumentDescription

-verbose level

Specify verbosity level:

  • 0 –– No information

  • 1 –– Detailed information

-port number

For XCP on TCP/IP transport layer, specify the port number of the TCP/IP server. Use an integer value between 256 and 65535. Default is 17725.

For XCP on Serial transport layer, specify the serial port ID. For example:

On Windows, 'COM1' or 1 for COM1, 'COM2' or 2 for COM2, and so on.

On Linux, '/dev/ttyS0', and so on.

-baud value

For XCP on Serial transport layer, specify the baud value: 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600 (default), or 115200.

XCP External Mode Limitations

This table describes limitations that apply to external mode simulations that use XCP communication.

FeatureDetails

Parameter updates that change model structure

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 parameter updates that change the model structure, you must rebuild the target application.

You can change numerator and denominator polynomial parameters for the Transfer Fcn, Discrete Transfer Fcn, and Discrete Filter blocks if the number of states does not change.

You cannot change zero entries in the State-Space, Zero-Pole, and Discrete Zero-Pole 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.

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

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

Signal value display

The graphical display of signal values during a simulation is not supported. For example, you cannot use the Data Display in Simulation menu items Show Value Labels When Hovering, Toggle Value Labels When Clicked, and Show Value Label of Selected Port. For more information, see Display Signal Values in Model Diagrams.

Data archiving

Data Archiving features available on the External Mode Control Panel are not supported. You can use the Simulation Data Inspector to collect and export data.

Overriding signal logging settings

If you use the Signal Logging Selector to override signal logging settings, the controls to override the Decimation and Limit data points settings are not supported.

Subsystem signal logging

For external mode simulations, signal logging occurs in response to an event on the target hardware. Currently, the only supported logging event is a new sample time tick. Some subsystems are enabled or disabled by control signals. For these subsystems, the software logs signal values even when the control signals for the subsystems are not enabled.

For example, if signals in an Enabled Subsystem block are configured for logging, the software logs the signal values even when the control signal for the subsystem is not greater than zero. In this case, the logged values are the values the signals had when the control signal was last greater than zero.

For more information about the subsystems for which this limitation applies, see Simulink Subsystem Semantics.

Compiler debug symbol format

Your toolchain must generate debug information in one of these formats:

  • DWARF

  • PDB

Global variables

Signals, parameters, and states must be specified as global variables. The target memory locations where the variables are stored must lie in the range 0 – 4294967295.

Parameter structures

You cannot tune parameters that are structures.

Pure integer code

Pure integer code is supported. For code generation, if PurelyIntegerCode is 'on', specify FixedStep with a resolution that is greater or equal to 1 microsecond. For example, specify 1.000001, but not 1.0000001.

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 steps, not seconds.

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

Variable-size signals

Uploading of variable-size signals is not supported.

Compiler support

lcc-win64 is not supported.

Address granularity

Target hardware that uses word addresses is not supported.

Portable word sizes

When the production target hardware is word-addressable, the generation of a host-based target application by using portable word sizes is not supported. The production target hardware must support 8-bit, 16-bit, and 32-bit native data types.

Scope and Floating Scope blocks, and Scope Viewer

Some signal data types are not supported. The simulation produces a warning.

Floating Scope blocks and Scope ViewerYou cannot use Floating Scope blocks and Scope Viewers to monitor signals in referenced models during external mode simulations. To monitor referenced model signals, enable signal logging and use the Simulation Data Inspector.

Scopes in referenced models

In a model hierarchy, if the top model runs in external mode, scopes in the referenced models are not displayed. To monitor signals within a referenced model, enable signal logging and use the Simulation Data Inspector.

Nonzero simulation start time

Nonzero simulation start times are not supported. Use the default value for Solver > Start time, 0.0.

Intermediate step values

Some Simulink blocks can generate multiple values in a simulation time step. For example:

For each time step in an external mode simulation, Simulink uploads from the target application only the final values of such blocks. Simulink does not upload the intermediate values generated during the step.

File-scoped data

File-scoped data is not supported. For example, data items to which you apply the built-in custom storage class FileScope. The simulation produces a warning.

For more information about the FileScope storage class, see Choose Storage Class for Controlling Data Representation in Generated Code (Embedded Coder).

Row-major code generation

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

Concurrent execution

On Windows and Linux computers, concurrent execution is supported.

On Mac computers, concurrent execution using the native threads example is not supported. If the External mode and Allow tasks to execute concurrently on target check boxes are selected, you cannot build the target application unless you are using a target hardware support package that supports concurrent execution for external mode simulations.

On a Windows computer, at run time, the base sample time in the target application is quantized to the nearest multiple of the system timer interrupt interval (usually 15.625 ms). Sampling subrates are the expected multiples of the base sample rate. Logged timestamps in the Simulation Data Inspector (SDI) correspond to simulation times rather than wall-clock times. As an example, this table shows the step times for a Simulink model that has a base sample time of 10 ms and a subrate sample time of 20 ms.

Base RateSubrate
Step Wall-Clock Time (ms) Logged Timestamp (ms)StepWall-Clock Time (ms)Logged Timestamp (ms)
000000
1 15.625 10   
2 31.250 20 1 31.250 20
3 46.875 30   
4 62.500 40 2 62.500 40

VxWorks® example

If System target file is ert.tlc and Target operating system is VxWorksExample, you cannot build the target application.

Saving simulation output as a single objectSaving the XCP external mode simulation output as a single object is not supported. The simulation produces a warning.
Structure packing and alignmentFor packing and alignment of C structures, your compiler must support the #pragma pack preprocessor directive. Otherwise, the target application might produce undefined behavior.

Related Topics

External Websites