If you have a license for HDL Coder™, you can generate HDL code from your Simscape™ model for deployment onto FPGA platforms using the Simscape HDL Workflow Advisor. The Simscape HDL Workflow Advisor first helps you to convert your Simscape model to a Simulink^{®} implementation. It then converts the Simulink model to HDL code using HDL Coder. Converting your Simscape model to HDL code allows you to:

Accelerate the simulation of physical systems by using an optimized implementation of Simscape models

Use the reconfigurability and parallelism capabilities of the FPGA for rapid prototyping

Simulate the HDL implementation in real time using hardware-in-the-loop (HIL) simulation

The general workflow for converting a Simscape model to HDL code using the Simscape HDL Workflow Advisor consists of these steps.

Generate baseline results for your Simscape model.

Ensure that the model contains only linear or switched linear blocks by using the

`simscape.findNonLinearBlocks`

function. This function detects the nonlinear blocks in your Simscape model. The function returns the number and type of networks, that is, linear, switched linear, or nonlinear, based on the blocks that the network contains. The function also returns the names of any blocks that yield nonlinear equations. Update or replace any blocks that yield nonlinear equations.Ensure that simulation results of the model, which now contains no blocks that yield nonlinear equations, match the baseline results.

Configure the Simscape network for real-time simulation and HDL code generation:

Add blocks that allow you to monitor the progress of the HDL workflow in terms of simulation time.

Display sample time information.

Configure the Simscape network for fixed-step, fixed cost simulation.

Ensure that simulation results of the discrete model match the baseline results.

Run the Simscape HDL Workflow Advisor tasks by using the

`sschdladvisor`

function. The`sschdladvisor`

function:Checks for HDL code generation compatibility by ensuring that the model is switched linear and is configured for real-time simulation.

Extracts state-space coefficients for the Simscape network.

Generates an HDL code generation compatible implementation of the Simscape network.

Ensure that simulation results from the HDL code generation compatible implementation match the baseline results.

Generate HDL code:

Configure the Simulink model for HDL code generation by running the

`hdlsetup`

function. The`hdlsetup`

function configures the fixed-step solver for HDL code generation compatibility and specifies the simulation start and stop times.Save the model parameters and validation model generation settings.

Generate code using the

`makehdl`

function.

The Simscape HDL Workflow Advisor does not work for Simscape networks that contain:

Events.

Mode charts.

Delays.

Enabled runtime parameters.

Periodic sources.

Nonlinearities that result from network connectivity. If your model does contain a nonlinearity of this sort, the

`sschdladvisor`

function may run all tasks to completion, but generates a zero-value output.

This example shows how to convert your Simscape model to HDL code using the Simscape HDL Workflow Advisor. To learn how to configure your Simscape network and Simulink model for real-time simulation and HDL code generation, see Model Preparation. To open a version of the model that is already prepared for using the Simscape HDL Workflow Advisor, see Generate HDL Code by Using the Simscape HDL Workflow Advisor.

To prepare your Simscape model for conversion to HDL code for FPGA deployment:

Open the model and show hidden block names. At the MATLAB

^{®}command prompt, enterbaselineModel = 'ssc_bridge_rectifier'; load_system(baselineModel) set_param(baselineModel,'HideAutomaticNames','off') open_system(baselineModel)

To compare the baseline simulation results to results from modified versions of the model later, remove the data point limitation on the

**Load Voltage**scope block and enable data logging to the Simulation Data Inspector for the signal that inputs data to the scope.In the configuration parameters for the scope, for the

**Logging**parameters, clear the option to limit data points.Right-click the connection line to the

**Load Voltage**scope block and select`Log selected signals`

.

The logging badge marks the signal in the model.

Simulate the model and view the results in the Simulation Data Inspector.

%% Simulate baseline model sim(baselineModel) %% Get Simulation Data Inspector run IDs for runIDs = Simulink.sdi.getAllRunIDs; runID = runIDs(end); run = Simulink.sdi.getRun(runID); signal1 = run.getSignalByIndex(1); % run.signalCount signal1.checked = true; Simulink.sdi.view

As needed, press the spacebar on your keyboard to fit the Simulation Data Inspector plot to view.

The baseline simulation results are as expected for the full-wave bridge rectifier load voltage.

The Simscape HDL Workflow Advisor cannot convert nonlinear networks to HDL Code. Before running the advisor, identify and replace blocks that cause your network to be nonlinear. To identify the blocks, use the

`simcape.findNonlearBlocks`

function.simscape.findNonlinearBlocks(baselineModel)

Found network that contains nonlinear equations in the following blocks: 'ssc_bridge_rectifier/AC Voltage Source' The number of linear or switched linear networks in the model is 0. The number of nonlinear networks in the model is 1. ans = 1×1 cell array {'ssc_bridge_rectifier/AC Voltage Source'}

The model contains an AC Voltage Source block, a periodic source that yields nonlinear equations.

You can replace the Simscape periodic source by adding a Simscape Controlled Voltage Source block in the Simscape network with a Simulink Sine Wave block outside the network. An added benefit is that you can configure the frequency and amplitude for the Sine Wave block at run time during real-time simulation.

Delete the AC Voltage Source block.

Add a Sine Wave block from the Simulink Sources library.

Add a Simulink-PS Converter block from the Simscape Utilities library.

Add a Controlled Voltage Source block from the Simscape / Foundation Library / Electrical / Electrical Sources library.

Connect the Sine Wave block to the Simulink-PS Converter block and the Simulink-PS Converter block to the Controlled Voltage Source block.

The Simulink model is configured for variable-step simulation. If you specify the Sine Wave block sample time as

`-1`

, for inheriting the sample time, the simulation generates a warning. Instead, specify the sample time for the Sine Wave as`0`

by using a workspace variable that you can later adjust for improving simulation speed or accuracy. The removed AC Voltage Source block has a**Peak amplitude**of`sqrt(2)*120`

`V`

and a**Frequency**of`60`

`Hz`

.Configure the Sine Wave block.

Define the sample time in the workspace.

Ts = 1e-5;

Set the

**Amplitude**parameter to`sqrt(2)*120`

.Set the

**Frequency (rad/sec)**parameter to`60*2*pi`

.Set the

**Sample time**parameter to`Ts`

.

Ensure that there are no blocks that cause your network to be nonlinear.

% Simulate sim(baselineModel) % Check for nonlinear blocks simscape.findNonlinearBlocks(baselineModel)

The number of linear or switched linear networks in the model is 1. ans = 0×0 empty cell array

The model contains only blocks that yield linear or switched linear equations.

Simulate the model and compare the results to the baseline results in the Simulation Data Inspector.

% Get Simulation Data Inspector run IDs runIDs = Simulink.sdi.getAllRunIDs; runBaseline = runIDs(end - 1); runSwitchedLinear = runIDs(end); % Open the Simulation Data Inspector Simulink.sdi.view compBaseline1 = Simulink.sdi.compareRuns(runBaseline,... runSwitchedLinear);

The results are similar to the baseline results.

To examine the progress of the Simscape HDL Workflow Advisor later, add and connect a Digital Clock block from the Simulink Sources library and a Display block from the Simulink / Sinks library, as shown in the figure. For the Digital Clock, specify

`Ts`

for**Sample time**parameter.The model is currently simulating in continuous time using a variable-step solver. For real time-simulation, a fixed-step solver is required for discrete-time simulation. Sample time colors and annotations help you to determine if your model contains any continuous settings. To turn on sample time colors and annotations, in the Simulink model window, on the

**Debug**tab, under**Information Overlays**, in the**Sample Time**group, select**Colors**and**Text**.The model diagram updates and the Sample Time Legend displays.

Configure the model for real-time simulation.

Configure the Simulink model for fixed-step, fixed-cost simulation. In the Model Configuration Parameters, for the

**Solver**parameters, set:Set

**Type**to`Fixed-step`

.Set

**Solver**to`discrete (no continuous states)`

.

Configure the Simscape network for fixed-step, fixed-cost simulation. For the Solver Configuration block:

Select

**Use local solver**.Ensure that

**Solver type**is set to`Backward Euler`

.Specify

`Ts`

for the**Sample time**.

Simulate the model and compare the results to the baseline results in the Simulation Data Inspector.

% Simulate sim(baselineModel) % Get Simulation Data Inspector run IDs runIDs = Simulink.sdi.getAllRunIDs; runBaseline = runIDs(end - 2); runRealTime = runIDs(end); % Open the Simulation Data Inspector Simulink.sdi.view compBaseline1 = Simulink.sdi.compareRuns(runBaseline,... runRealTime);

The results are similar to the baseline results.

Generate HDL code by running the Simscape HDL Workflow Advisor either on the Simscape model that you prepared by stepping through Model Preparation or on a Simscape model that is already prepared for code generation.

Rename the model.

To continue working with the model that you prepared for HDL code generation, rename the model

`ssc_model`

.To open and use a model that is already prepared for HDL code generation, at the MATLAB command prompt, enter

`open_system('ssc_bridge_rectifier_hdl')`

Save the model to a local directory as

`ssc_model`

.

Run the Simscape HDL Workflow Advisor.

`sschdladvisor('ssc_model')`

The Simscape HDL Workflow Advisor opens.

Run the code generation compatibility checks.

Select

**Code generation compatibility**>**Check solver configuration**and then click**Run this task**.Select

**Check switched linear**and then click**Run this task**.

The advisor reports when your model has passed each of these checks.

Extract the state-space coefficients. Select

**State-space conversion**>**Get state-space parameters**and then click**Run this task**. The conversion can take some time. The Display block in the model window shows the elapsed simulation time.After running the task, the advisor displays a summary of the state-space representation and a table of parameters.

Number of states: 5

Number of inputs: 1

Number of outputs: 1

Number of modes: 7

Discrete sample time: 1e-05

**Parameter****Parameter size**A 5 x 5 x 7 B 5 x 1 x 7 F0 5 x 1 x 7 C 1 x 5 x 7 D 1 x 1 x 7 Y0 1 x 1 x 7 The size of the state, mode, and parameter data helps you estimate how much of the FPGA resources are required to deploy the model. The higher the values, the more FPGA resources are required. The input and output data indicate the number and type of I/O connections needed for real-time deployment and visualization.

Generate an HDL implementation of your model. Select

**Implementation model generation**>**Generate implementation model**and then click**Run this task**.When the implementation model is generated, the advisor reports that the task is passed and displays a link to the generated implementation model, which is named

**gmStateSpaceHDL_ssc_model**.Open the generated implementation model by clicking the provided link.

The model contains blocks labeled:

**Subsystem**— Simulink subsystem that contains the prepared model and any signal routing that the Simscape HDL Workflow Advisor adds. For this model, the advisor adds a Goto block that routes the**Sine Wave**block input to the**HDL Subsystem**.**T**— From block that routes the**Sine Wave**block input from the**Subsystem**block to the**HDL Subsystem**block.**Rate Transition1**— Handles the transfer of data between blocks operating at different rates.**Data Type Conversion1**— Converts double data types to single data types, as is required for HDL code generation.**HDL Subsystem**—Simulink subsystem that contains an HDL code generation compatible version of your Simscape network. For this model, the advisor adds a Goto block that routes the**Sine Wave**block input to the**HDL Subsystem**block.**Scope**— Displays the load voltage.

Prepare the

**HDL Subsystem**for a simulation comparison to the baseline results:Delete the

**T**From block.Copy and paste the

**Sine Wave**block from the**Subsystem**block into the top-level model.Connect the

**Sine Wave**block to the**Rate Transition1**block.Delete the

**Subsystem**block, which contains the baseline model.Enable data logging to the Simulation Data Inspector for the signal that goes to the

**Scope**block.

To ensure that the HDL subsystem corresponds to your original Simscape model, simulate the model and compare the results to the baseline simulation results.

% Simulate sim('gmStateSpaceHDL_ssc_model') % Get Simulation Data Inspector run IDs runIDs = Simulink.sdi.getAllRunIDs; runBaseline = runIDs(end - 3); runHDLImplementation = runIDs(end); % Open the Simulation Data Inspector Simulink.sdi.view compBaseline1 = Simulink.sdi.compareRuns(runBaseline,... runHDLImplementation);

The results are similar to the baseline results. Your Simscape model is now converted to an HDL code generation compatible implementation.

Generate HDL code from the implementation:

In the model configuration parameters, for

**HDL Code Generation****Report**, select the**Generate traceability report**and the**Generate resource utilization report**options.Run the

`hdlsetup`

function.`hdlsetup('gmStateSpaceHDL_ssc_model')`

Save the model and subsystem parameter settings.

`hdlsaveparams('gmStateSpaceHDL_ssc_model');`

%% Set Model 'gmStateSpaceHDL_ssc_model' HDL parameters hdlset_param('gmStateSpaceHDL_ssc_model', 'FloatingPointTargetConfiguration', ... hdlcoder.createFloatingPointTargetConfig('NativeFloatingPoint')); hdlset_param('gmStateSpaceHDL_ssc_model', 'MaskParameterAsGeneric', 'on'); hdlset_param('gmStateSpaceHDL_ssc_model', 'Oversampling', 100); % Set SubSystem HDL parameters hdlset_param('gmStateSpaceHDL_ssc_model/HDL Subsystem', 'FlattenHierarchy', 'on');

Save validation model generation settings.

HDLmodelname = 'gmStateSpaceHDL_ssc_model'; hdlset_param(HDLmodelname, 'GenerateValidationModel', 'on');

Generate HDL code.

`makehdl('gmStateSpaceHDL_ssc_model/HDL Subsystem')`

### Generating HDL for 'gmStateSpaceHDL_ssc_model/HDL Subsystem'. ### Using the config set for model gmStateSpaceHDL_ssc_model ... for HDL code generation parameters. ### Starting HDL check. ### The code generation and optimization options you ... have chosen have introduced additional pipeline delays. ### The delay balancing feature has automatically inserted ... matching delays for compensation. ### The DUT requires an initial pipeline setup latency. ... Each output port experiences these additional delays. ### Output port 0: 1 cycles. ### Clock-rate pipelining results can be diagnosed by running this script:... C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\highlightClockRatePipelining.m ### One or more feedback loops in the model are inhibiting optimizations. ... To highlight these loops in your model, click the following MATLAB ... script: C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\highlightFeedbackLoop.m ### To clear highlighting, click the following MATLAB ... script: C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\clearhighlighting.m ### Generating new validation model: gm_gmStateSpaceHDL_ssc_model_vnl. ### Validation model generation complete. ### Begin VHDL Code Generation for 'gmStateSpaceHDL_ssc_model'. ### MESSAGE: The design requires 100 times faster clock ... with respect to the base rate = 2e-07. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode ... Selection/Mode Vector To Index/Subsystem1 ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_mul_comp ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\nfp_mul_comp.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_add_comp ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\nfp_add_comp.vhd. ### Working on MultiplyAndAdd_2_entries ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\MultiplyAndAdd_2_entries.vhd. ### Working on MultiplyAndAdd_1_entries ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\MultiplyAndAdd_1_entries.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_uminus_comp ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\nfp_uminus_comp.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_relop_comp ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\nfp_relop_comp.vhd. ### Working on HDL Subsystem_tc ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem_tc.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem ... as C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem.vhd. ### Generating package file ... C:\Temp\hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem_pkg.vhd. ### Generating HTML files for code generation report ... at gmStateSpaceHDL_ssc_model_codegen_rpt.html ### Creating HDL Code Generation Check Report HDL_Subsystem_report.html ### HDL check for 'gmStateSpaceHDL_ssc_model' complete ... with 0 errors, 0 warnings, and 3 messages. ### HDL code generation complete.

The HDL code generation report opens and includes any generated errors or warnings. The report includes a link to the resource utilization report, which describes the resource requirements for FPGA deployment.

The generated HDL code and validation model are saved in the

**hdlsrc\gmStateSpaceHDL_ssc_model\html**directory. The generated code is saved as**HDL_Subsystem_tc.vhd**.To generate HDL code for deployment to a specified target, use the HDL Workflow Advisor.

`simscape.findNonlinearBlocks`

|`hdladvisor`

(HDL Coder) |`hdlsaveparams`

(HDL Coder) |`hdlset_param`

(HDL Coder) |`hdlsetup`

(HDL Coder) |`makehdl`

(HDL Coder) |`sschdladvisor`

(HDL Coder)

- View Sample Time Information
- Generate HDL Code for Simscape Models (HDL Coder)
- Generate Simulink Real-Time Interface Subsystem for Simscape Two-Level Converter Model (HDL Coder)
- Troubleshoot Conversion of Simscape DC Motor Control to HDL-Compatible Simulink Model (HDL Coder)
- Troubleshoot Conversion of Simscape Permanent Magnet Synchronous Motor to HDL-Compatible Simulink Model (HDL Coder)
- View Data in the Simulation Data Inspector