## Generate HDL Code Using the Simscape HDL Workflow Advisor

If you have an HDL Coder™ license, 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 generates a Simulink® implementation of your Simscape model 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

• Rapidly prototype models using the reconfigurability and parallelism capabilities of the FPGA

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

### Basic Simscape HDL Workflow Advisor Steps

Convert a Simscape model to HDL code using the Simscape HDL Workflow Advisor by following these steps.

1. Generate baseline results for your Simscape model.

2. Ensure that the model contains only linear or switched linear blocks by using the simscape.findNonlinearBlocks function.

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

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

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

2. Display sample time information.

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

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

6. Run the Simscape HDL Workflow Advisor tasks by using the sschdladvisor (HDL Coder) function. The HDL Workflow Advisor:

• Checks for HDL code generation compatibility by ensuring that the model contains only linear and switched linear blocks 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.

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

8. Generate the HDL code:

1. Run the hdlsetup (HDL Coder) function. The hdlsetup function configures the fixed-step solver for HDL code generation and specifies the simulation start and stop times.

2. Save the model parameters and validation model generation settings.

3. Generate code using the makehdl function.

Before running the Simscape HDL Workflow Advisor, configure your network to exclude:

• Events

• Mode charts

• Delays

• Enabled run time 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.

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

#### Model Preparation

To prepare your Simscape model for FPGA deployment:

1. Open the ssc_bridge_rectifier model and show hidden block names. At the MATLAB® command prompt, enter

baselineModel = 'ssc_bridge_rectifier'; load_system(baselineModel) set_param(baselineModel,'HideAutomaticNames','off') open_system(baselineModel)

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

1. Open the Scope block. Click View > Configuration Properties. On the Logging tab, clear Limit data points to last.

2. Right-click the connection to the Scope block and select Log selected signals. The logging badge appears above the signal.

3. 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 returns the expected results for the full-wave bridge rectifier load voltage.

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

5. You can replace the periodic source with a Controlled Voltage Source block in the Simscape network with a Sine Wave block outside the network.

1. Delete the AC Voltage Source block.

2. Add a Sine Wave block from the Simulink > Sources library.

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

4. Add a Controlled Voltage Source block from the SimscapeFoundation LibraryElectricalElectrical Sources library.

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

6. Configure the Sine Wave block to match the parameters of the AC Voltage Source block that you removed.

1. Set the Amplitude parameter to sqrt(2)*120.

2. Set the Frequency (rad/sec) parameter to 60*2*pi.

3. Set the Sample time parameter to 1e-5. Then click the three-dots icon next to the Sample time box, and select Create variable. Name the variable Ts and click . You can now view and edit this variable in you workspace.

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

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

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

10. The model is stil 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.

11. Configure the model for real-time simulation.

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

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

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

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

2. Run the Simscape HDL Workflow Advisor.

sschdladvisor('ssc_model')

The Simscape HDL Workflow Advisor opens.

3. Run the code generation compatibility checks.

1. Select Code generation compatibility > Check solver configuration , then click .

2. Select Check model compatibility, then click .

The advisor reports when the model passes these checks.

4. Extract the state-space coefficients. Select State-space conversion and click . 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.

5. Generate an HDL implementation of your model. Select Implementation model generation > Generate implementation model and click .

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.

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

7. Prepare the implementation model for a simulation comparison to the baseline results:

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

2. Right-click the input signal to the Scope block and click Log Selected Signals.

The Display block in the model window shows the elapsed simulation time.

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

9. Generate HDL code from the implementation:

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

2. Run the hdlsetup function.

hdlsetup('gmStateSpaceHDL_ssc_model')
3. 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); 
4. Save the validation model generation settings.

HDLmodelname = 'gmStateSpaceHDL_ssc_model'; hdlset_param(HDLmodelname, 'GenerateValidationModel', 'on');
5. 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 Selection/State Mode Vector To Index/Subsystem7 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem6 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem5 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block1.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem4 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block2.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem3 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block3.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem2 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block4.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/HDL Algorithm/Mode Selection/State Mode Vector To Index/Subsystem1 as ... hdlsrc\gmStateSpaceHDL_ssc_model\Subsystem1_block5.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 gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_uminus_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_uminus_single.vhd. ### Working on gmStateSpaceHDL_ssc_model/HDL Subsystem/nfp_relop_single as hdlsrc\gmStateSpaceHDL_ssc_model\nfp_relop_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, 7 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 as HDL_Subsystem_tc.vhd.

To generate HDL code for deployment to a specified target, use the HDL Workflow Advisor.