Generate HDL Code from Simscape Models in the Simscape FPGA HIL Workflow
With an HDL Coder™ license and the Simscape™ HDL Workflow Advisor, you can generate HDL code from your Simscape model to deploy onto FPGA platforms. The advisor converts your Simscape model into a Simulink® implementation model that HDL Coder uses to generate HDL code.
Converting your Simscape model to HDL code allows you to:
Take advantage of the Simscape physical system modelling capabilities.
Rapidly prototype models using the reconfigurability and parallelism capabilities of the FPGA.
Simulate the HDL implementation in real time with hardware-in-the-loop (HIL).
Before you run the Simscape HDL Workflow Advisor, configure your network to exclude delays and enabled runtime parameters. To learn more about the capabilities and limitations of Simscape models in HDL Coder, visit Get Started with Simscape Hardware-in-the-Loop Workflow (HDL Coder).
Generate HDL Code for a Simscape Model Using the Simscape HDL Workflow Advisor
This example shows how to convert your Simscape model to HDL code using the Simscape HDL Workflow Advisor and the Backward-Euler solver. 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.
Note
This example involves reconfiguring a model to replace nonlinear blocks, which is
necessary when you want to use the Backward-Euler solver. To avoid reconfiguring the
model, you can set Solver type to Partitioning
solver
.
Model Preparation
To prepare your Simscape model for FPGA deployment:
Open the
ssc_bridge_rectifier
model. At the MATLAB® command prompt, enterbaselineModel = 'ssc_bridge_rectifier'; load_system(baselineModel) open_system(baselineModel)
To compare the baseline simulation results to subsequent iterations, remove the data point limitation on the Scope block labeled Load Voltage scope block and capture the signal that inputs data to the Scope block by enabling data logging to the Simulation Data Inspector.
Open the Scope block. Click View > Configuration Properties. On the Logging tab, clear Limit data points to last.
Right-click the connection to the Scope block and select
Log selected signals
. The logging badgeappears above the signal.
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 space bar on your keyboard to fit the Simulation Data Inspector plot to view.
The baseline simulation returns the expected results for the full-wave bridge rectifier load voltage.
Before running the advisor, identify and replace blocks that cause your network to be nonlinear. To identify the blocks, use the
simscape.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 periodic source with a Controlled Voltage Source block in the Simscape network with a Sine Wave block outside the network.
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 SimscapeFoundation LibraryElectricalElectrical 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.
Configure the Sine Wave block to match the parameters of the AC Voltage Source block that you removed.
Set the Amplitude parameter to
sqrt(2)*120
.Set the Frequency (rad/sec) parameter to
60*2*pi
.Set the Sample time parameter to
1e-5
. Then click the three-dots iconnext to the Sample time box, and select Create variable. Name the variable
Ts
and click Create. You can now view and edit this variable in you workspace.
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. Now the model is ready for the Backward-Euler solver.
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 perform future progress checks for the Simscape HDL Workflow Advisor, add and connect a Digital Clock block from the Simulink > Sources library and a Display block from the SimulinkSinks library, as shown in the figure. For the Digital Clock, set the Sample time parameter to
Ts
.The model is still set to use a variable-step solver. For real time-simulation, you must use a fixed-step solver. Use the sample time colors and annotations to help you to determine if your model contains any continuous settings. To turn on sample time colors and annotations, on the Debug tab, click Information Overlays, and in the Sample Time group, select Colors and Text.
The model diagram updates and the Timing Legend pane displays.
Configure the model for real-time simulation.
Configure the Simulink model for fixed-step, fixed-cost simulation. In the Configuration Parameters window, click Solver and set:
Type to
Fixed-step
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.
Set Solver type 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 Using the Simscape HDL Workflow Advisor
Generate HDL code by running the Simscape HDL Workflow Advisor either on the Simscape model that you prepared in the Model Preparation section or by
opening the ssc_bridge_rectifier_hdl
model, which is prepared for
code generation.
Rename the model.
If you prepared the model in the Model Preparation section, 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 , then click Run This Task.
Select Check model compatibility, then click Run this task.
The advisor reports when the model passes these checks.
Extract the state-space coefficients. Select State-space conversion and click Run All. The conversion can take some 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
Number of differential variables: 1
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 1 D 1 x 1 x 1 Y0 1 x 1 x 1 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.
Note
This table will have different values if you perform this step using the partitioning solver.
Generate an HDL implementation of your model. Select Implementation model generation > Generate implementation model and click Run this task.
When the Simscape HDL Workflow Advisor generates the implementation model, the advisor reports that the task passed and displays a link to the generated implementation model, which is named
gmStateSpaceHDL_ssc_model
.Open the generated implementation model by clicking gmStateSpaceHDL_ssc_model.
The model contains blocks from the original model as well as new blocks that support the HDL Workflow Advisor:
Digital Clock, Display, Sine Wave, and Load Voltage—Remnants from your original model
Rate Transition1 — Handles the transfer of data between blocks operating at different rates.
Data Type Conversion1, Data Type Conversion2 — Converts between double and single precision data types. HDL code generation requires single-precision data
HDL Subsystem —Contains an HDL code generation-compatible version of your Simscape network.
Load Voltage — Scope block that displays the load voltage.
Prepare the implementation model for a simulation comparison to the baseline results:
You can adjust the automatically generated model and delete vestigial blocks as necessary to improve model cleanliness. The Digial Clock block and the Display block are unnecessary but will not inhibit the simulation results.
Right-click the input signal to the Scope block and click Log Selected Signals.
If your model is too stiff, you may encounter a validation mismatch. To learn about checking the model stiffness, visit Simscape Stiffness Impact Analysis.
The Display block in the model window shows the elapsed simulation time.
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. The Simscape model is compatible with HDL code generation.
Generate HDL code from the implementation:
Access the Configuration Parameters window from the HDL implementation model. Expand HDL Code Generation and select Report. Check the boxes for the Generate traceability report and 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' ... , 'LatencyStrategy', 'MIN') ... ); hdlset_param('gmStateSpaceHDL_ssc_model', 'HDLSubsystem', 'gmStateSpaceHDL_ssc_model/HDL Subsystem'); hdlset_param('gmStateSpaceHDL_ssc_model', 'MaskParameterAsGeneric', 'on'); hdlset_param('gmStateSpaceHDL_ssc_model', 'Oversampling', 49); % Set SubSystem HDL parameters hdlset_param('gmStateSpaceHDL_ssc_model/HDL Subsystem', 'FlattenHierarchy', 'on'); hdlset_param('gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/Generate Mode Vector', 'Architecture', 'MATLAB Datapath'); % Set SubSystem HDL parameters hdlset_param('gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/State Update/Multiply State', 'SharingFactor', 1);
Save the 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. ### Running HDL checks on the model 'gmStateSpaceHDL_ssc_model'. ### Begin compilation of the model 'gmStateSpaceHDL_ssc_model'... ### Applying HDL optimizations on the model 'gmStateSpaceHDL_ssc_model'... ### 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 1: 1 cycles. ### Begin model generation. ### Model generation complete. ### Clock-rate pipelining results can be diagnosed by running this script: hdlsrc\gmStateSpaceHDL_ssc_model\... highlightClockRatePipelining.m ### To clear highlighting, click the following MATLAB script: 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 49 times faster clock with respect to the base rate = 3.33333e-06. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Iteration Manager/Compare To Constant as hdlsrc\... gmStateSpaceHDL_ssc_model\Compare_To_Constant.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_mul_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_mul_single.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_add_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_add_single.vhd. ### Working on dot_product_2 as hdlsrc\gmStateSpaceHDL_ssc_model\dot_product_2.vhd. ### Working on dot_product_1 as hdlsrc\gmStateSpaceHDL_ssc_model\dot_product_1.vhd. ### Working on dot_product_1 as hdlsrc\gmStateSpaceHDL_ssc_model\dot_product_1_block.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_relop_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_relop_single.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_uminus_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_uminus_single.vhd. ### Working on HDL Subsystem_tc as hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem_tc.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem as hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem.vhd. ### Generating package file hdlsrc\gmStateSpaceHDL_ssc_model\HDL_Subsystem_pkg.vhd. ### Code Generation for 'gmStateSpaceHDL_ssc_model' completed. ### Creating HDL Code Generation Check Report HDL_Subsystem_report.html ### HDL check for 'gmStateSpaceHDL_ssc_model' complete with 0 errors, 2 warnings, and 2 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 asHDL_Subsystem_tc.vhd
.To generate HDL code for deployment to a specified target, use the HDL Workflow Advisor.
See Also
Blocks
Simscape Blocks
Functions
hdladvisor
(HDL Coder) |hdlsaveparams
(HDL Coder) |hdlset_param
(HDL Coder) |hdlsetup
(HDL Coder) |makehdl
(HDL Coder) |simscape.findNonlinearBlocks
|sschdladvisor
(HDL Coder)