HDL Verifier™ User's Guide
HDL Verifier™ User's Guide
HDL Verifier™ User's Guide
User’s Guide
R2014a
How to Contact MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support
508-647-7000 (Phone)
508-647-7001 (Fax)
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
August 2003 Online only New for Version 1 (Release 13SP1)
February 2004 Online only Revised for Version 1.1 (Release 13SP1)
June 2004 Online only Revised for Version 1.1.1 (Release 14)
October 2004 Online only Revised for Version 1.2 (Release 14SP1)
December 2004 Online only Revised for Version 1.3 (Release 14SP1+)
March 2005 Online only Revised for Version 1.3.1 (Release 14SP2)
September 2005 Online only Revised for Version 1.4 (Release 14SP3)
March 2006 Online only Revised for Version 2.0 (Release 2006a)
September 2006 Online only Revised for Version 2.1 (Release 2006b)
March 2007 Online only Revised for Version 2.2 (Release 2007a)
September 2007 Online only Revised for Version 2.3 (Release 2007b)
March 2008 Online only Revised for Version 2.4 (Release 2008a)
October 2008 Online only Revised for Version 2.5 (Release 2008b)
March 2009 Online only Revised for Version 2.6 (Release 2009a)
September 2009 Online only Revised for Version 3.0 (Release 2009b)
March 2010 Online only Revised for Version 3.1 (Release 2010a)
September 2010 Online only Revised for Version 3.2 (Release 2010b)
April 2011 Online only Revised for Version 3.3 (Release 2011a)
September 2011 Online only Revised for Version 3.4 (Release 2011b)
March 2012 Online only Revised for Version 4.0 (Release 2012a)
September 2012 Online only Revised for Version 4.1 (Release 2012b)
March 2013 Online only Revised for Version 4.2 (Release 2013a)
September 2013 Online only Revised for Version 4.3 (Release 2013b)
March 2014 Online only Revised for Version 4.4 (Release 2014a)
Contents
v
Example of Starting MATLAB Server for Test Bench
Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22
vi Contents
Automatic Cosimulation Verification . . . . . . . . . . . . . . . . 1-60
vii
Start HDL Simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15
Start HDL Simulator for Component Session . . . . . . . . . . . 2-15
Load HDL Design for Visualization . . . . . . . . . . . . . . . . . . . 2-15
viii Contents
Simulink Test Bench for HDL Component
4
Simulink as a Test Bench . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Communications During Test Bench Cosimulation . . . . . . 4-2
HDL Cosimulation Block Features for Test Bench
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
ix
Configure Communication Link in the HDL Cosimulation
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35
Specify Pre- and Post-Simulation Tcl Commands with HDL
Cosimulation Block Parameters Dialog Box . . . . . . . . . . 4-38
Programmatically Control Block Parameters . . . . . . . . . . . 4-41
x Contents
Replace HDL Component with Simulink Algorithm . . . 5-6
xi
Determine Available Socket Port Number . . . . . . . . . . . . . 5-45
Check Connection Status . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-45
Run and Test Component Cosimulation Model . . . . . . . . . . 5-45
Avoid Race Conditions in HDL Simulation with Component
Cosimulation and the HDL Verifier HDL Cosimulation
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-48
xii Contents
HDL Compilation—MATLAB Function . . . . . . . . . . . . . . . . 7-10
HDL Modules—MATLAB Function . . . . . . . . . . . . . . . . . . . 7-12
Callback Schedule—MATLAB Function . . . . . . . . . . . . . . . 7-14
Script Generation—MATLAB Function . . . . . . . . . . . . . . . 7-16
Complete the Component or Test Bench Function . . . . . . . 7-17
xiii
HDL Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-103
xiv Contents
Converting Data for Return to the HDL Simulator . . . . . . 8-70
System Objects
9
Create System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Create a System object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Change a System object Property . . . . . . . . . . . . . . . . . . . . 9-3
Check if a System object Property Has Changed . . . . . . . . 9-3
Run a System object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Display Available System Objects . . . . . . . . . . . . . . . . . . . . 9-3
xv
The Step Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7
Common Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7
Advantages of Using Methods . . . . . . . . . . . . . . . . . . . . . . . 9-9
FPGA-in-the-Loop
About FPGA-in-the-Loop (FIL) Simulation
10
FPGA-in-the-Loop (FIL) Simulation . . . . . . . . . . . . . . . . . 10-2
What is FPGA-in-the-Loop Simulation? . . . . . . . . . . . . . . . 10-2
What You Need To Know . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6
FIL Preparation
11
FPGA-in-the-Loop Simulation Workflows . . . . . . . . . . . . 11-2
xvi Contents
FPGA Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-25
xvii
Troubleshooting FPGA-in-the-Loop
14
Troubleshooting FIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
FIL Examples
15
Verify HDL Implementation of PID Controller Using
FPGA-in-the-Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
xviii Contents
What Is Support Package Installer? . . . . . . . . . . . . . . . . . . 16-12
xix
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-30
FIL I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-32
Turnkey I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-34
Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-37
Finish . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-38
xx Contents
TLM Component Timing Values . . . . . . . . . . . . . . . . . . . . . 19-27
TLM Component Naming and Packaging . . . . . . . . . . . . . . 19-28
xxi
Run TLM Component Test Bench
22
Testing TLM Components . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
TLM Component Test Bench Overview . . . . . . . . . . . . . . . . 22-2
TLM Component Compilation . . . . . . . . . . . . . . . . . . . . . . . 22-2
Automatic Verification of the Generated Component . . . . . 22-3
Report Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Working with Configurations . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Considerations When Creating a TLM Component Test
Bench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4
xxii Contents
Configuration Parameters for TLM Generator
Target
24
TLM Component Generation . . . . . . . . . . . . . . . . . . . . . . . 24-2
TLM Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
TLM Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-9
TLM Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-17
TLM Testbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-21
TLM Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-26
xxiii
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-20
xxiv Contents
HDL Verification with
Cosimulation
MATLAB test bench functions let you verify the performance of the HDL
model, or of components within the model. A test bench function drives
values onto signals connected to input ports of an HDL design under test and
receives signal values from the output ports of the module.
The following figure shows how a MATLAB function wraps around and
communicates with the HDL simulator during a test bench simulation session.
MATLAB
Stimulus Response
HDL Simulator
HDL Entity
Output Input
Arguments IN OUT Arguments
When linked with MATLAB, the HDL simulator functions as the client, with
MATLAB as the server. The following figure shows a multiple-client scenario
connecting to the server at TCP/IP socket port 4449.
1-2
MATLAB as a Test Bench
MATLAB
HDL Simulator Link Server
Port
Client 4449
1-3
1 HDL Cosimulation Using MATLAB Test Bench Function
1-4
Code HDL Modules for Verification Using MATLAB
The process for coding HDL modules for MATLAB verification is as follows:
• “Choose HDL Module Name for Use with MATLAB Test Bench” on page 1-6
• “Specify Port Direction Modes in HDL Module for Use with Test Bench”
on page 1-6
• “Specify Port Data Types in HDL Modules for Use with Test Bench” on
page 1-6
• “Compile and Elaborate HDL Design for Use with Test Bench” on page 1-8
1-5
1 HDL Cosimulation Using MATLAB Test Bench Function
1-6
Code HDL Modules for Verification Using MATLAB
Note If you use unsupported types, the HDL Verifier software issues a
warning and ignores the port at run time. For example, if you define your
interface with five ports, one of which is a VHDL access port, at run time,
then the interface displays a warning and your code sees only four ports.
The interface also supports all subtypes and arrays of the preceding types.
Note The HDL Verifier software does not support VHDL extended identifiers
for the following components:
1-7
1 HDL Cosimulation Using MATLAB Test Bench Function
• reg
• integer
• wire
Note HDL Verifier software does not support Verilog escaped identifiers for
port and signal names used in cosimulation. However, it does support simple
identifiers for Verilog.
You have the option of invoking the compiler from menus in the ModelSim
graphic interface or from the command line with the vcom command. The
following sequence of ModelSim commands creates and maps the design
library work and compiles the VHDL file modsimrand.vhd:
The following sequence of ModelSim commands creates and maps the design
library work and compiles the Verilog file test.v:
1-8
Code HDL Modules for Verification Using MATLAB
Note You should provide read/write access to the signals that are connecting
to the MATLAB session for cosimulation. For higher performance, you
want to provide access only to those signals used in cosimulation. You can
check read/write access through the HDL simulator—see HDL simulator
documentation for details.
The Cadence Incisive simulator allows for 1-step and 3-step processes for HDL
compilation, elaboration, and simulation. The following Cadence Incisive
simulator command compiles the Verilog file test.v:
Note You should provide read/write access to the signals that are connecting
to the MATLAB session for cosimulation. The previous example shows
how to provide read/write access to all signals in your design. For higher
performance, you want to provide access only to those signals used in
cosimulation. See the description of the +access flag to ncverilog and the
-access argument to ncelab for details.
For more examples, see the HDL Verifier tutorials and demos. For details on
using the HDL compiler, see the simulator documentation.
1-9
1 HDL Cosimulation Using MATLAB Test Bench Function
The keyword PORT marks the start of the entity’s port clause, which defines
two IN ports—isum and qsum—and three OUT ports—adj, dvalid, and odata.
The output ports drive signals to MATLAB function input ports for processing.
The input ports receive signals from the MATLAB function output ports.
Both input ports are defined as vectors consisting of five standard logic values.
The output port adj is also defined as a standard logic vector, but consists
of only two values. The output ports dvalid and odata are defined as scalar
standard logic ports. For information on how the HDL Verifier interface
converts data of standard logic scalar and array types for use in the MATLAB
environment, see “Data Type Conversions” on page 8-65.
ENTITY decoder IS
PORT (
isum : IN std_logic_vector(4 DOWNTO 0);
qsum : IN std_logic_vector(4 DOWNTO 0);
adj : OUT std_logic_vector(1 DOWNTO 0);
dvalid : OUT std_logic;
odata : OUT std_logic);
END decoder ;
1-10
Code an HDL Verifier™ Test Bench Function
1 Learn the syntax for a MATLAB HDL Verifier test bench function (see
“Syntax of a Test Bench Function” on page 1-12).
2 Understand how HDL Verifier software converts data from the HDL
simulator for use in the MATLAB environment (see “Data Type
Conversions” on page 8-65).
3 Choose a name for the MATLAB function (see “Bind HDL Module
Component to MATLAB Test Bench Function” on page 1-26).
5 Determine the types of port data being passed into the function (see
“MATLAB Function Syntax and Function Argument Definitions” on page
8-40).
1-11
1 HDL Cosimulation Using MATLAB Test Bench Function
For ModelSim Users This example uses a VHDL entity and MATLAB
function code drawn from the decoder portion of the Manchester Receiver
example. For the complete VHDL and function code listings, see the following
files:
matlabroot\toolbox\edalink\extensions\modelsim\modelsimdemos\vhdl\manchester\decoder.vhd
matlabroot\toolbox\edalink\extensions\modelsim\modelsimdemos\manchester_decoder.m
As the first step to coding a MATLAB test bench function, you must
understand how the data modeled in the VHDL entity maps to data in the
MATLAB environment. The VHDL entity decoder is defined as follows:
ENTITY decoder IS
PORT (
isum : IN std_logic_vector(4 DOWNTO 0);
qsum : IN std_logic_vector(4 DOWNTO 0);
1-12
Code an HDL Verifier™ Test Bench Function
The following discussion highlights key lines of code in the definition of the
manchester_decoder MATLAB function:
tnext = [];
iport = struct();
1-13
1 HDL Cosimulation Using MATLAB Test Bench Function
The following figure shows the relationship between the entity’s ports
and the MATLAB function’s iport and oport parameters.
oport.adj (2)
iport.isum (5)
decoder.vhd oport.dvalid(1)
iport.qsum (5)
oport.odata(1)
2 Make note of the data types of ports defined for the entity being
simulated.
The VHDL entity defined for this example consists of the following ports
1-14
Code an HDL Verifier™ Test Bench Function
For more information on interface data type conversions, see “Data Type
Conversions” on page 8-65.
tnext = tnow+1e-9;
1-15
1 HDL Cosimulation Using MATLAB Test Bench Function
The following code excerpt illustrates data type conversion of output port
data.
The two calls to mvl2dec convert the binary data that the MATLAB
function receives from the entity’s output ports, adj, dvalid, and odata to
unsigned decimal values that MATLAB can compute. The function converts
the 2-bit transposed vector oport.adj to a decimal value in the range 0 to
4 and oport.dvalid and oport.odata to the decimal value 0 or 1.
if isum == 17
iport.isum = dec2mvl(isum,5);
iport.qsum = dec2mvl(qsum,5);
else
iport.isum = dec2mvl(isum,5);
end
1-16
Code an HDL Verifier™ Test Bench Function
“Converting Data for Return to the HDL Simulator” on page 8-70 provides
a summary of the types of data conversions to consider when returning
data to the HDL simulator.
persistent isum;
persistent qsum;
%persistent ga;
persistent x;
persistent y;
persistent adj;
persistent data;
global testisdone;
% This useful feature allows you to manually
% reset the plot by simply typing: >manchester_decoder
1-17
1 HDL Cosimulation Using MATLAB Test Bench Function
tnext = [];
iport = struct();
if nargin == 0,
isum = [];
return;
end
if exist('portinfo') == 1
isum = [];
end
tnext = tnow+1e-9;
if isempty(isum), %% First call
scale = 9;
isum = 0;
qsum = 0;
for k=1:2,
ga(k) = subplot(2,1,k);
axis([-1 17 -1 17]);
ylabel('Quadrature');
line([0 16],[8 8],'Color','r','LineStyle',':','LineWidth',1)
line([8 8],[0 16],'Color','r','LineStyle',':','LineWidth',1)
end
xlabel('Inphase');
subplot(2,1,1);
title('Clock Adjustment (adj)');
subplot(2,1,2);
title('Data with Validity');
iport.isum = '00000';
iport.qsum = '00000';
return;
end
if isum == 17,
1-18
Code an HDL Verifier™ Test Bench Function
subplot(2,1,1);
for k=0:16,
if adj(k+1) == 0, % Bang on!
line(k,qsum,'color','k','Marker','o');
elseif adj(k+1) == 1, %
line(k,qsum,'color','r','Marker','<');
else
line(k,qsum,'color','b','Marker','>');
end
end
subplot(2,1,2);
for k=0:16,
if data(k+1) < 2, % Invalid
line(k,qsum,'color','r','Marker','X');
else
if data(k+1) == 2, %Valid and 0!
line(k,qsum,'color','g','Marker','o');
else
line(k,qsum,'color','k','Marker','.');
end
end
end
isum = 0;
qsum = qsum + 1;
if qsum == 17,
qsum = 0;
disp('done');
tnext = []; % suspend callbacks
testisdone = 1;
return;
end
iport.isum = dec2bin(isum,5);
iport.qsum = dec2bin(qsum,5);
else
iport.isum = dec2bin(isum,5);
end
1-19
1 HDL Cosimulation Using MATLAB Test Bench Function
which MyVhdlFunction
/work/incisive/MySym/MyVhdlFunction.m
If the specified function is on the search path, which displays the complete
path to the function. If the function is not on the search path, which informs
you that the file was not found.
1-20
Start Server for MATLAB—HDL Simulator Connection
1 Start MATLAB.
See hdldaemon reference documentation for when and how to specify property
name/property value pairs and for more examples of using hdldaemon.
The communication mode that you specify (shared memory or TCP/IP sockets)
must match what you specify for the communication mode when you initialize
the HDL simulator for use with a MATLAB cosimulation session using the
matlabtb or matlabcp function. In addition, if you specify TCP/IP socket
mode, the socket port that you specify with hdldaemon and matlabtb or
matlabcp must match. See “TCP/IP Socket Ports” on page 8-95 for more
information .
1-21
1 HDL Cosimulation Using MATLAB Test Bench Function
Note You cannot begin an HDL Verifier transaction between MATLAB and
the HDL simulator from MATLAB. The MATLAB server simply responds to
function call requests that it receives from the HDL simulator.
1-22
Start HDL Simulator
>>vsim
You can call vsim or nclaunch with additional parameters; see the reference
pages for details.
You must make sure the HDL simulator executables — also called vsim
(ModelSim®) and nclaunch (Cadence Incisive®) — are on the system path. See
your system documentation for instruction on setting environment variables.
Linux Users Make sure the HDL simulator executable is still on the system
path after the shell is launched from MATLAB. If it is not, make sure the
shell startup file does not remove it from the path environment variable.
hdlsimmatlab work.osc_top
This command loads the HDL Verifier library, opens a simulation workspace
for osc_top, and display a series of messages in the HDL simulator command
window as the simulator loads the entity (see example for remaining code).
1-23
1 HDL Cosimulation Using MATLAB Test Bench Function
Be sure to follow the path specifications for MATLAB test bench sessions
when invoking matlabtb, as explained in “Specify HDL Signal/Port and
Module Paths for MATLAB Test Bench Cosimulation” on page 1-24.
For instructions in issuing the matlabtb command, see “Run MATLAB Test
Bench Simulation” on page 1-32.
The rules stated in this section apply to signal/port and module path
specifications for MATLAB cosimulation sessions. Other specifications may
work but the HDL Verifier software does not officially recognize nor support
them.
1-24
Bind Test Bench Function Calls With matlabtb
Path Specifications for MATLAB Link Sessions with Verilog Top Level.
The following examples show valid signal and module path specifications:
top.port_or_sig
/top/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
Path Specifications for MATLAB Link Sessions with VHDL Top Level.
• The path specification can include the top-level module name, but you do
not have to include it.
1-25
1 HDL Cosimulation Using MATLAB Test Bench Function
• The path specification can include "." or "/" path delimiters, but it cannot
include mixed delimiters.
• The leaf module or signal must match the HDL language of the top-level
module.
The following examples show valid signal and module path specifications:
top.port_or_sig
/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
1-26
Bind Test Bench Function Calls With matlabtb
For more information on the -mfunc argument and for a full list of matlabtb
parameters, see the matlabtb function reference.
The matlabtb command instructs the HDL simulator to call back the
inverter_tb function when inverter_vl executes in the simulation.
When the HDL simulator calls the oscfilter callback, the function knows to
operate on the model osc_top.u_osc_filter.
1-27
1 HDL Cosimulation Using MATLAB Test Bench Function
The two types of scheduling are not mutually exclusive. You can combine
the matlabtb or matlabcp timing arguments and the tnext parameter of a
MATLAB function to schedule test bench or component session callbacks.
1-28
Schedule Options for a Test Bench Session
You can set the value of tnext to a value of type double or int64. Specify
double to express the callback time in seconds. For example, to schedule
a callback in 1 ns, specify::
tnext = 1e-9
tnext=int64(100)
1-29
1 HDL Cosimulation Using MATLAB Test Bench Function
Note The tnext parameter represents time from the start of the simulation.
Therefore, tnext must always be greater than tnow. If it is less, the software
does not schedule a callback.
For more information on tnext and the function prototype, see “MATLAB
Function Syntax and Function Argument Definitions” on page 8-40.
tnext = [];
.
.
.
tnext = tnow+1e-9;
Using tnext you can dynamically decide the callback scheduling based on
criteria specific to the operation of the test bench. For example, you can decide
to stop scheduling callbacks when a data signal has a certain value:
if qsum == 17,
qsum = 0;
disp('done');
tnext = []; % suspend callbacks
testisdone = 1;
return;
end
1-30
Schedule Options for a Test Bench Session
The following assignment statement sets the timing parameter tnext. This
parameter schedules the next callback to the MATLAB component function,
relative to the current simulation time (tnow).
The function returns a new value for tnext each time the HDL simulator
calls the function.
1-31
1 HDL Cosimulation Using MATLAB Test Bench Function
3 “Apply Stimuli to Test Bench Session with force Command” on page 1-37
hdldaemon('status')
The function displays a message that indicates whether the server is running
and, if it is running, the number of connections it is handling. For example:
1-32
Run MATLAB Test Bench Simulation
• “Cosimulation with MATLAB Using the HDL Simulator GUI” on page 1-33
• “Cosimulation with MATLAB Using the Command Line Interface (CLI)”
on page 1-35
• “Cosimulation with MATLAB Using Batch Mode” on page 1-36
1 Set breakpoints in the HDL and MATLAB code to verify and analyze
simulation progress.
How you set breakpoints in the HDL simulator will vary depending on
what simulator application you are using.
In MATLAB, there are several ways you can set breakpoints; for example,
by using the Set/Clear Breakpoint button on the toolbar.
When you begin a specific test bench or component session, you specify
parameters that identify the following information:
1-33
1 HDL Cosimulation Using MATLAB Test Bench Function
For example:
The run command offers a variety of options for applying control over how
a simulation runs (refer to your HDL simulator documentation for details).
For example, you can specify that a simulation run for several time steps.
The following command instructs the HDL simulator to run the loaded
simulation for 50000 time steps:
run 50000
How you step through the simulation in the HDL simulator will vary
depending on what simulator application you are using.
In MATLAB, there are several ways you can step through code; for
example, by clicking the Step toolbar button.
5 When you block execution of the MATLAB function, the HDL simulator
also blocks and remains blocked until you clear all breakpoints in the
function’s code.
How you resume the simulation in the HDL simulator will vary depending
on what simulator application you are using.
1-34
Run MATLAB Test Bench Simulation
In MATLAB, there are several ways you can resume the simulation; for
example, by clicking the Continue toolbar button.
run -continue
To use the CLI, specify "CLI" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command.
The Tcl command you build to pass to the HDL simulator launch command
must contain the run command or no cosimulation will take place.
Caution Close the terminal window by entering "quit -f" at the command
prompt. Do not close the terminal window by clicking the "X" in the upper
right-hand corner. This causes a memory-type error to be issued from the
system. This is not a bug with HDL Verifier but just the way the HDL
simulator behaves in this context.
You can type CTRL+C to interrupt and terminate the simulation in the HDL
simulator but this action also causes the memory-type error to be displayed.
Issue the nclaunch command with "CLI" as the runmode property value, as
follows (example entered into the MATLAB editor):
1-35
1 HDL Cosimulation Using MATLAB Test Bench Function
nclaunch('tclstart',tclcmd,'runmode','CLI');
Issue the vsim command with "CLI" as the runmode property value, as follows
(example entered into the MATLAB editor):
vsim('tclstart',tclcmd,'runmode','CLI');
To use the batch mode, specify "Batch" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command. After you
issue the HDL Verifier HDL simulator launch command with batch mode
specified, start the simulation in Simulink. To stop the HDL simulator before
the simulation is completed, issue the breakHdlSim command.
1-36
Run MATLAB Test Bench Simulation
nclaunch('tclstart',manchestercmds,'runmode','Batch')
You can also set runmode to "Batch with Xterm", which starts the HDL
simulator in the background but shows the session in an Xterm.
Issue the vsim command with "Batch" as the runmode parameter, as follows:
>> vsim('tclstart',manchestercmds,'runmode','Batch')
Other ways to apply stimuli include issuing force commands in the HDL
simulator main window (for ModelSim, you can also use the Edit > Clock
option in the ModelSim Signals window).
• Incisive
• ModelSim
1-37
1 HDL Cosimulation Using MATLAB Test Bench Function
1
0
...
t 0 5 10 20 30
For example,
1-38
Run MATLAB Test Bench Simulation
1 Make the HDL simulator your active window, if your input focus was not
already set to that application.
2 Reload HDL design elements and reset the simulation time to zero.
1-39
1 HDL Cosimulation Using MATLAB Test Bench Function
1 Make the HDL simulator your active window, if your input focus was not
already set to that application.
2 Halt the simulation. You must quit the simulation at the HDL simulator
side or MATLAB may hang until the simulator is quit.
4 Exit the HDL simulator, if you are finished with the application.
5 Quit MATLAB, if you are finished with the application. If you want to
shut down the server manually, stop the server by calling hdldaemon with
the 'kill' option:
hdldaemon('kill')
For more information on closing HDL simulator sessions, see the HDL
simulator documentation.
1-40
Verify HDL Model with MATLAB Testbench
Tutorial Overview
This tutorial guides you through the basic steps for setting up an HDL
Verifier application that uses MATLAB to verify a simple HDL design. In this
tutorial, you develop, simulate, and verify a model of a pseudorandom number
generator based on the Fibonacci sequence. The model is coded in VHDL.
Note This tutorial demonstrates creating and running a test bench using
ModelSim SE 6.5. If you are not using this version, the messages and screen
images from ModelSim may not appear to you exactly as they do in this
tutorial.
This tutorial requires MATLAB, the HDL Verifier software, and the
ModelSim HDL simulator.
1-41
1 HDL Cosimulation Using MATLAB Test Bench Function
1 Create a folder outside the scope of your MATLAB installation folder into
which you can copy the tutorial files. The folder must be writable. This
tutorial assumes that you create a folder named MyPlayArea.
matlabroot\toolbox\edalink\extensions\modelsim\modelsimdemos\modsimrand_pl
matlabroot\toolbox\edalink\extensions\modelsim\modelsimdemos\VHDL\modsimra
1 Start MATLAB.
1-42
Verify HDL Model with MATLAB Testbench
2 Set your MATLAB current folder to the folder you created in “Set Up
Tutorial Files” on page 1-42.
hdldaemon('status')
hdldaemon('kill')
You will see the following message that confirms that the server was shut
down.
5 Start the server in TCP/IP socket mode by calling hdldaemon with the
property name/property value pair 'socket' 0. The value 0 specifies
that the operating system assign the server a TCP/IP socket port that is
available on your system. For example
hdldaemon('socket', 0)
The server informs you that it has started by displaying the following
message. The portnum will be specific to your system:
1-43
1 HDL Cosimulation Using MATLAB Test Bench Function
Make note of portnum as you will need it when you issue the matlabtb
command in “Load Simulation” on page 1-51.
You can alternatively specify that the MATLAB server use shared memory
communication instead of TCP/IP socket communication; however, for this
tutorial we will use socket communication as means of demonstrating this
type of connection. For details on how to specify the various options, see
the description of hdldaemon.
vsim
This function launches and configures ModelSim for use with the HDL
Verifier software. The first folder of ModelSim matches your MATLAB
current folder.
2 Verify the current ModelSim folder. You can verify that the current
ModelSim folder matches the MATLAB current folder by entering the ls
command in the ModelSim command window.
1-44
Verify HDL Model with MATLAB Testbench
If it does not, change your ModelSim folder to the current MATLAB folder.
You can find the current MATLAB folder by looking in the Current Folder
Browser or by viewing the Current folder navigation bar. In ModelSim, you
can change the working folder by issuing the command
cd directory
Where directory is the folder you want to work from. Or you may also
change directory by selecting File > Change Directory....
Note You must use the ModelSim File menu or vlib command to create
the library folder so that the required _info file is created. Do not create
the library with operating system commands.
1-45
1 HDL Cosimulation Using MATLAB Test Bench Function
If you choose not to examine the HDL code at this time, skip to “Compile
VHDL” on page 1-48.
You can open modsimrand.vhd in the edit window with the edit command, as
follows:
ModelSim opens its edit window and displays the VHDL code for
modsimrand.vhd.
1-46
Verify HDL Model with MATLAB Testbench
• The line ENTITY modsimrand contains the definition for the VHDL entity
modsimrand:
ENTITY modsimrand IS
PORT (
clk : IN std_logic ;
clk_en : IN std_logic ;
reset : IN std_logic ;
dout : OUT std_logic_vector (31 DOWNTO 0);
END modsimrand;
This is the entity that will be verified in the MATLAB environment during
the tutorial. Note the following:
- By default, the MATLAB server assumes that the name of the MATLAB
function that verifies the entity in the MATLAB environment is the
same as the entity name. You have the option of naming the MATLAB
function explicitly. However, if you do not specify a name, the server
1-47
1 HDL Cosimulation Using MATLAB Test Bench Function
expects the function name to match the entity name. In this example,
the MATLAB function name is modsimrand_plot and does not match.
- The entity must be defined with a PORT clause that includes at least one
port definition. Each port definition must specify a port mode (IN, OUT,
or INOUT) and a VHDL data type that is supported by the HDL Verifier
software. For a list of the supported types, see “Code HDL Modules for
Verification Using MATLAB ” on page 1-5.
The entity modsimrand in this example is defined with three input
ports clk, clk_en, and reset of type STD_LOGIC and output port dout
of type STD_LOGIC_VECTOR. The output port passes simulation output
data out to the MATLAB function for verification. The optional input
ports receive clock and reset signals from the function. Alternatively, the
input ports can receive signals from ModelSim force commands.
For more information on coding port entities for use with MATLAB, see
“Code HDL Modules for Verification Using MATLAB ” on page 1-5.
• The remaining code for modsimrand.vhd defines a behavioral architecture
for modsimrand that writes a randomly generated Fibonacci sequence to an
output register when the clock experiences a rising edge.
When you are finished examining the file, close the ModelSim edit window.
Compile VHDL
After you create or edit your VHDL source files, compile them. As part of this
tutorial, compile modsimrand.vhd. One way of compiling the file is to click the
file name in the project workspace and select Compile > Compile All. An
alternative is to specify modsimrand.vhd with the vcom command, as follows:
1-48
Verify HDL Model with MATLAB Testbench
If you choose not to examine the HDL code at this time, skip to “Load
Simulation” on page 1-51.
edit modsimrand_plot.m
• On line 1, you will find the MATLAB function name specified along with its
required parameters:
1-49
1 HDL Cosimulation Using MATLAB Test Bench Function
tnext = [];
iport = struct();
In this case, function outputs iport and tnext are initialized to empty
values.
• When coding a MATLAB function for use with HDL Verifier, you need to
know the types of the data that the test bench function receives from and
needs to return to ModelSim and how HDL Verifier handles this data; see
“Data Type Conversions” on page 8-65. This function includes the following
port data type definitions and conversions:
- The entity defined for this tutorial consists of three input ports of type
STD_LOGIC and an output port of type STD_LOGIC_VECTOR.
- Data of type STD_LOGIC_VECTOR consists of a column vector of characters
with one bit per character.
- The interface converts scalar data of type STD_LOGIC to a character that
matches the character literal for the corresponding enumerated type.
On line 62, the line of code containing oport.dout shows how the data that
a MATLAB function receives from ModelSim might need to be converted
for use in the MATLAB environment:
ud.buffer(cyc) = mvl2dec(oport.dout)
1-50
Verify HDL Model with MATLAB Testbench
Load Simulation
After you compile the VHDL source file, you are ready to load the model
for simulation. This section explains how to load an instance of entity
modsimrand for simulation:
1-51
1 HDL Cosimulation Using MATLAB Test Bench Function
1-52
Verify HDL Model with MATLAB Testbench
3 Initialize clock and reset input signals. You can drive simulation input
signals using several mechanisms, including ModelSim force commands
and an iport parameter (see “Syntax of a Test Bench Function” on page
1-12). For now, enter the following force commands:
The first command forces the clk signal to value 0 at 0 nanoseconds and to
1 at 5 nanoseconds. After 10 nanoseconds, the cycle starts to repeat every
10 nanoseconds. The second and third force commands set clk_en to 1
and reset to 1 at 0 nanoseconds and to 0 at 50 nanoseconds.
Run Simulation
This section explains how to start and monitor this simulation, and rerun it, if
you desire. When you have completed as many simulation runs as desired,
shut down the simulation as described in the next section.
1-53
1 HDL Cosimulation Using MATLAB Test Bench Function
hdldaemon('status')
Or
Note If you attempt to run the simulation before starting the hdldaemon
in MATLAB, you will receive the following warning:
4 Search for oport.dout and set a breakpoint at that line by clicking next to
the line number. A red breakpoint marker will appear.
1-54
Verify HDL Model with MATLAB Testbench
ModelSim is now blocked and remains blocked until you explicitly unblock
it. While the simulation is blocked, note that MATLAB displays the data
that ModelSim passed to the MATLAB function in the Workspace window.
In ModelSim, an empty figure window opens. You can use this window to
plot data generated by the simulation.
7 Click Continue in the MATLAB Editor. The next time the breakpoint
is reached, notice that portinfo no longer appears in the MATLAB
1-55
1 HDL Cosimulation Using MATLAB Test Bench Function
1-56
Verify HDL Model with MATLAB Testbench
The simulation runs in MATLAB until it reaches the breakpoint that you just
set. Continue the simulation/debugging session as desired.
1-57
1 HDL Cosimulation Using MATLAB Test Bench Function
> restart
The Restart dialog box appears. Leave all the options enabled, and click
Restart.
1 Stop the simulation on the client side by selecting Simulate > End
Simulation or entering the quit command.
2 Quit ModelSim.
1-58
Verify HDL Model with MATLAB Testbench
In MATLAB, you can just quit the application, which will shut down the
simulation and also close MATLAB.
To shut down the server without closing MATLAB, you have the option of
calling hdldaemon with the 'kill' option:
hdldaemon('kill')
The following message appears, confirming that the server was shut down:
1-59
1 HDL Cosimulation Using MATLAB Test Bench Function
1-60
Automatic Cosimulation Verification
3 Select Generate HDL test bench to instruct HDL Coder to generate HDL
test bench code from your MATLAB test script (optional).
4 Select Log outputs for comparison plots if you would like to log and
plot outputs of the reference design function and HDL simulator (optional).
5 For Cosimulate for use with, select either Mentor Graphics ModelSim
or Cadence Incisive as the HDL simulator you want for cosimulation.
6 For HDL simulator run mode in cosimulation, select Batch mode for
non-interactive simulation. Select GUI mode to view waverforms.
8 For Advanced Options, select and set the optional parameters according
to the descriptions in the following table.
Parameter Description
Clock high time (ns) Specify the number of nanoseconds
the clock is high.
Clock low time (ns) Specify the number of nanoseconds
the clock is low.
Hold time (ns) Specify the hold time for input
signals and forced reset signals.
Clock enable delay (in clock Specify time (in clock cycles)
cycles) between deassertion of reset and
assertion of clock enable.
Reset length (in clock cycles) Specify time (in clock cycles)
between assertion and deassertion
of reset.
9 Optionally, select Skip this step if you don’t want to verify with
cosimulation.
10 Click Run.
1-61
1 HDL Cosimulation Using MATLAB Test Bench Function
If there are errors, those messages appear in the message pane. Correct
any errors and click Run.
1-62
2
The following figure shows how an HDL simulator wraps around a MATLAB
component function and how MATLAB communicates with the HDL
simulator during a component simulation session.
When linked with MATLAB, the HDL simulator functions as the client, with
MATLAB as the server. The following figure shows a multiple-client scenario
connecting to the server at TCP/IP socket port 4449.
2-2
MATLAB Function as a Component
MATLAB
HDL Simulator Link Server
Port
Client 4449
2-3
2 HDL Cosimulation Using MATLAB Component Function
5 Launch HDL simulator for use with MATLAB and load HDL Verifier
libraries. See “Start HDL Simulator” on page 2-15
6 Bind HDL instance with component function using matlabcp. See “Bind
Component Function Calls With matlabcp” on page 2-16.
2-4
Code HDL Modules for Visualization Using MATLAB
The process for coding HDL modules for MATLAB visualization is as follows:
2-5
2 HDL Cosimulation Using MATLAB Component Function
2-6
Code HDL Modules for Visualization Using MATLAB
Note If you use unsupported types, the HDL Verifier software issues a
warning and ignores the port at run time. For example, if you define your
interface with five ports, one of which is a VHDL access port, at run time,
then the interface displays a warning and your code sees only four ports.
The interface also supports all subtypes and arrays of the preceding types.
Note The HDL Verifier software does not support VHDL extended identifiers
for the following components:
2-7
2 HDL Cosimulation Using MATLAB Component Function
• reg
• integer
• wire
Note HDL Verifier software does not support Verilog escaped identifiers for
port and signal names used in cosimulation. However, it does support simple
identifiers for Verilog.
You have the option of invoking the compiler from menus in the ModelSim
graphic interface or from the command line with the vcom command. The
following sequence of ModelSim commands creates and maps the design
library work and compiles the VHDL file modsimrand.vhd:
The following sequence of ModelSim commands creates and maps the design
library work and compiles the Verilog file test.v:
2-8
Code HDL Modules for Visualization Using MATLAB
Note You should provide read/write access to the signals that are connecting
to the MATLAB session for cosimulation. For higher performance, you
want to provide access only to those signals used in cosimulation. You can
check read/write access through the HDL simulator—see HDL simulator
documentation for details.
The Cadence Incisive simulator allows for 1-step and 3-step processes for HDL
compilation, elaboration, and simulation. The following Cadence Incisive
simulator command compiles the Verilog file test.v:
Note You should provide read/write access to the signals that are connecting
to the MATLAB session for cosimulation. The previous example shows
how to provide read/write access to all signals in your design. For higher
performance, you want to provide access only to those signals used in
cosimulation. See the description of the +access flag to ncverilog and the
-access argument to ncelab for details.
For more examples, see the HDL Verifier tutorials and demos. For details on
using the HDL compiler, see the simulator documentation.
2-9
2 HDL Cosimulation Using MATLAB Component Function
1 Learn the syntax for a MATLAB HDL Verifier component function (see
“Syntax of a Component Function” on page 2-11.).
2 Understand how HDL Verifier software converts data from the HDL
simulator for use in the MATLAB environment (see “Data Type
Conversions” on page 8-65).
3 Choose a name for the MATLAB component function (see “Bind Component
Function Calls With matlabcp” on page 2-16).
5 Determine the types of port data being passed into the function (see
“MATLAB Function Syntax and Function Argument Definitions” on page
8-40).
2-10
Create an HDL Verifier™ MATLAB® Component Function
Initialize the function outputs to empty values at the beginning of the function
as in the following example:
tnext = [];
oport = struct();
2-11
2 HDL Cosimulation Using MATLAB Component Function
which MyVhdlFunction
/work/incisive/MySym/MyVhdlFunction.m
If the specified function is on the search path, which displays the complete
path to the function. If the function is not on the search path, which informs
you that the file was not found.
2-12
Start Connection to HDL Simulator
1 Start MATLAB.
See hdldaemon reference documentation for when and how to specify property
name/property value pairs and for more examples of using hdldaemon.
The communication mode that you specify (shared memory or TCP/IP sockets)
must match what you specify for the communication mode when you initialize
the HDL simulator for use with a MATLAB cosimulation session using the
matlabtb or matlabcp function. In addition, if you specify TCP/IP socket
mode, the socket port that you specify with hdldaemon and matlabtb or
matlabcp must match. See “TCP/IP Socket Ports” on page 8-95 for more
information .
2-13
2 HDL Cosimulation Using MATLAB Component Function
Note You cannot begin an HDL Verifier transaction between MATLAB and
the HDL simulator from MATLAB. The MATLAB server simply responds to
function call requests that it receives from the HDL simulator.
2-14
Start HDL Simulator
>>vsim
You can call vsim or nclaunch with additional parameters; see the reference
pages for details.
You must make sure the HDL simulator executables — also called vsim
(ModelSim) and nclaunch (Cadence Incisive) — are on the system path. See
your system documentation for instruction on setting environment variables.
Linux Users Make sure the HDL simulator executable is still on the system
path after the shell is launched from MATLAB. If it is not, make sure the
shell startup file does not remove it from the path environment variable.
hdlsimmatlab work.osc_top
This command loads the HDL Verifier library, opens a simulation workspace
for osc_top, and display a series of messages in the HDL simulator command
window as the simulator loads the entity (see example for remaining code).
2-15
2 HDL Cosimulation Using MATLAB Component Function
For instructions in issuing the matlabcp command, see “Run MATLAB Test
Bench Simulation” on page 1-32.
The rules stated in this section apply to signal/port and module path
specifications for MATLAB cosimulation sessions. Other specifications may
work but the HDL Verifier software does not officially recognize nor support
them.
2-16
Bind Component Function Calls With matlabcp
Path Specifications for MATLAB Link Sessions with Verilog Top Level.
The following examples show valid signal and module path specifications:
top.port_or_sig
/top/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
Path Specifications for MATLAB Link Sessions with VHDL Top Level.
• The path specification can include the top-level module name, but you do
not have to include it.
2-17
2 HDL Cosimulation Using MATLAB Component Function
• The path specification can include "." or "/" path delimiters, but it cannot
include mixed delimiters.
• The leaf module or signal must match the HDL language of the top-level
module.
The following examples show valid signal and module path specifications:
top.port_or_sig
/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
2-18
Bind Component Function Calls With matlabcp
For more information on the -mfunc argument and for a full list of matlabtb
parameters, see the matlabtb function reference.
The matlabtb command instructs the HDL simulator to call back the
inverter_tb function when inverter_vl executes in the simulation.
When the HDL simulator calls the oscfilter callback, the function knows to
operate on the model osc_top.u_osc_filter.
2-19
2 HDL Cosimulation Using MATLAB Component Function
The two types of scheduling are not mutually exclusive. You can combine
the matlabtb or matlabcp timing arguments and the tnext parameter of a
MATLAB function to schedule test bench or component session callbacks.
2-20
Schedule Options for a Component Session
You can set the value of tnext to a value of type double or int64. Specify
double to express the callback time in seconds. For example, to schedule
a callback in 1 ns, specify::
tnext = 1e-9
tnext=int64(100)
2-21
2 HDL Cosimulation Using MATLAB Component Function
Note The tnext parameter represents time from the start of the simulation.
Therefore, tnext must always be greater than tnow. If it is less, the software
does not schedule a callback.
For more information on tnext and the function prototype, see “MATLAB
Function Syntax and Function Argument Definitions” on page 8-40.
tnext = [];
.
.
.
tnext = tnow+1e-9;
Using tnext you can dynamically decide the callback scheduling based on
criteria specific to the operation of the test bench. For example, you can decide
to stop scheduling callbacks when a data signal has a certain value:
if qsum == 17,
qsum = 0;
disp('done');
tnext = []; % suspend callbacks
testisdone = 1;
return;
end
2-22
Schedule Options for a Component Session
The following assignment statement sets the timing parameter tnext. This
parameter schedules the next callback to the MATLAB component function,
relative to the current simulation time (tnow).
The function returns a new value for tnext each time the HDL simulator
calls the function.
2-23
2 HDL Cosimulation Using MATLAB Component Function
3 “Apply Stimuli to Test Bench Session with force Command” on page 1-37
hdldaemon('status')
2-24
Run MATLAB Component Function Simulation
The function displays a message that indicates whether the server is running
and, if it is running, the number of connections it is handling. For example:
• “Cosimulation with MATLAB Using the HDL Simulator GUI” on page 1-33
• “Cosimulation with MATLAB Using the Command Line Interface (CLI)”
on page 1-35
• “Cosimulation with MATLAB Using Batch Mode” on page 1-36
1 Set breakpoints in the HDL and MATLAB code to verify and analyze
simulation progress.
How you set breakpoints in the HDL simulator will vary depending on
what simulator application you are using.
In MATLAB, there are several ways you can set breakpoints; for example,
by using the Set/Clear Breakpoint button on the toolbar.
2-25
2 HDL Cosimulation Using MATLAB Component Function
When you begin a specific test bench or component session, you specify
parameters that identify the following information:
• The mode and, if applicable, TCP/IP data for connecting to a MATLAB
server (see matlabtb reference)
• The MATLAB function that is associated with and executes on behalf
of the HDL instance (see “Bind HDL Module Component to MATLAB
Test Bench Function” on page 1-26)
• Timing specifications and other control data that specifies when the
module’s MATLAB function is to be called (see “Schedule Options for a
Test Bench Session” on page 1-28).
For example:
The run command offers a variety of options for applying control over how
a simulation runs (refer to your HDL simulator documentation for details).
For example, you can specify that a simulation run for several time steps.
The following command instructs the HDL simulator to run the loaded
simulation for 50000 time steps:
run 50000
How you step through the simulation in the HDL simulator will vary
depending on what simulator application you are using.
In MATLAB, there are several ways you can step through code; for
example, by clicking the Step toolbar button.
5 When you block execution of the MATLAB function, the HDL simulator
also blocks and remains blocked until you clear all breakpoints in the
function’s code.
2-26
Run MATLAB Component Function Simulation
How you resume the simulation in the HDL simulator will vary depending
on what simulator application you are using.
In MATLAB, there are several ways you can resume the simulation; for
example, by clicking the Continue toolbar button.
run -continue
To use the CLI, specify "CLI" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command.
The Tcl command you build to pass to the HDL simulator launch command
must contain the run command or no cosimulation will take place.
Caution Close the terminal window by entering "quit -f" at the command
prompt. Do not close the terminal window by clicking the "X" in the upper
right-hand corner. This causes a memory-type error to be issued from the
system. This is not a bug with HDL Verifier but just the way the HDL
simulator behaves in this context.
You can type CTRL+C to interrupt and terminate the simulation in the HDL
simulator but this action also causes the memory-type error to be displayed.
2-27
2 HDL Cosimulation Using MATLAB Component Function
Issue the nclaunch command with "CLI" as the runmode property value, as
follows (example entered into the MATLAB editor):
nclaunch('tclstart',tclcmd,'runmode','CLI');
Issue the vsim command with "CLI" as the runmode property value, as follows
(example entered into the MATLAB editor):
vsim('tclstart',tclcmd,'runmode','CLI');
2-28
Run MATLAB Component Function Simulation
To use the batch mode, specify "Batch" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command. After you
issue the HDL Verifier HDL simulator launch command with batch mode
specified, start the simulation in Simulink. To stop the HDL simulator before
the simulation is completed, issue the breakHdlSim command.
nclaunch('tclstart',manchestercmds,'runmode','Batch')
You can also set runmode to "Batch with Xterm", which starts the HDL
simulator in the background but shows the session in an Xterm.
Issue the vsim command with "Batch" as the runmode parameter, as follows:
>> vsim('tclstart',manchestercmds,'runmode','Batch')
Other ways to apply stimuli include issuing force commands in the HDL
simulator main window (for ModelSim, you can also use the Edit > Clock
option in the ModelSim Signals window).
• Incisive
2-29
2 HDL Cosimulation Using MATLAB Component Function
• ModelSim
1
0
...
t 0 5 10 20 30
For example,
2-30
Run MATLAB Component Function Simulation
1 Make the HDL simulator your active window, if your input focus was not
already set to that application.
2 Reload HDL design elements and reset the simulation time to zero.
2-31
2 HDL Cosimulation Using MATLAB Component Function
1 Make the HDL simulator your active window, if your input focus was not
already set to that application.
2 Halt the simulation. You must quit the simulation at the HDL simulator
side or MATLAB may hang until the simulator is quit.
4 Exit the HDL simulator, if you are finished with the application.
5 Quit MATLAB, if you are finished with the application. If you want to
shut down the server manually, stop the server by calling hdldaemon with
the 'kill' option:
hdldaemon('kill')
For more information on closing HDL simulator sessions, see the HDL
simulator documentation.
2-32
3
The easiest way to create a test bench System object is by using existing
HDL code and the HDL Cosimulation Wizard. You can also create an HDL
Cosimulation System object manually. In the following section,“Verify Viterbi
Decoder Using MATLAB System Object and Mentor Graphics ModelSim” on
page 3-3, you will find an example of how to use the HDL Cosimulation System
object and ModelSim to cosimulate a Viterbi decoder implanted in VHDL.
You can find out more about the HDL Cosimulation Wizard and creating
System objects within these topics:
• “Import HDL Code With the HDL Cosimulation Wizard” on page 7-2
This chapter contains an example for converting existing HDL Code to a
System object test bench using the HDL Cosimulation Wizard.
• General information about System objects:
- “Create System Objects” on page 9-2
- “Set Up System Objects” on page 9-4
- “Process Data Using System Objects” on page 9-7
- “Tuning System object Properties in MATLAB” on page 9-10
You can also refer to the section on “Find Help and Examples for System
Objects” on page 9-12 for more general assistance.
3-2
Verify Viterbi Decoder Using MATLAB System Object and Mentor Graphics ModelSim
% Convolution Encoder
hConEnc = comm.ConvolutionalEncoder;
% BPSK Modulator
hMod = comm.BPSKModulator;
% AWGN channel
hChan = comm.AWGNChannel('NoiseMethod', ...
'Signal to noise ratio (Es/No)',...
'SamplesPerSymbol',1,...
'EsNo',EsNo);
% BPSK demodulator
hDemod = comm.BPSKDemodulator('DecisionMethod','Log-likelihood ratio',...
'Variance',0.5*10^(-EsNo/10));
% Error Rate Calculator
hError = comm.ErrorRate('ComputationDelay',100,'ReceiveDelay', 58);
3-3
3 HDL Cosimulation Using MATLAB System Object
Run Cosimulation
3-4
Verify Viterbi Decoder Using MATLAB System Object and Mentor Graphics ModelSim
The HDL simulator is unblocked when the HDL cosimulation system object is
destroyed in MATLAB. Close the ModelSim session manually.
clear hDec;
% This concludes the "Verifying Viterbi Decoder Using MATLAB System Object
% and ModelSim" example.
3-5
3 HDL Cosimulation Using MATLAB System Object
3-6
4
Link
HDL Simulator Request Simulink
In Out Client
Server Response
Out In
HDL Simulator
Server
Port Link
4449 Simulink
Link Client
Port
4448
HDL Simulator
Server
4-2
Simulink as a Test Bench
When you link the HDL simulator with a Simulink application, the simulator
functions as the server. Using the HDL Verifier communications interface,
an HDL Cosimulation block cosimulates a hardware component by applying
input signals to and reading output signals from an HDL model under
simulation in the HDL simulator.
• Frequency Error Range block, Frequency Error Slider block, and Phase
Event block
• Manchester encoder subsystem
• Data alignment subsystem
• Inphase/Quadrature (I/Q) capture subsystem
• Error Rate Calculation block from the Communications System Toolbox™
software
• Bit Errors block
4-3
4 Simulink Test Bench for HDL Component
For information on getting started with Simulink software, see the Simulink
online help or documentation.
If you need to use a signal that has multiple drivers and it is resolved (for
example, it is of VHDL type STD_LOGIC) , Simulink applies the resolution
function at each time step defined by the signal’s Simulink sample rate.
Depending on the other drivers, the Simulink value may or may not get
applied. Furthermore, Simulink has no control over signal changes that occur
between its sample times.
Note Verify that signals used in cosimulation have read/write access. You
can check read/write access through the HDL simulator—see HDL simulator
documentation for details.
This rule applies to all signals on the Ports, Clocks, and Simulation panes
and to signals added to the model in any other manner.
4-4
Simulink as a Test Bench
The HDL Cosimulation block also lets you specify an independent sample
time for each output port. You must explicitly set the sample time for each
output port, or accept the default. Using this setting lets you control the
rate at which Simulink updates an output port by reading the corresponding
signal from the HDL simulator.
You can link Simulink and the HDL simulator in two possible ways:
The block mask contains panels for entering port and signal information,
setting communication modes, adding clocks (Incisive and ModelSim only),
specifying pre- and post-simulation Tcl commands (Incisive and ModelSim
only), and defining the timing relationship.
After you code one of your model’s components in VHDL or Verilog and
simulate it in the HDL simulator environment, you integrate the HDL
representation into your Simulink model as an HDL Cosimulation block.
There is one block for each supported HDL simulator. These blocks are
located in the Simulink Library, within the HDL Verifier block library. As
an example, the block for use with Mentor Graphics ModelSim is shown in
the next figure.
4-5
4 Simulink Test Bench for HDL Component
• Ports Pane: Block input and output ports that correspond to signals,
including internal signals, of your HDL design, and an output sample time.
• Connection Pane: Type of communication and related settings to be used
for exchanging data between simulators.
• Timescales Pane: The timing relationship between Simulink software
and the HDL simulator.
• Clocks Pane (Incisive and ModelSim only): Optional rising-edge and
falling-edge clocks to apply to your model.
• Simulation Pane (Incisive and ModelSim only): Tcl commands to run
before and after a simulation.
For more detail on each of these panes, see the HDL Cosimulation reference
page.
4-6
Simulink Test Bench Cosimulation
1 Create Simulink model. See “Create Simulink Model for Test Bench
Cosimulation” on page 4-8.
3 Start HDL simulator for use with MATLAB and Simulink and load HDL
Verifier libraries. See “Start HDL Simulator” on page 4-12
4 Add HDL Cosimulation block. See “Add HDL Cosimulation Block to Model”
on page 4-14.
4-7
4 Simulink Test Bench for HDL Component
4-8
Code an HDL Component
4-9
4 Simulink Test Bench for HDL Component
• reg
• integer
• wire
Note HDL Verifier software does not support Verilog escaped identifiers for
port and signal names used in cosimulation. However, it does support simple
identifiers for Verilog.
The interface also supports all subtypes and arrays of the preceding types.
4-10
Code an HDL Component
Note The HDL Verifier software does not support VHDL extended identifiers
for the following components:
Port Data Types for Verilog Entities. In your module definition, you must
define each port that you plan to test with MATLAB with a Verilog port
data type that is supported by the HDL Verifier software. The interface can
convert data of the following Verilog port types to comparable MATLAB types:
• reg
• integer
• wire
Note HDL Verifier software does not support Verilog escaped identifiers for
port and signal names used in cosimulation. However, it does support simple
identifiers for Verilog.
4-11
4 Simulink Test Bench for HDL Component
>>vsim
Note that if both tools (MATLAB and the HDL simulator) are not running on
the same system, you must start the HDL simulator manually and load the
HDL Verifier libraries yourself. See “HDL Verifier Libraries” on page 8-11.
You can call vsim or nclaunch with additional parameters; see the reference
pages for details.
You must make sure the HDL simulator executables — also called vsim
(ModelSim) and nclaunch (Cadence Incisive) — are on the system path. See
your system documentation for instruction on setting environment variables.
Linux Users Make sure the HDL simulator executable is still on the system
path after the shell is launched from MATLAB. If it is not, make sure the
shell startup file does not remove it from the path environment variable.
4-12
Start HDL Simulator
After you start the HDL simulator from MATLAB, load an instance of an
HDL module for cosimulation with the function hdlsimulink. Issue the
command for each instance of an HDL module in your model that you want to
cosimulate.
For example:
hdlsimulink work.manchester
After you start the HDL simulator from MATLAB, load an instance of an HDL
module for cosimulation with the function vsimulink. Issue the command for
each instance of an HDL module in your model that you want to cosimulate.
For example:
vsimulink work.manchester
4-13
4 Simulink Test Bench for HDL Component
2 Delete the model component that the HDL Cosimulation block is to replace.
3 In the Simulink Library Browser, click the HDL Verifier block library. You
can then select the block library for your supported HDL simulator. Select
either the Mentor Graphics® ModelSim HDL Cosimulation block, or the
Cadence Incisive HDL Cosimulation block, as shown below.
4-14
Add HDL Cosimulation Block to Model
4 Copy the HDL Cosimulation block icon from the Library Browser to your
model. Simulink creates a link to the block at the point where you drop
the block icon.
4-15
4 Simulink Test Bench for HDL Component
4-16
Define HDL Cosimulation Block Interface
The first step to configuring your HDL Verifier Cosimulation block is to map
signals and signal instances of your HDL design to port definitions in your
HDL Cosimulation block. In addition to identifying input and output ports,
4-17
4 Simulink Test Bench for HDL Component
you can specify a sample time for each output port. You can also specify a
fixed-point data type for each output port.
The signals that you map can be at any level of the HDL design hierarchy.
To map the signals, you can perform either of the following actions:
• Enter signal information manually into the Ports pane of the HDL
Cosimulation Block Parameters dialog box (see “Enter Signal Information
Manually” on page 4-26). This approach can be more efficient when
you want to connect a small number of signals from your HDL model
to Simulink.
• Use the Auto Fill button to have the HDL Cosimulation block obtain
signal information for you by transmitting a query to the HDL simulator.
This approach can save significant effort when you want to cosimulate
an HDL model that has many signals that you want to connect to your
Simulink model. However, in some cases, you will need to edit the signal
data returned by the query. See “Get Signal Information from HDL
Simulator” on page 4-20 for details.
Note Verify that signals used in cosimulation have read/write access. For
higher performance, you want to provide access only to those signals used
in cosimulation. This rule applies to all signals on the Ports, Clocks, and
Simulation panes, and to all signals added in any other manner.
HDL designs generally do have hierarchy; that is the reason for this syntax.
This specification does not represent a file name hierarchy.
Path specifications must follow the rules listed in the following sections:
4-18
Define HDL Cosimulation Block Interface
The following examples show valid signal and module path specifications:
top.port_or_sig
/top/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
• Path specification may include the top-level module name but it is not
required.
4-19
4 Simulink Test Bench for HDL Component
• Path specification can include "." or "/" path delimiters, but cannot include
a mixture.
• The leaf module or signal must match the HDL language of the top-level
module.
The following examples show valid signal and module path specifications:
top.port_or_sig
/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
4-20
Define HDL Cosimulation Block Interface
1 Open the block parameters dialog box for the HDL Cosimulation block.
Click the Ports tab. The Ports pane opens (as an example, the Ports
pane for the HDL Cosimulation block for use with ModelSim is shown
in the illustrations below).
4-21
4 Simulink Test Bench for HDL Component
Tip Delete all ports before performing Auto Fill to make sure that no
unused signal remains in the Ports list at any time.
2 Click the Auto Fill button. The Auto Fill dialog box opens.
3 In this example, the Auto Fill feature obtains port data for a
VHDL component called manchester. The HDL path is specified as
/top/manchester (path specifications will vary depending on your
HDL simulator; see “Specify HDL Signal/Port and Module Paths for
Cosimulation” on page 4-18).
5 After the HDL simulator returns the port data, the Auto Fill feature enters
it into the Ports pane, as shown in the following figure (examples shown
for use with Cadence Incisive).
4-22
Define HDL Cosimulation Block Interface
7 Delete unused signals from Ports pane and add Clock signal.
The preceding figure shows that the query entered clock, clock enable, and
reset ports (labeled clk, enable, and reset respectively) into the ports list.
Delete the enable and reset signals from the Ports pane, and add the clk
signal in the Clocks pane.
4-23
4 Simulink Test Bench for HDL Component
4-24
Define HDL Cosimulation Block Interface
• Sample time: 1
• Data type: Inherit
• Fraction length: Inherit
You may need to change these values as required by your model. In this
example, the Sample time should be set to 10 for all outputs. See also
“Specify Signal Data Types” on page 4-32.
9 Before closing the HDL Cosimulation block parameters dialog box, click
Apply to commit any edits you have made.
Observe that Auto Fill returned information about all inputs and outputs
for the targeted component. In many cases, this will include signals that
function in the HDL simulator but cannot be connected in the Simulink
model. You may delete any such entries from the list in the Ports pane if
they are unwanted. You can drive the signals from Simulink; you just have to
define their values by laying down Simulink blocks.
4-25
4 Simulink Test Bench for HDL Component
Note that Auto Fill does not return information for internal signals. If your
Simulink model needs to access such signals, you must enter them into the
Ports pane manually. For example, in the case of the Manchester Receiver
model, you would need to add output port entries for top/manchester/sync_i,
top/manchester/isum_i, and top/manchester/qsum_i, as shown in step 8.
Incisive and ModelSim users: Note that clk, reset, and clk_enable may be
in the Clocks and Simulation panes but they don’t have to be. These signals
can be ports if you choose to drive them explicitly from Simulink.
Note When you import VHDL signals using Auto Fill, the HDL simulator
returns the signal names in all capitals.
1 In the HDL simulator, determine the signal path names for the HDL
signals you plan to define in your block. For example, in the ModelSim
simulator, the following wave window shows all signals are subordinate to
the top-level module manchester.
4-26
Define HDL Cosimulation Block Interface
2 In Simulink, open the block parameters dialog box for your HDL
Cosimulation block, if it is not already open.
3 Select the Ports pane tab. Simulink displays the following dialog box
(example shown for use with Incisive).
4-27
4 Simulink Test Bench for HDL Component
In this pane, you define the HDL signals of your design that you want to
include in your Simulink block and set a sample time and data type for
output ports. The parameters that you should specify on the Ports pane
depend on the type of device the block is modeling as follows:
• For a device having both inputs and outputs: specify block input ports,
block output ports, output sample times and output data types.
For output ports, accept the default or enter an explicit sample time.
Data types can be specified explicitly, or set to Inherit (the default). In
the default case, the output port data type is inherited either from the
signal connected to the port, or derived from the HDL model.
• For a sink device: specify block output ports.
• For a source device: specify block input ports.
4-28
Define HDL Cosimulation Block Interface
4 Enter signal path names in the Full HDL name column by double-clicking
on the existing default signal.
• Use HDL simulator path name syntax (as described in “Specify HDL
Signal/Port and Module Paths for MATLAB Test Bench Cosimulation”
on page 1-24).
• If you are adding signals, click New and then edit the default values.
Select either Input or Output from the I/O Mode column.
• If you want to, set the Sample Time, Data Type, and Fraction Length
parameters for signals explicitly, as discussed in the remaining steps.
When you have finished editing clock signals, click Apply to register your
changes with Simulink.
The following dialog box shows port definitions for an HDL Cosimulation
block. The signal path names match path names that appear in the HDL
simulator wave window (Incisive example shown).
4-29
4 Simulink Test Bench for HDL Component
Note When you define an input port, make sure that only one source is
set up to force input to that port. If multiple sources drive a signal, your
Simulink model may produce unpredictable results.
5 You must specify a sample time for the output ports. Simulink uses the
value that you specify, and the current settings of the Timescales pane,
to calculate an actual simulation sample time.
4-30
Define HDL Cosimulation Block Interface
6 You can configure the fixed-point data type of each output port explicitly
if desired, or use a default (Inherited). In the default case, Simulink
determines the data type for an output port as follows:
If Simulink can determine the data type of the signal connected to the
output port, it applies that data type to the output port. For example,
the data type of a connected Signal Specification block is known by
back-propagation. Otherwise, Simulink queries the HDL simulator to
determine the data type of the signal from the HDL module.
For example, if the model has an 8-bit signal with Signed data type and
a Fraction Length of 5, the HDL Cosimulation block assigns it the
data type sfix8_En5. If the model has an Unsigned 16-bit signal with no
fractional part (a Fraction Length of 0), the HDL Cosimulation block
assigns it the data type ufix16.
7 Before closing the dialog box, click Apply to register your edits.
4-31
4 Simulink Test Bench for HDL Component
For more about the direct feedthrough feature, see “Direct Feedthrough
Cosimulation” on page 8-46.
4-32
Define HDL Cosimulation Block Interface
4-33
4 Simulink Test Bench for HDL Component
4-34
Define HDL Cosimulation Block Interface
4-35
4 Simulink Test Bench for HDL Component
1 Determine whether Simulink and the HDL simulator are running on the
same computer. If they are, skip to step 4.
4-36
Define HDL Cosimulation Block Interface
3 Enter the host name of the computer that is running your HDL simulation
(in the HDL simulator) in the Host name text field. In the Port number
or service text field, specify a valid port number or service for your
computer system. For information on choosing TCP/IP socket ports, see
“TCP/IP Socket Ports” on page 8-95. Skip to step 5.
4 If the HDL simulator and Simulink are running on the same computer,
decide whether you are going to use shared memory or TCP/IP sockets for
the communication channel. For information on the different modes of
communication, see “HDL Cosimulation with MATLAB or Simulink”.
5 If you want to bypass the HDL simulator when you run a Simulink
simulation, use the Connection Mode options to specify what type of
simulation connection you want. Select one of the following options:
• Full Simulation: Confirm interface and run HDL simulation (default).
• Confirm Interface Only: Check HDL simulator for expected signal
names, dimensions, and data types, but do not run HDL simulation.
• No Connection: Do not communicate with the HDL simulator. The
HDL simulator does not need to be started.
With the second and third options, HDL Verifier software does not
communicate with the HDL simulator during Simulink simulation.
6 Click Apply.
4-37
4 Simulink Test Bench for HDL Component
4-38
Define HDL Cosimulation Block Interface
Note for ModelSim Users After each simulation, it takes ModelSim time
to update the coverage result. To prevent the potential conflict between this
process and the next cosimulation session, add a short pause between each
successive simulation.
1 Select the Simulation tab of the Block Parameters dialog box. The dialog
box appears as follows (example shown for use with ModelSim).
4-39
4 Simulink Test Bench for HDL Component
ModelSim DO Files
Alternatively, you can create a ModelSim DO file that lists Tcl commands
and then specify that file with the ModelSim do command as shown in
the following figure.
4-40
Define HDL Cosimulation Block Interface
3 Click Apply.
4-41
4 Simulink Test Bench for HDL Component
The HDL Cosimulation block does not have any tunable parameters; thus,
you get an error if you try to change a value while the simulation is running.
However, it does have a few evaluated parameters.
You can see the list of parameters and their attributes by performing
a right-mouse click on the block, selecting View Mask, and then the
Parameters tab. The Variable column shows the programmatic parameter
names. Alternatively, you can get the names programmatically by selecting
the HDL Cosimulation block and then typing the following commands at
the MATLAB prompt:
• In the model workspace, for example, View > Model Explorer > Simulink
Root > model_name > Model Workspace, option Data Source is set
to Model File.
• In a model callback, for example, File > Model Properties > Callbacks.
• A subsystem callback (right-mouse click on an empty subsystem and then
select Properties > Callbacks). Many of the HDL Verifier demos use
this technique to start the HDL simulator by placing MATLAB code in
the OpenFcn callback.
• The HDL Cosimulation block callback (right-mouse click on HDL
Cosimulation block, and then select Properties > Callbacks).
4-42
Define HDL Cosimulation Block Interface
collisions with other simulation runs. This example shows code that could
handle that task. The script is for a 32-bit Linux platform.
4-43
4 Simulink Test Bench for HDL Component
You can adjust the parameters individually or you can use the MATLAB
file dspstartup, which lets you automate the configuration process so that
every new model that you create is preconfigured with the following relevant
parameter settings:
4-44
Run a Test Bench Cosimulation Session
4-45
4 Simulink Test Bench for HDL Component
For more information on using and customizing dspstartup, see the DSP
System Toolbox™ documentation. For more information about automating
tasks at startup, see the description of the startup command in the MATLAB
documentation.
The MATLAB command pingHdlSim can also be used to check the connection
status. If a -1 is returned, then there is no connection with the HDL simulator.
• “Cosimulation Using the Simulink and HDL Simulator GUIs” on page 4-46
• “Cosimulation with Simulink Using the Command Line Interface (CLI)”
on page 4-47
• “Cosimulation with Simulink Using Batch Mode” on page 4-48
4-46
Run a Test Bench Cosimulation Session
model and displays any errors that it detects. You can alternate between the
HDL simulator and Simulink GUIs to monitor the cosimulation results.
You can specify "GUI" as the property value for the run mode parameter of
the HDL Verifier HDL simulator launch command, but since using the GUI is
the default mode for HDL Verifier, you do not have to.
To use the CLI, specify "CLI" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command.
Caution Close the terminal window by entering "quit -f" at the command
prompt. Do not close the terminal window by clicking the "X" in the upper
right-hand corner. This causes a memory-type error to be issued from the
system. This is not a bug with HDL Verifier but just the way the HDL
simulator behaves in this context.
You can type CTRL+C to interrupt and terminate the simulation in the HDL
simulator but this action also causes the memory-type error to be displayed.
Issue the nclaunch command with "CLI" as the runmode property value, as
follows (example entered into the MATLAB editor):
4-47
4 Simulink Test Bench for HDL Component
};
nclaunch('tclstart',tclcmd,'runmode','CLI');
Issue the vsim command with "CLI" as the runmode property value, as follows
(example entered into the MATLAB editor):
vsim('tclstart',tclcmd,'runmode','CLI');
To use the batch mode, specify "Batch" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command. After you
issue the HDL Verifier HDL simulator launch command with batch mode
specified, start the simulation in Simulink. To stop the HDL simulator before
the simulation is completed, issue the breakHdlSim command.
nclaunch('tclstart',manchestercmds,'runmode','Batch')
You can also set runmode to "Batch with Xterm", which starts the HDL
simulator in the background but shows the session in an Xterm.
4-48
Run a Test Bench Cosimulation Session
Issue the vsim command with "Batch" as the runmode parameter, as follows:
>> vsim('tclstart',manchestercmds,'runmode','Batch')
Test Cosimulation
If you wish to reset a clock during a cosimulation, you can do so in one of
these ways:
If you change any part of the Simulink model, including the HDL
Cosimulation block parameters, update the diagram to reflect those changes.
You can do this update in one of the following ways:
4-49
4 Simulink Test Bench for HDL Component
can avoid race conditions that could create differing cosimulation results. See
“Race Conditions in HDL Simulators” on page 8-62.
4-50
Verify HDL Model with Simulink Test Bench
Tutorial Overview
This chapter guides you through the basic steps for setting up an HDL
Verifier session that uses Simulink and the HDL Cosimulation block to
verify an HDL model. The HDL Cosimulation block cosimulates a hardware
component by applying input signals to and reading output signals from an
HDL model under simulation in ModelSim. The HDL Cosimulation block
supports simulation of either VHDL or Verilog models. In the tutorial in this
section, you will cosimulate a simple VHDL model.
invertercmds.m File
Included with your HDL Verifier installation is
the file invertercmds.m, located in the folder
matlabroot/toolbox/edalink/extensions/modelsim/modelsimdemos. The
returned cell array can be passed as parameters (’cmd’) to vsimulink. These
parameters, when used with the vsimulink command, launch ModelSim and
build the VHDL source file created in “Develop VHDL Code” on page 4-52.
4-51
4 Simulink Test Bench for HDL Component
Use of this file is not required. It is provided only for your convenience. You
may complete each step manually and forego using this file, if you so choose.
...10101000 sin 8
8 sout ...01010111
The VHDL entity for this model will represent 8-bit streams of input and
output signal values with an IN port and OUT port of type STD_LOGIC_VECTOR.
An input clock signal of type STD_LOGIC will trigger the bit inversion process
when set.
1 Start ModelSim
2 Change to the writable folder MyPlayArea, which you may have created for
another tutorial. If you have not created the folder, create it now. The
folder must be writable.
ModelSim>cd C:/MyPlayArea
---------------------------------------------------
-- Simulink and ModelSim Inverter Tutorial
--
-- Copyright 2003-2004 The MathWorks, Inc.
4-52
Verify HDL Model with Simulink Test Bench
--
---------------------------------------------------
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ENTITY inverter IS PORT (
sin : IN std_logic_vector(7 DOWNTO 0);
sout: OUT std_logic_vector(7 DOWNTO 0);
clk : IN std_logic
);
END inverter;
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ARCHITECTURE behavioral OF inverter IS
BEGIN
PROCESS(clk)
BEGIN
IF (clk'EVENT AND clk = '1') THEN
sout <= NOT sin;
END IF;
END PROCESS;
END behavioral;
Compile VHDL
This section explains how to set up a design library and compile
inverter.vhd, as follows:
1 Verify that the file inverter.vhd is in the current folder by entering the
ls command at the ModelSim command prompt.
4-53
4 Simulink Test Bench for HDL Component
If the design library work already exists, ModelSim does not overwrite the
current library, but displays the following warning:
Note You must use the ModelSim File menu or vlib command to create
the library folder so that the required _info file is created. Do not create
the library with operating system commands.
3 Compile the VHDL file. One way of compiling the file is to click the
file name in the project workspace and select Compile > Compile All.
Another alternative is to specify the name of the VHDL file with the vcom
command, as follows:
4-54
Verify HDL Model with Simulink Test Bench
2 Drag the following blocks from the Simulink Library Browser to your
model window:
Arrange the three blocks in the order shown in the following figure.
Next, configure the Constant block, which is the model’s input source, by
performing the following actions:
1 Double-click the Constant block icon to open the Constant block parameters
dialog box. Enter the following parameter values in the Main pane:
• Constant value: 0
• Sample time: 10
4-55
4 Simulink Test Bench for HDL Component
Later you can change these initial values to see the effect various sample
times have on different simulation runs.
2 Click the Signal Attributes tab. The dialog box now displays the Output
data type mode menu.
Select uint8 from the Output data type mode menu. This data type
specification is supported by HDL Verifier software without the need for a
type conversion. It maps directly to the VHDL type for the VHDL port sin,
STD_LOGIC_VECTOR(7 DOWNTO 0).
4-56
Verify HDL Model with Simulink Test Bench
3 Click OK. The Constant block parameters dialog box closes and the value
in the Constant block icon changes to 0.
Next, configure the HDL Cosimulation block, which represents the inverter
model written in VHDL. Start with the Ports pane, by performing the
following actions:
2 In the Ports pane, select the sample signal /top/sig1 from the signal list
in the center of the pane by double-clicking on it.
4-57
4 Simulink Test Bench for HDL Component
4 Similarly, select the sample signal /top/sig2. Change the Full HDL
Name to /inverter/sout. Select Output from the I/O Mode list. Change
the Sample Time parameter to 10. Then click Apply to update the list.
5 Select the sample signal /top/sig3. Click the Delete button. The signal is
now removed from the list.
4-58
Verify HDL Model with Simulink Test Bench
3 Select socket from the Connection method list. This option specifies
that Simulink and ModelSim will communicate via a designated TCP/IP
socket port. Observe that two additional fields, Port number or service
and Host name, are now visible.
4 In the Port number or service text box, enter socket port number 4449
or, if this port is not available on your system, another valid port number
or service name. The model will use TCP/IP socket communication to link
with ModelSim. Note what you enter for this parameter. You will specify
the same socket port information when you set up ModelSim for linking
with Simulink.
4-59
4 Simulink Test Bench for HDL Component
5 Click Apply.
2 Click the New button. A new clock signal with an empty signal name
is added to the signal list.
3 Double-click on the new signal name to edit. Enter the signal path
/inverter/clk. Then select Rising from the Edge list. Set the Period
parameter to 10.
5 Click Apply.
Next, enter some simple Tcl commands to be executed before and after
simulation, as follows:
4-60
Verify HDL Model with Simulink Test Bench
echo "Done"
4 Click Apply.
Next, view the Timescales pane to make sure it is set to its default
parameters, as follows:
2 The default settings of the Timescales pane are shown in the following
figure. These settings are required for operation of this example. See
“Simulation Timescales” on page 8-74 for further information.
4-61
4 Simulink Test Bench for HDL Component
The final step is to connect the blocks, configure model-wide parameters, and
save the model. Perform the following actions:
4-62
Verify HDL Model with Simulink Test Bench
At this point, you might also want to consider adjusting block annotations.
d Click Apply.
vsim('socketsimulink', 4449)
Note If you entered a different socket port specification when you configured
the HDL Cosimulation block in Simulink, replace the port number 4449 in
the preceding command line with the applicable socket port information for
your model. The vsim function informs ModelSim of the TCP/IP socket to use
for establishing a communication link with your Simulink model.
To launch ModelSim, you may choose instead to use the invertercmds.m file.
See the section about “invertercmds.m File” on page 4-51.
4-63
4 Simulink Test Bench for HDL Component
2 If your VHD file is not in the current folder, change your folder to the
location of your inverter.vhd file. For example:
ModelSim> cd C:/MyPlayArea
ModelSim starts the vsim simulator such that it is ready to simulate entity
inverter in the context of your Simulink model. The ModelSim command
window display should be similar to the following.
4-64
Verify HDL Model with Simulink Test Bench
Instead of loading the entity manually, you may choose to use the
invertercmds.m file. See the section about “invertercmds.m File” on page
4-51.
4-65
4 Simulink Test Bench for HDL Component
Run Simulation
This section guides you through a scenario of running and monitoring a
cosimulation session.
1 Open and add the inverter signals to a wave window by entering the
following ModelSim command:
4-66
Verify HDL Model with Simulink Test Bench
4 In the Simulink model, change Constant value to 255, save the model,
and start another simulation. The value in the Display block changes to 0
and the ModelSim wave window is updated as follows.
4-67
4 Simulink Test Bench for HDL Component
4-68
Verify HDL Model with Simulink Test Bench
2 Quit ModelSim.
4-69
4 Simulink Test Bench for HDL Component
3 Run all steps under 2, Prepare Model For HDL Code Generation.
4-70
Test Bench Automatic Verification with Simulink®
5 At step 3.3, click Run This Task. The HDL Workflow Advisor and HDL
Verifier verify the generated HDL using cosimulation between the HDL
Simulator and the Simulink test bench. Any relevant status messages are
displayed in the status window in the HDL Workflow Advisor.
4-71
4 Simulink Test Bench for HDL Component
4-72
5
5-2
Component Simulation with Simulink
If you need to use a signal that has multiple drivers and it is resolved (for
example, it is of VHDL type STD_LOGIC) , Simulink applies the resolution
function at each time step defined by the signal’s Simulink sample rate.
Depending on the other drivers, the Simulink value may or may not get
applied. Furthermore, Simulink has no control over signal changes that occur
between its sample times.
Note Verify that signals used in cosimulation have read/write access. You
can check read/write access through the HDL simulator—see HDL simulator
documentation for details.
This rule applies to all signals on the Ports, Clocks, and Simulation panes
and to signals added to the model in any other manner.
The HDL Cosimulation block also lets you specify an independent sample
time for each output port. You must explicitly set the sample time for each
output port, or accept the default. Using this setting lets you control the
rate at which Simulink updates an output port by reading the corresponding
signal from the HDL simulator.
5-3
5 Replace HDL Component with Simulink Algorithm
You can link Simulink and the HDL simulator in two possible ways:
The block mask contains panels for entering port and signal information,
setting communication modes, adding clocks (Incisive and ModelSim only),
specifying pre- and post-simulation Tcl commands (Incisive and ModelSim
only), and defining the timing relationship.
After you code one of your model’s components in VHDL or Verilog and
simulate it in the HDL simulator environment, you integrate the HDL
representation into your Simulink model as an HDL Cosimulation block.
There is one block for each supported HDL simulator. These blocks are
located in the Simulink Library, within the HDL Verifier block library. As
an example, the block for use with Mentor Graphics ModelSim is shown in
the next figure.
5-4
Component Simulation with Simulink
• Ports Pane: Block input and output ports that correspond to signals,
including internal signals, of your HDL design, and an output sample time.
• Connection Pane: Type of communication and related settings to be used
for exchanging data between simulators.
• Timescales Pane: The timing relationship between Simulink software
and the HDL simulator.
• Clocks Pane (Incisive and ModelSim only): Optional rising-edge and
falling-edge clocks to apply to your model.
• Simulation Pane (Incisive and ModelSim only): Tcl commands to run
before and after a simulation.
5-5
5 Replace HDL Component with Simulink Algorithm
1 Create, compile, and elaborate HDL design. See “Code an HDL Component”
on page 5-7.
3 Start HDL simulator for use with MATLAB and Simulink and load HDL
Verifier libraries. See “Start HDL Simulator” on page 5-11.
5-6
Code an HDL Component
5-7
5 Replace HDL Component with Simulink Algorithm
Note If you use unsupported types, the HDL Verifier software issues a
warning and ignores the port at run time. For example, if you define your
interface with five ports, one of which is a VHDL access port, at run time,
then the interface displays a warning and your code sees only four ports.
5-8
Code an HDL Component
• TIME
• Enumerated types, including user-defined enumerated types and
CHARACTER
The interface also supports all subtypes and arrays of the preceding types.
Note The HDL Verifier software does not support VHDL extended identifiers
for the following components:
Port Data Types for Verilog Modules. In your module definition, you
must define each port that you plan to test with MATLAB with a Verilog port
data type that is supported by the HDL Verifier software. The interface can
convert data of the following Verilog port types to comparable MATLAB types:
• reg
• integer
• wire
Note HDL Verifier software does not support Verilog escaped identifiers for
port and signal names used in cosimulation. However, it does support simple
identifiers for Verilog.
5-9
5 Replace HDL Component with Simulink Algorithm
Create a Simulink test bench model by adding Simulink blocks from the
Simulink Block libraries. For help with creating a Simulink model, see the
Simulink documentation.
5-10
Start HDL Simulator
>>vsim
Note that if both tools (MATLAB and the HDL simulator) are not running on
the same system, you must start the HDL simulator manually and load the
HDL Verifier libraries yourself. See “HDL Verifier Libraries” on page 8-11.
You can call vsim or nclaunch with additional parameters; see the reference
pages for details.
You must make sure the HDL simulator executables — also called vsim
(ModelSim) and nclaunch (Cadence Incisive) — are on the system path. See
your system documentation for instruction on setting environment variables.
Linux Users Make sure the HDL simulator executable is still on the system
path after the shell is launched from MATLAB. If it is not, make sure the
shell startup file does not remove it from the path environment variable.
5-11
5 Replace HDL Component with Simulink Algorithm
After you start the HDL simulator from MATLAB, load an instance of an
HDL module for cosimulation with the function hdlsimulink. Issue the
command for each instance of an HDL module in your model that you want to
cosimulate.
For example:
hdlsimulink work.manchester
After you start the HDL simulator from MATLAB, load an instance of an HDL
module for cosimulation with the function vsimulink. Issue the command for
each instance of an HDL module in your model that you want to cosimulate.
For example:
vsimulink work.manchester
5-12
Add HDL Cosimulation Block to Model
2 Delete the model component that the HDL Cosimulation block is to replace.
3 In the Simulink Library Browser, click the HDL Verifier block library. You
can then select the block library for your supported HDL simulator. Select
either the Mentor Graphics ModelSim HDL Cosimulation block, or the
Cadence Incisive HDL Cosimulation block, as shown below.
5-13
5 Replace HDL Component with Simulink Algorithm
4 Copy the HDL Cosimulation block icon from the Library Browser to your
model. Simulink creates a link to the block at the point where you drop
the block icon.
5-14
Define HDL Cosimulation Block Interface
5-15
5 Replace HDL Component with Simulink Algorithm
The first step to configuring your HDL Verifier Cosimulation block is to map
signals and signal instances of your HDL design to port definitions in your
HDL Cosimulation block. In addition to identifying input and output ports,
5-16
Define HDL Cosimulation Block Interface
you can specify a sample time for each output port. You can also specify a
fixed-point data type for each output port.
The signals that you map can be at any level of the HDL design hierarchy.
To map the signals, you can perform either of the following actions:
• Enter signal information manually into the Ports pane of the HDL
Cosimulation Block Parameters dialog box (see “Enter Signal Information
Manually” on page 4-26). This approach can be more efficient when
you want to connect a small number of signals from your HDL model
to Simulink.
• Use the Auto Fill button to have the HDL Cosimulation block obtain
signal information for you by transmitting a query to the HDL simulator.
This approach can save significant effort when you want to cosimulate
an HDL model that has many signals that you want to connect to your
Simulink model. However, in some cases, you will need to edit the signal
data returned by the query. See “Get Signal Information from HDL
Simulator” on page 4-20 for details.
Note Verify that signals used in cosimulation have read/write access. For
higher performance, you want to provide access only to those signals used
in cosimulation. This rule applies to all signals on the Ports, Clocks, and
Simulation panes, and to all signals added in any other manner.
HDL designs generally do have hierarchy; that is the reason for this syntax.
This specification does not represent a file name hierarchy.
Path specifications must follow the rules listed in the following sections:
5-17
5 Replace HDL Component with Simulink Algorithm
The following examples show valid signal and module path specifications:
top.port_or_sig
/top/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
• Path specification may include the top-level module name but it is not
required.
5-18
Define HDL Cosimulation Block Interface
• Path specification can include "." or "/" path delimiters, but cannot include
a mixture.
• The leaf module or signal must match the HDL language of the top-level
module.
The following examples show valid signal and module path specifications:
top.port_or_sig
/sub/port_or_sig
top
top/sub
top.sub1.sub2
The following examples show invalid signal and module path specifications:
• top.sub/port_or_sig
Why this specification is invalid: You cannot use mixed delimiters.
• :sub:port_or_sig
:
:sub
Why this specification is invalid: When you use VHDL-specific delimiters
you limit the interoperability with paths when moving between HDL
simulators and between VHDL and Verilog.
5-19
5 Replace HDL Component with Simulink Algorithm
1 Open the block parameters dialog box for the HDL Cosimulation block.
Click the Ports tab. The Ports pane opens (as an example, the Ports
pane for the HDL Cosimulation block for use with ModelSim is shown
in the illustrations below).
5-20
Define HDL Cosimulation Block Interface
Tip Delete all ports before performing Auto Fill to make sure that no
unused signal remains in the Ports list at any time.
2 Click the Auto Fill button. The Auto Fill dialog box opens.
3 In this example, the Auto Fill feature obtains port data for a
VHDL component called manchester. The HDL path is specified as
/top/manchester (path specifications will vary depending on your
HDL simulator; see “Specify HDL Signal/Port and Module Paths for
Cosimulation” on page 4-18).
5 After the HDL simulator returns the port data, the Auto Fill feature enters
it into the Ports pane, as shown in the following figure (examples shown
for use with Cadence Incisive).
5-21
5 Replace HDL Component with Simulink Algorithm
7 Delete unused signals from Ports pane and add Clock signal.
The preceding figure shows that the query entered clock, clock enable, and
reset ports (labeled clk, enable, and reset respectively) into the ports list.
Delete the enable and reset signals from the Ports pane, and add the clk
signal in the Clocks pane.
5-22
Define HDL Cosimulation Block Interface
5-23
5 Replace HDL Component with Simulink Algorithm
• Sample time: 1
• Data type: Inherit
• Fraction length: Inherit
You may need to change these values as required by your model. In this
example, the Sample time should be set to 10 for all outputs. See also
“Specify Signal Data Types” on page 4-32.
9 Before closing the HDL Cosimulation block parameters dialog box, click
Apply to commit any edits you have made.
Observe that Auto Fill returned information about all inputs and outputs
for the targeted component. In many cases, this will include signals that
function in the HDL simulator but cannot be connected in the Simulink
model. You may delete any such entries from the list in the Ports pane if
they are unwanted. You can drive the signals from Simulink; you just have to
define their values by laying down Simulink blocks.
5-24
Define HDL Cosimulation Block Interface
Note that Auto Fill does not return information for internal signals. If your
Simulink model needs to access such signals, you must enter them into the
Ports pane manually. For example, in the case of the Manchester Receiver
model, you would need to add output port entries for top/manchester/sync_i,
top/manchester/isum_i, and top/manchester/qsum_i, as shown in step 8.
Incisive and ModelSim users: Note that clk, reset, and clk_enable may be
in the Clocks and Simulation panes but they don’t have to be. These signals
can be ports if you choose to drive them explicitly from Simulink.
Note When you import VHDL signals using Auto Fill, the HDL simulator
returns the signal names in all capitals.
1 In the HDL simulator, determine the signal path names for the HDL
signals you plan to define in your block. For example, in the ModelSim
simulator, the following wave window shows all signals are subordinate to
the top-level module manchester.
5-25
5 Replace HDL Component with Simulink Algorithm
2 In Simulink, open the block parameters dialog box for your HDL
Cosimulation block, if it is not already open.
3 Select the Ports pane tab. Simulink displays the following dialog box
(example shown for use with Incisive).
5-26
Define HDL Cosimulation Block Interface
In this pane, you define the HDL signals of your design that you want to
include in your Simulink block and set a sample time and data type for
output ports. The parameters that you should specify on the Ports pane
depend on the type of device the block is modeling as follows:
• For a device having both inputs and outputs: specify block input ports,
block output ports, output sample times and output data types.
For output ports, accept the default or enter an explicit sample time.
Data types can be specified explicitly, or set to Inherit (the default). In
the default case, the output port data type is inherited either from the
signal connected to the port, or derived from the HDL model.
• For a sink device: specify block output ports.
• For a source device: specify block input ports.
5-27
5 Replace HDL Component with Simulink Algorithm
4 Enter signal path names in the Full HDL name column by double-clicking
on the existing default signal.
• Use HDL simulator path name syntax (as described in “Specify HDL
Signal/Port and Module Paths for MATLAB Test Bench Cosimulation”
on page 1-24).
• If you are adding signals, click New and then edit the default values.
Select either Input or Output from the I/O Mode column.
• If you want to, set the Sample Time, Data Type, and Fraction Length
parameters for signals explicitly, as discussed in the remaining steps.
When you have finished editing clock signals, click Apply to register your
changes with Simulink.
The following dialog box shows port definitions for an HDL Cosimulation
block. The signal path names match path names that appear in the HDL
simulator wave window (Incisive example shown).
5-28
Define HDL Cosimulation Block Interface
Note When you define an input port, make sure that only one source is
set up to force input to that port. If multiple sources drive a signal, your
Simulink model may produce unpredictable results.
5 You must specify a sample time for the output ports. Simulink uses the
value that you specify, and the current settings of the Timescales pane,
to calculate an actual simulation sample time.
5-29
5 Replace HDL Component with Simulink Algorithm
6 You can configure the fixed-point data type of each output port explicitly
if desired, or use a default (Inherited). In the default case, Simulink
determines the data type for an output port as follows:
If Simulink can determine the data type of the signal connected to the
output port, it applies that data type to the output port. For example,
the data type of a connected Signal Specification block is known by
back-propagation. Otherwise, Simulink queries the HDL simulator to
determine the data type of the signal from the HDL module.
For example, if the model has an 8-bit signal with Signed data type and
a Fraction Length of 5, the HDL Cosimulation block assigns it the
data type sfix8_En5. If the model has an Unsigned 16-bit signal with no
fractional part (a Fraction Length of 0), the HDL Cosimulation block
assigns it the data type ufix16.
7 Before closing the dialog box, click Apply to register your edits.
5-30
Define HDL Cosimulation Block Interface
For more about the direct feedthrough feature, see “Direct Feedthrough
Cosimulation” on page 8-46.
5-31
5 Replace HDL Component with Simulink Algorithm
5-32
Define HDL Cosimulation Block Interface
5-33
5 Replace HDL Component with Simulink Algorithm
5-34
Define HDL Cosimulation Block Interface
1 Determine whether Simulink and the HDL simulator are running on the
same computer. If they are, skip to step 4.
5-35
5 Replace HDL Component with Simulink Algorithm
3 Enter the host name of the computer that is running your HDL simulation
(in the HDL simulator) in the Host name text field. In the Port number
or service text field, specify a valid port number or service for your
computer system. For information on choosing TCP/IP socket ports, see
“TCP/IP Socket Ports” on page 8-95. Skip to step 5.
4 If the HDL simulator and Simulink are running on the same computer,
decide whether you are going to use shared memory or TCP/IP sockets for
the communication channel. For information on the different modes of
communication, see “HDL Cosimulation with MATLAB or Simulink”.
5 If you want to bypass the HDL simulator when you run a Simulink
simulation, use the Connection Mode options to specify what type of
simulation connection you want. Select one of the following options:
• Full Simulation: Confirm interface and run HDL simulation (default).
• Confirm Interface Only: Check HDL simulator for expected signal
names, dimensions, and data types, but do not run HDL simulation.
• No Connection: Do not communicate with the HDL simulator. The
HDL simulator does not need to be started.
With the second and third options, HDL Verifier software does not
communicate with the HDL simulator during Simulink simulation.
6 Click Apply.
5-36
Define HDL Cosimulation Block Interface
5-37
5 Replace HDL Component with Simulink Algorithm
Note for ModelSim Users After each simulation, it takes ModelSim time
to update the coverage result. To prevent the potential conflict between this
process and the next cosimulation session, add a short pause between each
successive simulation.
1 Select the Simulation tab of the Block Parameters dialog box. The dialog
box appears as follows (example shown for use with ModelSim).
5-38
Define HDL Cosimulation Block Interface
ModelSim DO Files
Alternatively, you can create a ModelSim DO file that lists Tcl commands
and then specify that file with the ModelSim do command as shown in
the following figure.
5-39
5 Replace HDL Component with Simulink Algorithm
3 Click Apply.
5-40
Define HDL Cosimulation Block Interface
The HDL Cosimulation block does not have any tunable parameters; thus,
you get an error if you try to change a value while the simulation is running.
However, it does have a few evaluated parameters.
You can see the list of parameters and their attributes by performing
a right-mouse click on the block, selecting View Mask, and then the
Parameters tab. The Variable column shows the programmatic parameter
names. Alternatively, you can get the names programmatically by selecting
the HDL Cosimulation block and then typing the following commands at
the MATLAB prompt:
• In the model workspace, for example, View > Model Explorer > Simulink
Root > model_name > Model Workspace, option Data Source is set
to Model File.
• In a model callback, for example, File > Model Properties > Callbacks.
• A subsystem callback (right-mouse click on an empty subsystem and then
select Properties > Callbacks). Many of the HDL Verifier demos use
this technique to start the HDL simulator by placing MATLAB code in
the OpenFcn callback.
• The HDL Cosimulation block callback (right-mouse click on HDL
Cosimulation block, and then select Properties > Callbacks).
5-41
5 Replace HDL Component with Simulink Algorithm
collisions with other simulation runs. This example shows code that could
handle that task. The script is for a 32-bit Linux platform.
5-42
Run a Component Cosimulation Session
You can adjust the parameters individually or you can use the MATLAB
file dspstartup, which lets you automate the configuration process so that
every new model that you create is preconfigured with the following relevant
parameter settings:
5-43
5 Replace HDL Component with Simulink Algorithm
5-44
Run a Component Cosimulation Session
For more information on using and customizing dspstartup, see the DSP
System Toolbox documentation. For more information about automating
tasks at startup, see the description of the startup command in the MATLAB
documentation.
The MATLAB command pingHdlSim can also be used to check the connection
status. If a -1 is returned, then there is no connection with the HDL simulator.
• “Cosimulation Using the Simulink and HDL Simulator GUIs” on page 4-46
• “Cosimulation with Simulink Using the Command Line Interface (CLI)”
on page 4-47
• “Cosimulation with Simulink Using Batch Mode” on page 4-48
5-45
5 Replace HDL Component with Simulink Algorithm
model and displays any errors that it detects. You can alternate between the
HDL simulator and Simulink GUIs to monitor the cosimulation results.
You can specify "GUI" as the property value for the run mode parameter of
the HDL Verifier HDL simulator launch command, but since using the GUI is
the default mode for HDL Verifier, you do not have to.
To use the CLI, specify "CLI" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command.
Caution Close the terminal window by entering "quit -f" at the command
prompt. Do not close the terminal window by clicking the "X" in the upper
right-hand corner. This causes a memory-type error to be issued from the
system. This is not a bug with HDL Verifier but just the way the HDL
simulator behaves in this context.
You can type CTRL+C to interrupt and terminate the simulation in the HDL
simulator but this action also causes the memory-type error to be displayed.
Issue the nclaunch command with "CLI" as the runmode property value, as
follows (example entered into the MATLAB editor):
5-46
Run a Component Cosimulation Session
};
nclaunch('tclstart',tclcmd,'runmode','CLI');
Issue the vsim command with "CLI" as the runmode property value, as follows
(example entered into the MATLAB editor):
vsim('tclstart',tclcmd,'runmode','CLI');
To use the batch mode, specify "Batch" as the property value for the run mode
parameter of the HDL Verifier HDL simulator launch command. After you
issue the HDL Verifier HDL simulator launch command with batch mode
specified, start the simulation in Simulink. To stop the HDL simulator before
the simulation is completed, issue the breakHdlSim command.
nclaunch('tclstart',manchestercmds,'runmode','Batch')
You can also set runmode to "Batch with Xterm", which starts the HDL
simulator in the background but shows the session in an Xterm.
5-47
5 Replace HDL Component with Simulink Algorithm
Issue the vsim command with "Batch" as the runmode parameter, as follows:
>> vsim('tclstart',manchestercmds,'runmode','Batch')
Test Cosimulation
If you wish to reset a clock during a cosimulation, you can do so in one of
these ways:
If you change any part of the Simulink model, including the HDL
Cosimulation block parameters, update the diagram to reflect those changes.
You can do this update in one of the following ways:
5-48
Run a Component Cosimulation Session
can avoid race conditions that could create differing cosimulation results. See
“Race Conditions in HDL Simulators” on page 8-62.
5-49
5 Replace HDL Component with Simulink Algorithm
5-50
6
VCD files can provide data that you might not otherwise acquire unless you
understood the details of a device’s internal logic. In addition, they include
data that can be graphically displayed or analyzed with postprocessing tools,
including, for example, the extraction of data about a particular section of a
design hierarchy or data generated during a specific time interval.
The To VCD File block provided in the HDL Verifier block library serves as a
VCD file generator during Simulink sessions. The block generates a VCD file
that contains information about changes to signals connected to the block’s
input ports and names the file with a specified file name.
Note The To VCD File block logs changes to states '1' and '0' only. The
block does not log changes to states 'X' and 'Z'.
6-2
Add a Value Change Dump (VCD) File
2 Identify where you want to add the To VCD File block. For example, you
might temporarily replace a scope with this block.
3 In the Simulink Library Browser, click HDL Verifier and then select the
block library for your HDL simulator. You will see the HDL Cosimulation
block icon and the To VCD File block icon.
4 Copy the To VCD File block from the Library Browser to your model by
clicking the block and dragging it from the browser to your model window.
5 Connect the block ports to the applicable blocks in your Simulink model.
6 Configure the To VCD File block by specifying values for parameters in the
Block Parameters dialog box, as follows:
a Double-click the block icon. Simulink displays the following dialog box.
6-3
6 Record Simulink Signal State Transitions for Post-Processing
b Specify a file name for the generated VCD file in the VCD file name
text box.
• If you specify a file name only, Simulink places the file in your current
MATLAB folder.
• Specify a complete path name to place the generated file in a different
location.
• If you want the generated file to have a .vcd file type extension, you
must specify it explicitly.
6-4
Add a Value Change Dump (VCD) File
Note Do not give the same file name to different VCD blocks. Doing so
results in invalid VCD files.
c Specify an integer in the Number of input ports text box that indicates
the number of block input ports on which signal data is to be collected.
The block can handle up to 943 (830,584) signals, each of which maps to
a unique symbol in the VCD file.
d Click OK.
8 Run the simulation. Simulink captures the simulation data in the VCD
file as the simulation runs.
For a description of the VCD file format see “VCD File Format”. For a sample
application of a VCD file, see “Visually Compare Simulink Signals with HDL
Signals” on page 6-6.
6-5
6 Record Simulink Signal State Transitions for Post-Processing
Tutorial: Overview
Note This tutorial and the tool used are specific to ModelSim users; however,
much of the process will be the same for Incisive users with a similar tool. See
HDL simulator documentation for details.
VCD files include data that can be graphically displayed or analyzed with
postprocessing tools. An example of such a tool is the ModelSim vcd2wlf tool,
which converts a VCD file to a WLF file that you can then view in a ModelSim
wave window. This tutorial shows how you might apply the vcd2wlf tool.
Tutorial: Instructions
Perform the following steps to view VCD data:
2 Open your writable copy of the Manchester Receiver model. For example,
select File > Open, select the file manchestermodel and click Open. The
Simulink model should appear as follows. The HDL Cosimulation block is
marked “VHDL Manchester Receiver”.
6-6
Visually Compare Simulink Signals with HDL Signals
4 Replace the Signal Scope block with a To VCD File block, as follows:
a Delete the Signal Scope block. The lines representing the signal
connections to that block change to dashed lines, indicating the
disconnection.
b Find and open the HDL Verifier block library.
6-7
6 Record Simulink Signal State Transitions for Post-Processing
c Click “For Use with Mentor Graphics ModelSim” to access the HDL
Verifier Simulink blocks for use with ModelSim.
d Copy the To VCD File block from the Library Browser to the model by
clicking the block and dragging it from the browser to the location in
your model window previously occupied by the Signal Scope block.
e Double-click the To VCD File block icon. The Block Parameters dialog
box appears.
f Type MyVCDfile.vcd in the VCD file name text box.
g Type 4 in the Number of input ports text box.
6-8
Visually Compare Simulink Signals with HDL Signals
7 Select the following command line from the instructional text that appears
in the demonstration model:
vsim('tclstart',manchestercmds,'socketsimulink',4442)
8 Paste the command in the MATLAB Command Window and execute the
command line. This command starts ModelSim and configures it for a
Simulink cosimulation session.
9 Open the HDL Cosimulation block parameters dialog box and select the
Connection tab. Change the Connection method to Socket and “4442” for
the TCP/IP socket port. The port you specify here must match the value
specified in the call to the vsim command in the previous step.
11 When the simulation is complete, locate, open, and browse through the
generated VCD file, MyVCDfile.vcd (any text editor will do).
14 Change the current folder to the folder containing the VCD file and enter
the following command at the ModelSim command prompt:
6-9
6 Record Simulink Signal State Transitions for Post-Processing
The vcd2wlf utility converts the VCD file to a WLF file that you display
with the command vsim -view.
A wave window appears showing the signals logged in the VCD file.
17 Click the Zoom Full button to view the signal data. The wave window
should appear as follows.
6-10
Visually Compare Simulink Signals with HDL Signals
18 Exit the simulation. One way of exiting is to enter the following command:
ModelSim closes the data set, clears the wave window, and exits the
simulation.
For more information on the vcd2wlf utility and working with data sets, see
the ModelSim documentation.
6-11
6 Record Simulink Signal State Transitions for Post-Processing
6-12
7
• “Import HDL Code With the HDL Cosimulation Wizard” on page 7-2
• “Invoking the Cosimulation Wizard” on page 7-5
• “Import HDL Code for MATLAB Function” on page 7-6
• “Import HDL Code for MATLAB System Object” on page 7-20
• “Import HDL Code for HDL Cosimulation Block” on page 7-37
• “Performing Cosimulation” on page 7-53
• “HDL Cosimulation Wizard Tutorials” on page 7-55
• “Help Button” on page 7-98
7 HDL Code Import for Cosimulation
Each cosimulation type workflow requires that you complete the generated
cosimulation interface when the wizard is completed. For example, if you
specified a MATLAB function, the generated script contains some simple port
I/O instructions and empty routines, which you will then need to complete
for HDL cosimulation.
• The name of the HDL files or compilation scripts to use in creating the
block or function
• For Simulink blocks and MATLAB System objects:
- The name of the top module to be used for cosimulation
- Output port types and sample times
- Whether there are clocks and resets and which of them you want to
use, and timing parameters
- Timescale
7-2
Import HDL Code With the HDL Cosimulation Wizard
For Simulink blocks, you must also have a destination model to receive the
newly-generated block.
When you are ready to begin, start with “Invoking the Cosimulation Wizard”
on page 7-5.
7-3
7 HDL Code Import for Cosimulation
• The status window displays the current status of the options you have
selected. Warnings are displayed here also.
• Click Help to display this HDL Code Import topic.
• Click Cancel to exit the Cosimulation Wizard without creating a
cosimulation component.
• Click Back and Next to navigate forwards and backwards, respectively,
through the application. Note that you can move forwards only after you
have provided all information for the step you are on.
The last step of the Cosimulation Wizard generates the function scripts,
System objects, or blocks and launches the specified HDL simulator.
• If you select a function or System object, the MATLAB Editor opens with
the unfinished script or System object ready for editing.
• If you select a block, Simulink opens with the new block inside an untitled
model.
7-4
Invoking the Cosimulation Wizard
cosimWizard
Select one of the following topics to continue instruction for the cosimulation
interface you selected:
7-5
7 HDL Code Import for Cosimulation
7-6
Import HDL Code for MATLAB Function
If the HDL simulator executables are not on the system path, select Use
the following HDL simulator executables at the following location
and specify the folder location in the text box below.
If you click Next and the Cosimulation Wizard does not find the
executables, the following occurs:
• You are returned to this dialog and the Cosimulation Wizard displays
an error in the status pane.
7-7
7 HDL Code Import for Cosimulation
You must enter a valid path to the HDL simulator executables before you
are allowed to continue.
4 Click Next.
In the HDL Files pane, specify the files to be used in creating the function
or block.
7-8
Import HDL Code for MATLAB Function
2 Remove files by first highlighting the file name in the File List, then
clicking Remove Selected File.
3 Click Next.
7-9
7 HDL Code Import for Cosimulation
In the HDL Compilation pane, you can review the generated HDL
compilation commands. You may override and/or customize those commands,
if you wish. If you included compilation scripts instead of HDL files, this pane
will show you the command to run those scripts.
7-10
Import HDL Code for MATLAB Function
7-11
7 HDL Code Import for Cosimulation
In the HDL Module pane, provide the name of the HDL module to be used
in cosimulation.
7-12
Import HDL Code for MATLAB Function
4 Click Next to proceed to the next step. At this time in the process, the
application performs the following actions in a command window:
• Starts the HDL simulator.
• Loads the HDL module in the HDL simulator.
• Starts the HDL server, and waits to receive notice that the server has
started.
• Connects with the HDL server to get the port information.
• Disconnects and shuts down the HDL server.
7-13
7 HDL Code Import for Cosimulation
7-14
Import HDL Code for MATLAB Function
assumption is that the function name is the same as the HDL component
name.
• HDL component: Enter component name manually or browse for it
by clicking Browse.
• Trigger mode: Specify one of the following to trigger the callback
function:
– Repeat
– Rising Edge
– Falling Edge
– Sensitivity
• Sample time (ns) or Trigger Signal:
– If you selected trigger Repeat, enter the sample time in nanoseconds.
– If you selected Rising Edge, Falling Edge, or Sensitivity,
Sample time (ns) changes to Trigger Signal. Enter the signal
name to be used to trigger the callback.
You can browse the existing signals in the HDL component you specified
by clicking Browse.
2 Click Add to add the command to the MATLAB Callback Functions list.
If you have more callback functions you want to schedule, repeat the above
steps. If you want to remove any callback functions, highlight the line you
want to remove and click Remove.
Note If you attempt to add a callback function for the same HDL module
as an existing callback function in the MATLAB Callback Functions list,
the new callback function will overwrite the existing one (this is true even
if you change the callback type). You will see a warning in the Status
window:
Warning: This HDL component already has a scheduled callback function, which is
replaced by this new one.
7-15
7 HDL Code Import for Cosimulation
3 Click Next.
7-16
Import HDL Code for MATLAB Function
function osc_top_u_osc_filter1x(obj)
% Automatically generated MATLAB(R) callback function.
% The name strings of ports that sends data from MATLAB callback
% function to HDL simulator
obj.userdata.ToHdlPortNames = fields(obj.portinfo.in);
obj.userdata.ToHdlPortNum = length(fields(obj.portinfo.in));
7-17
7 HDL Code Import for Cosimulation
% Initialize state
obj.userdata.State = 0;
end
if(obj.userdata.FromHdlPortNum > 0)
% The name of the first input port
portName = obj.userdata.FromHdlPortNames{1};
disp(['Reading input port ' portName]);
% Convert the multi-valued logic value of the first port to decimal
portValueDec = mvl2dec( ...
obj.portvalues.(portName), ... % Multi-valued logic of the first port
obj.portinfo.out.(portName).size); %#ok<NASGU> % Bit width
% Then perform any necessary operations on this value passed by HDL simulator.
% ...
% Optionally, you can translate the port value into fixed point object,
% e.g.
% myfiobj = fi(portValueDec,1, 16, 4);
end
if(obj.userdata.ToHdlPortNum > 0)
% The name of the first output port in HDL
portName = obj.userdata.ToHdlPortNames{1};
disp(['Writing output port ' portName]);
7-18
Import HDL Code for MATLAB Function
end
7-19
7 HDL Code Import for Cosimulation
7-20
Import HDL Code for MATLAB System Object
7-21
7 HDL Code Import for Cosimulation
If the HDL simulator executables are not on the system path, select Use
the following HDL simulator executables at the following location
and specify the folder location in the text box below.
If you click Next and the Cosimulation Wizard does not find the
executables, the following occurs:
• You are returned to this dialog and the Cosimulation Wizard displays
an error in the status pane.
• The Cosimulation Wizard switches the option to Use the following
HDL simulator executables at the following location.
• The Cosimulation Wizard makes the HDL simulation path field editable.
You must enter a valid path to the HDL simulator executables before you
are allowed to continue.
4 Click Next.
7-22
Import HDL Code for MATLAB System Object
In the HDL Files pane, specify the files to be used in creating the function
or block.
7-23
7 HDL Code Import for Cosimulation
2 Remove files by first highlighting the file name in the File List, then
clicking Remove Selected File.
3 Click Next.
7-24
Import HDL Code for MATLAB System Object
In the HDL Compilation pane, you can review the generated HDL
compilation commands. You may override and/or customize those commands,
if you wish. If you included compilation scripts instead of HDL files, this pane
will show you the command to run those scripts.
7-25
7 HDL Code Import for Cosimulation
In the HDL Module pane, provide the name of the HDL module to be used
in cosimulation.
7-26
Import HDL Code for MATLAB System Object
4 Click Next to proceed to the next step. At this time in the process, the
application performs the following actions in a command window:
• Starts the HDL simulator.
• Loads the HDL module in the HDL simulator.
• Starts the HDL server, and waits to receive notice that the server has
started.
• Connects with the HDL server to get the port information.
• Disconnects and shuts down the HDL server.
7-27
7 HDL Code Import for Cosimulation
1 In the Input/Output Ports pane, specify the type of each input and output
port (Input, Clock, Reset, or Unused).
• The Cosimulation Wizard attempts to determine the port types for you,
but you may override any setting.
• MATLAB forces clock and reset signals in the HDL simulator through
Tcl commands. You can specify clock and reset signal timing in a later
step (see “Clock/Reset Details—MATLAB System Object” on page 7-30).
2 Click Next.
7-28
Import HDL Code for MATLAB System Object
1 In the Output Port Details pane, set the sample time and data type for
all output ports.
• Sample time default is 1, the data type default is Inherit and Signed.
These defaults are consistent with the way the HDL Cosimulation
block mask (Ports tab) sets default settings for output ports (Simulink
workflow).
• If you select Set all sample times and data types to ’Inherit’, the
ports inherit the times via back propagation (sample times are set to
-1). However, back propagation may fail in some circumstances; see
“Backpropagation in Sample Times”.
2 Click Next.
7-29
7 HDL Code Import for Cosimulation
1 In the Clock/Reset Details pane, set the clock and reset parameters.
• The time period specified here refers to time in the HDL simulator.
• The clock default settings are a rising active edge and a period of 10 ns.
• The reset default settings are an initial value of 0 and a duration of 15 ns.
7-30
Import HDL Code for MATLAB System Object
The next screen provides a visual display of the simulation start time
where you can review how the clocks and resets line up.
2 Click Next.
1 In the Start Time Alignment pane, review the current settings for clocks
and resets. The purpose for this dialog is twofold:
7-31
7 HDL Code Import for Cosimulation
• To make sure the rising or falling edge is set as expected (from the
previous step)
– Examine the start time. If it coincides with the active edge of the
clock, you need to adjust the HDL simulator start time.
– Examine the reset signal. If it is synchronous with the clock active
edge, you may have a possible race condition.
To avoid a race condition, make sure the start time does not coincide
with the active edge of any clocks. You can do this by moving the start
time or by changing clock active edges in the previous step.
• To make sure the start time is where you want it.
The HDL simulator start time is calculated from the clock and reset values
on the previous pane. If you want, you can change the HDL simulator
start time by entering a new value where you see HDL time to start
cosimulation (ns). Click Update plot to see your change applied.
2 Click Next.
7-32
Import HDL Code for MATLAB System Object
1 You can modify the HDL simulator sampling period before the wizard
generates the System object. Enter the new value in the box labeled HDL
Simulator sampling period (ns).
The sampling period determines the elapsed time in the HDL Simulator
separating each call to step in MATLAB. Most of the time the sampling
period is equal to the clock period.
2 If your inputs and outputs are frame based (instead of sample based), select
Frame based processing.
3 Click Finish.
After you click Finish, the wizard generates the following HDL files in the
current directory:
7-33
7 HDL Code Import for Cosimulation
7-34
Import HDL Code for MATLAB System Object
See “Import HDL Code for MATLAB System Object” on page 7-20 for a
demonstration of creating a HDL cosimulationSystem object and test bench.
7-35
7 HDL Code Import for Cosimulation
2 When the HDL simulator is ready, return to MATLAB and start the
simulation by executing the test bench.
7-36
Import HDL Code for HDL Cosimulation Block
7-37
7 HDL Code Import for Cosimulation
If the HDL simulator executables are not on the system path, select Use
the following HDL simulator executables at the following location
and specify the folder location in the text box below.
If you click Next and the Cosimulation Wizard does not find the
executables, the following occurs:
• You are returned to this dialog and the Cosimulation Wizard displays
an error in the status pane.
7-38
Import HDL Code for HDL Cosimulation Block
You must enter a valid path to the HDL simulator executables before you
are allowed to continue.
4 Click Next.
In the HDL Files pane, specify the files to be used in creating the function
or block.
7-39
7 HDL Code Import for Cosimulation
2 Remove files by first highlighting the file name in the File List, then
clicking Remove Selected File.
3 Click Next.
7-40
Import HDL Code for HDL Cosimulation Block
In the HDL Compilation pane, you can review the generated HDL
compilation commands. You may override and/or customize those commands,
if you wish. If you included compilation scripts instead of HDL files, this pane
will show you the command to run those scripts.
7-41
7 HDL Code Import for Cosimulation
7-42
Import HDL Code for HDL Cosimulation Block
In the Simulation Options pane, provide the name of the HDL module
to be used in cosimulation.
7-43
7 HDL Code Import for Cosimulation
4 Click Next to proceed to the next step. At this time in the process, the
application performs the following actions in a command window:
• Starts the HDL simulator.
• Loads the HDL module in the HDL simulator.
• Starts the HDL server, and waits to receive notice that the server has
started.
• Connects with the HDL server to get the port information.
• Disconnects and shuts down the HDL server.
7-44
Import HDL Code for HDL Cosimulation Block
1 In the Simulink Ports pane, specify the type of each input and output port.
• The Cosimulation Wizard attempts to determine the port types for you,
but you may override any setting.
• For input ports, select Input, Clock, Reset, or Unused.
• For output ports, select Output or Unused.
• Simulink forces clock and reset signals in the HDL simulator through
Tcl commands. You can specify clock and reset signal timing in a later
step (see “Clock/Reset Details—Simulink Block” on page 7-48).
7-45
7 HDL Code Import for Cosimulation
• To drive your HDL clock and reset signals with Simulink signals, mark
them as Input.
1 In the Output Port Details pane, set the sample time and data type for
all output ports.
7-46
Import HDL Code for HDL Cosimulation Block
• Sample time default is 1, the data type default is Inherit and Signed.
These defaults are consistent with the way the HDL Cosimulation block
mask (Ports tab) sets default settings for output ports.
• If you select Set all sample times and data types to ’Inherit’, the
ports inherit the times via back propagation (sample times are set to
-1). However, back propagation may fail in some circumstances; see
“Backpropagation in Sample Times”.
2 Click Next.
7-47
7 HDL Code Import for Cosimulation
1 In the Clock/Reset Details pane, set the clock and reset parameters.
• The time period specified here refers to time in the HDL simulator.
• The clock default settings are a rising active edge and a period of 10 ns.
• The reset default settings are an initial value of 0 and a duration of 15 ns.
7-48
Import HDL Code for HDL Cosimulation Block
The next screen provides a visual display of the simulation start time
where you can review how the clocks and resets line up.
2 Click Next.
1 In the Start Time Alignment pane, review the current settings for clocks
and resets. The purpose for this dialog is twofold:
7-49
7 HDL Code Import for Cosimulation
• To make sure the rising or falling edge is set as expected (from the
previous step)
– Examine the start time. If it coincides with the active edge of the
clock, you need to adjust the HDL simulator start time.
– Examine the reset signal. If it is synchronous with the clock active
edge, you may have a possible race condition.
To avoid a race condition, make sure the start time does not coincide
with the active edge of any clocks. You can do this by moving the start
time or by changing clock active edges in the previous step.
• To make sure the start time is where you want it.
The HDL simulator start time is calculated from the clock and reset values
on the previous pane. If you want, you can change the HDL simulator
start time by entering a new value where you see HDL time to start
cosimulation (ns). Click Update plot to see your change applied.
2 Click Next.
7-50
Import HDL Code for HDL Cosimulation Block
Generate Block
1 Specify if you want HDL Verifier to determine the timescale when you
start the simulation by selecting Automatically determine timescale
at start of simulation. If you prefer to determine the timescale yourself,
leave this box unchecked and enter the timescale value in the text boxes
below. The default is to automatically determine timescale.
For more about timescales, see the “Timescales Pane” section in the HDL
Cosimulation block reference.
7-51
7 HDL Code Import for Cosimulation
1 Copy the HDL Cosimulation block and, if you wish, the helper functions,
from the newly generated model to the destination model.
2 Place the block so that the inputs and outputs to the HDL Cosimulation
block line up.
3 Connect the blocks in the destination model to the HDL Cosimulation block.
When you have completed the model, see “Performing Cosimulation” on page
7-53 for the next steps in HDL cosimulation.
7-52
Performing Cosimulation
Performing Cosimulation
When you are finished creating a function, System object, or block, select the
topic below that describes how you are planning to cosimulate your HDL code.
7-53
7 HDL Code Import for Cosimulation
7-54
HDL Cosimulation Wizard Tutorials
This example use a MATLAB System object and ModelSim to verify a register
transfer level (RTL) design of a Fast Fourier Transform (FFT) of size 8 written
in Verilog. The FFT is commonly used in digital signal processing to produces
frequency distribution of a signal.
The Cosimulation Wizard takes the provided Verilog file of this FFT as its
input. It also collects user input required for setting up cosimulation in
each step. At the end of the example, the Cosimulation Wizard generates
a MATLAB script that instantiates a configured HdlCosimulation System
object, a MATLAB script that compiles HDL design, and a MATLAB script
that launches the HDL simulator for cosimulation.
To ensure that others can access copies of the example files, set up a folder for
your own example work by following these instructions:
a. Create a folder outside the scope of your MATLAB installation folder into
which you can copy the example files. The folder must be writable. This
example assumes that you create a folder named ’MyTests’.
7-55
7 HDL Code Import for Cosimulation
b. Copy all the files located in the following directory to the folder you created:
matlabroot\toolbox\edalink\foundation\hdllink\demo_src\tutorial_fft
c. You now have all the example files you need in your working directory:
• fft_tb.m
• fft_hdl.v
• fft_hdl_tc.v
a. Start MATLAB.
b. Set the directory you created in Set Up Example Files as your current
directory in MATLAB.
>>cosimWizard
c. Leave the default option Use HDL simulator executables on the system
path option if the HDL simulator executables appear on your system path. If
these executable do not appear on the path, specify the HDL simulator path.
7-56
HDL Cosimulation Wizard Tutorials
• Click Add and select the Verilog files fft_hdl.v and fft_hdl_tc.v in your
example folder.
• Review the files in the file list to make sure the file type is correctly
identified.
Click Next. The MATLAB console displays the compilation log. If an error
occurs during compilation, that error appears in the Status area. Correct the
error before proceeding to the next step.
7-57
7 HDL Code Import for Cosimulation
c. Click Next. The Cosimulation Wizard launches the HDL simulator in the
background console using the specified HDL module and simulation options.
If the wizard launches the HDL simulator successfully, the wizard populates
the input and output ports on the Verilog model fft_hdl and displays them
in the next step.
In this step, the Cosimulation Wizard displays two tables containing the input
and output ports of fft_hdl, respectively.
The Cosimulation Wizard attempts to correctly identify the port type for each
port. If the wizard incorrectly identifies a port, you can change the port type
using these tables.
• For input ports, you can select from Clock, Reset, Input, or Unused. HDL
Verifier connects only the input ports marked "Input" to MATLAB during
cosimulation.
• HDL Verifier connects output ports marked Output with MATLAB during
cosimulation. The link software and MATLAB ignore those output ports
marked "Unused during cosimulation.
• You can change the parameters for signals identified as "Clock" and "Reset"
at a later step.
Accept the default port types and click Next to proceed to the Output Port
Details page.
For this example, the HDL FFT outputs are signed, 13 bits long with 9 bits of
fraction length. In the Output Port Details page, perform the following steps:
7-58
HDL Cosimulation Wizard Tutorials
a. Note that the Sample Time can not be changed and is always fixed to 1
with the HdlCosimulation System object .
Set the clock Period (ns) to 20. From the Verilog code, you know that the
reset is synchronous and the active value is 1. You can reset the entire HDL
design at time 1 ns, triggered by the rising edge of the clock. Use a duration
of 15 ns for the reset signal. In the Clock/Reset Details page, perform the
following steps:
The Start Time Alignment page displays a plot for the waveforms of clock
and reset signals. The Cosimulation Wizard shows the HDL time to start
cosimulation with a red line. The start time is also the time at which the
System object gets the first input sample from the HDL simulator. The active
edge of clock is a rising edge. Thus, at time 20 ns in the HDL simulator,
7-59
7 HDL Code Import for Cosimulation
the registered output of the FFT is stable. No race condition exists, and the
default HDL time to start cosimulation (20 ns) is correct.
a. Before Cosimulation Wizard generates the scripts, you have the option to
modify the HDL Simulator sampling period. The sampling period determine
the elapsed time in the HDL Simulator separating each call to step in
MATLAB. Most of the time the sampling period is equal to the clock period.
You can also specify if your inputs/outputs are frame based (instead of sample
based).
For this example, you do not actually create the test bench. Instead, you
can find the finished script fft_tb.m in the directory you created in Set Up
Example Files.
7-60
HDL Cosimulation Wizard Tutorials
instanciation and fft_tb.m contains a MATLAB System object test bench. You
will use this test bench to verify the HDL design for which you just generated
a corresponding HdlCosimulation System object .
>>launch_hdl_simulator_fft_hdl.m
b. When the HDL simulator is ready, return to MATLAB and start the
simulation by executing the script fft_tb.m.
>>fft_tb.m
c. Verify the result from the plot in the test bench. The plot display the
Fourier Coefficients in the Complex Plane.
This concludes the Cosimulation Wizard for use with MATLAB System object
example.
7-61
7 HDL Code Import for Cosimulation
Note This tutorial requires MATLAB, the HDL Verifier software, and the
ModelSim or Incisive HDL simulator. This tutorial also assumes that you
have read “Import HDL Code for MATLAB Function” on page 7-6.
The HDL test bench instantiates two raised-cosine filter components: one is
implemented in HDL, and the other is associated with a MATLAB callback
function. The test bench also generates stimulus to both filters and compares
their outputs.
7-62
HDL Cosimulation Wizard Tutorials
1 Create a folder outside the scope of your MATLAB installation folder into
which you can copy the tutorial files. The folder must be writable. This
tutorial assumes that you create a folder named MyTests.
2 Copy all the files located in the following MATLAB folder to the folder
you created:
matlabroot\toolbox\edalink\foundation\hdllink\demo_src\tutorial
7-63
7 HDL Code Import for Cosimulation
• filter_tb.v
• mycallback_solution.m
• rcosflt_beh.v
• rcosflt_rtl.v
• rcosflt_tb.mdl (not used in this tutorial)
1 Start MATLAB.
2 Set the folder you created in “Tutorial: Set Up Tutorial Files (MATLAB)”
on page 7-63 as your current folder in MATLAB.
>>cosimWizard
7-64
HDL Cosimulation Wizard Tutorials
3 Leave the default option Use HDL simulator executables on the system
path option if the HDL simulator executables appear on your system path.
If the executables do not appear in the path, specify the HDL simulator
path as described in “Cosimulation Type—MATLAB Function” on page 7-6.
7-65
7 HDL Code Import for Cosimulation
Tutorial: Select HDL Files (MATLAB). In the HDL Files page, perform the
following steps:
a Click Add and browse to the directory you created in “Tutorial: Set Up
Tutorial Files (MATLAB)” on page 7-63.
b Select the Verilog files filter_tb.v, rcosflt_rtl.v, and
rcosflt_beh.v. You can select multiple files in the file browser by
holding down the CTRL key while selecting the files with the mouse.
c Review the file in the file list with the file type identified as you expected.
7-66
HDL Cosimulation Wizard Tutorials
7-67
7 HDL Code Import for Cosimulation
The MATLAB console displays the compilation log. If an error occurs during
compilation, that error appears in the Status area. Change whatever
settings you can to remove the error before proceeding to the next step.
7-68
HDL Cosimulation Wizard Tutorials
If you do not see filter_tb in the drop-down list, you can enter it manually.
7-69
7 HDL Code Import for Cosimulation
3 For HDL component, click Browse. Click the expander icon next to
filter_tb to expand the selection. Select u_rcosflt_beh, and click OK.
You have specified to the Cosimulation Wizard that the HDL simulator
associate this component with the MATLAB callback function.
5 For Trigger Signal, click Browse. Click the expander icon next to
filter_tb to expand the selection. Select u_rcosflt_beh. In the ports list
on the right, select clk. Click OK.
7-70
HDL Cosimulation Wizard Tutorials
For more information on the callback parameters, see the reference page
for matlabcp.
7-71
7 HDL Code Import for Cosimulation
7-72
HDL Cosimulation Wizard Tutorials
In addition to launching the HDL simulator, HDL Verifier software opens the
MATLAB Editor and loads callback_fcn.m (partial image shown).
7-73
7 HDL Code Import for Cosimulation
You modify this template to model a raised cosine filter in MATLAB following
the instructions as shown in the following sections.
Edit callback_fcn.m so that the internal state section contains the following
code:
7-74
HDL Cosimulation Wizard Tutorials
Tutorial: Read Signal from HDL Component. Read the filter input and
convert it to a decimal number in MATLAB.
Edit callback_fcn.m so that the read signal section contains the following code:
Edit callback_fcn.m so that the write signal section contains the following
code:
7-75
7 HDL Code Import for Cosimulation
Tutorial: Update Internal States. Use the filter input to update the
internal 49-element state.
Edit callback_fcn.m so that the update internal states section contains the
following code:
run 200 ns
7-76
HDL Cosimulation Wizard Tutorials
These messages indicate that the output of the HDL component matches the
behavioral output of the MATLAB component.
7-77
7 HDL Code Import for Cosimulation
HDL design, using a Simulink model as the test bench. In this tutorial, you
perform the steps to cosimulate Simulink and the HDL simulator to verify a
simple raised cosine filter written in Verilog.
Note This tutorial requires Simulink, the HDL Verifier software, and the
ModelSim or Incisive HDL simulator. This tutorial assumes that you have
read “Import HDL Code for HDL Cosimulation Block” on page 7-37.
1 Create a folder outside the scope of your MATLAB installation folder into
which you can copy the tutorial files. The folder must be writable. This
tutorial assumes that you create a folder named MyTests.
2 Copy all the files located in the following directory to the folder you created:
matlabroot\toolbox\edalink\foundation\hdllink\demo_src\tutorial
3 You now have all the following files in your working directory, although,
for this tutorial, you will need only two of them:
7-78
HDL Cosimulation Wizard Tutorials
1 Start MATLAB.
2 Set the directory you created in “Tutorial: Set Up Tutorial Files (Simulink)”
on page 7-78 as your current directory in MATLAB.
>>cosimWizard
7-79
7 HDL Code Import for Cosimulation
3 Leave the default option Use HDL simulator executables on the system
path option if the HDL simulator executables appear on your system path.
If these executable do not appear on the path, specify the HDL simulator
path as described in “Cosimulation Type—Simulink Block” on page 7-37.
Tutorial: Select HDL Files (Simulink). In the HDL Files page, perform the
following steps:
7-80
HDL Cosimulation Wizard Tutorials
a Click Add and browse to the directory you created in “Tutorial: Set Up
Tutorial Files (Simulink)” on page 7-78.
b Select the Verilog file rcosflt_rtl.v.
c Review the file in the file list with the file type identified as you expected.
7-81
7 HDL Code Import for Cosimulation
When you run the Cosimulation Wizard with your own code, you may add or
change the compilation commands in this window. For example, you can add
-vlog01compat to add the —vlog01compat switch.
ModelSim users: The HDL Compilation pane will look similar to the one
in this figure:
Incisive users: Your HDL Compilation pane will look similar to the one in
the following figure.
7-82
HDL Cosimulation Wizard Tutorials
The MATLAB console displays the compilation log. If an error occurs during
compilation, that error appears in the Status area. Change whatever settings
you can to remove the error before proceeding to the next step.
From the drop-down list, select "rcosflt_rtl". This module is the Verilog
module you use for cosimulation.
7-83
7 HDL Code Import for Cosimulation
If you do not see "rcosflt_rtl" in the drop-down list, you can enter the file
name manually.
2 ModelSim users: In the Simulation options field, remove the -novopt option
so that ModelSim can optimize the HDL design.
The simulation options now look similar to those shown in the next figure.
Incisive users: Your HDL Module options look similar to the following
figure
7-84
HDL Cosimulation Wizard Tutorials
Tutorial: Specify Port Types. In this step, the Cosimulation Wizard displays
two tables containing the input and output ports of rcosflt_rtl, respectively.
7-85
7 HDL Code Import for Cosimulation
The Cosimulation Wizard attempts to identify the port type for each port. If
the wizard incorrectly identifies a port, you can change the port type using
these tables.
• For input ports, you can select from Clock, Reset, Input, or Unused. HDL
Verifier connects only the input ports marked "Input" to Simulink during
cosimulation.
• HDL Verifier connects output ports marked Output with Simulink during
cosimulation. The wizard and Simulink ignore those output ports marked
"Unused during cosimulation.
• You can change the parameters for signals identified as "Clock“ and "Reset"
at a later step.
Accept the default port types and click Next to proceed to the Output Port
Details page.
7-86
HDL Cosimulation Wizard Tutorials
Tutorial: Specify Output Port Details. In the Output Port Details page,
perform the following steps:
2 You can see from the Verilog code that the Cosimulation Wizard represents
the output in a S34,29 format. Change the following fields:
• Data Type to Fixedpoint
• Sign to Signed
• Fraction Length to 29
7-87
7 HDL Code Import for Cosimulation
Tutorial: Set Clock and Reset Details. For this tutorial, set the clock
Period (ns) to 20. From the Verilog code, you know that the reset is
synchronous and the active value is 1. You can reset the entire HDL design
at time 1 ns, triggered by the rising edge of the clock. Use a duration of 15
ns for the reset signal.
7-88
HDL Cosimulation Wizard Tutorials
Your clock and reset are now the same as those same signals shown in
the following figure.
7-89
7 HDL Code Import for Cosimulation
Tutorial: Confirm Start Time Alignment. The Start Time Alignment page
displays a plot for the waveforms of clock and reset signals. The Cosimulation
Wizard shows the HDL time to start cosimulation with a red line. The start
time is also the time at which the Simulink gets the first input sample from
the HDL simulator.
The active edge of our clock is a rising edge. Thus, at time 20 ns in the
HDL simulator, the registered output of the raised cosine filter is stable.
No race condition exists, and the default HDL time to start cosimulation
(20 ns) is what we want for this simulation. You do not need to make any
changes to the start time.
7-90
HDL Cosimulation Wizard Tutorials
7-91
7 HDL Code Import for Cosimulation
7-92
HDL Cosimulation Wizard Tutorials
Leave the model for the moment and proceed to the next step.
2 Open the file rcosflt_tb, located in the directory you created in “Tutorial:
Set Up Tutorial Files (Simulink)” on page 7-78.
This file contains a model of a Simulink test bench. You will use this
test bench to verify the HDL design for which you just generated a
corresponding HDL Cosimulation block.
7-93
7 HDL Code Import for Cosimulation
3 Add the HDL Cosimulation block to the test bench model as follows:
a Copy the HDL Cosimulation block from the newly generated model to
this test bench model.
b Place the block so that the constant and convert blocks line up as inputs
to the HDL Cosimulation block and the bus lines up as output.
c Connect the blocks in the test bench to the HDL Cosimulation block.
4 Copy the script blocks to the area below the test bench. Your model now
looks similar to that in the following figure.
7-94
HDL Cosimulation Wizard Tutorials
2 When the HDL simulator is ready, return to Simulink and start the
simulation.
3 Determine timescale.
Both the HDL simulator and Simulink sample the filter_in and filter_out
ports at 1 second. However, their sample time in the HDL simulator should
be the same as the clock period (2 ns).
a Change the Simulink sample time of /rcosflt_rtl/filter_in to 1 (seconds),
and press Enter. The wizard then updates the table. The following
figure shows the new timescale: 1 second in Simulink corresponds to
2e-008 s in the HDL simulator.
7-95
7 HDL Code Import for Cosimulation
4 Restart simulation.
5 Verify the result from the scope in the test bench model. The scope
displays both the delayed version of input to raised cosine filter and that
filter’s output. If you sample the output of this filter output directly, no
inter-symbol-interference occurs
7-96
HDL Cosimulation Wizard Tutorials
This step concludes the Cosimulation Wizard for use with Simulink tutorial.
7-97
7 HDL Code Import for Cosimulation
Help Button
In this section...
“Cosimulation Type” on page 7-98
“HDL Files” on page 7-100
“HDL Compilation” on page 7-102
“HDL Modules” on page 7-103
Cosimulation Type
7-98
Help Button
If the HDL simulator executables are not on the system path, select Use
the following HDL simulator executables at the following location
and specify the folder location in the text box below.
If you click Next and the Cosimulation Wizard does not find the
executables, the following occurs:
• You are returned to this dialog and the Cosimulation Wizard displays
an error in the status pane.
• The Cosimulation Wizard switches the option to Use the following
HDL simulator executables at the following location.
• The Cosimulation Wizard makes the HDL simulation path field editable.
You must enter a valid path to the HDL simulator executables before you
are allowed to continue.
Next Steps
• For an HDL cosimulation block, start at “Cosimulation Type—Simulink
Block” on page 7-37.
• For an HDL cosimulation function, start at “Cosimulation Type—MATLAB
Function” on page 7-6.
• For an HDL cosimulation System object, start at “Cosimulation
Type—MATLAB System Object” on page 7-20.
7-99
7 HDL Code Import for Cosimulation
HDL Files
In the HDL Files pane, specify the files to be used in creating the function
or block.
If you are using ModelSim, you will see compilation scripts listed as .do files
(ModelSim macro file). If you are using Incisive, you will see compilation
scripts listed as system scripts.
7-100
Help Button
2 Remove files by first highlighting the file name in the File List, then
clicking Remove Selected File.
Next Steps
• For an HDL cosimulation block, start at “HDL Files—Simulink Block”
on page 7-39.
• For an HDL cosimulation function, start at “HDL Files—MATLAB
Function” on page 7-8.
• For an HDL cosimulation System object, start at “HDL Files—MATLAB
System Object” on page 7-23.
7-101
7 HDL Code Import for Cosimulation
HDL Compilation
In the HDL Compilation pane, you can review the generated HDL
compilation commands. You may override and/or customize those commands,
if you wish. If you included compilation scripts instead of HDL files, this pane
will show you the command to run those scripts.
7-102
Help Button
Next Steps
• For an HDL cosimulation block, start at “HDL Compilation—Simulink
Block” on page 7-41.
• For an HDL cosimulation function, start at “HDL Compilation—MATLAB
Function” on page 7-10.
• For an HDL cosimulation System object, start at “HDL
Compilation—MATLAB System Object” on page 7-25.
HDL Modules
HDL Modules—Simulink Block
7-103
7 HDL Code Import for Cosimulation
In the HDL Modules pane, provide the name of the HDL module to be used
in cosimulation.
7-104
Help Button
3 When you proceed to the next step, the application performs the following
actions in a command window:
• Starts the HDL simulator.
• Loads the HDL module in the HDL simulator.
• Starts the HDL server, and waits to receive notice that the server has
started.
• Connects with the HDL server to get the port information.
• Disconnects and shuts down the HDL server.
Next Steps
• For an HDL cosimulation block, start at “Simulation Options—Simulink
Block” on page 7-43.
• For an HDL cosimulation function, start at “HDL Modules—MATLAB
Function” on page 7-12.
• For an HDL cosimulationSystem object, start at “Simulation
Options—MATLAB System Object” on page 7-26.
7-105
7 HDL Code Import for Cosimulation
7-106
8
HDL Cosimulation
Reference
8-2
Startup for HDL Cosimulation
Notes
8-3
8 HDL Cosimulation Reference
Notes
8-4
Startup for HDL Cosimulation
Note If you plan to use the Cosimulation Wizard, you do not need to start
the HDL simulator separately.
• You issue the launch command directly from MATLAB and provide the
HDL Verifier library information and other required parameters (see
“HDL Verifier Libraries” on page 8-11). No special setup is required. This
function starts and configures the HDL simulator for use with the HDL
Verifier software. By default, the function starts the first version of the
simulator executable that it finds on the system path (defined by the path
variable), using a temporary file that is overwritten each time the HDL
simulator starts.
• You can customize the startup file and communication mode to be used
between MATLAB or Simulink and the HDL simulator by specifying the
call to the HDL simulator launch command with property name/property
value pairs. Refer to the nclaunch or vsim reference documentation for
specific information regarding the property name/property value pairs.
8-5
8 HDL Cosimulation Reference
• If you want to start a different version of the simulator executable than the
first one found on the system path, use the setenv and getenv MATLAB
functions to set and get the environment of any sub-shells spawned by
UNIX(), DOS(), or system().
• When you specify a communication mode using any of the HDL Verifier
HDL simulator launch commands, the function applies the specified
communication mode to all MATLAB or Simulink/HDL simulator sessions.
Resources
• “Starting the ModelSim Simulator from MATLAB” on page 8-6, and
“Starting the Cadence Incisive Simulator from MATLAB” on page 8-8 for
examples of using these HDL Verifier HDL simulator launch commands
with various property/name value pairs and other parameters.
•
• “Linking with MATLAB and the HDL Simulator” for more information on
how HDL Verifier links the HDL simulator with MATLAB.
• “Verify HDL Model with MATLAB Testbench” on page 1-41 for a full
cosimulation example that demonstrates starting the HDL simulator from
MATLAB.
Diagnostic and Customization Setup Script for use with Incisive and
ModelSim If you would like some assistance in setting up your environment
for use with HDL Verifier, you can diagnose your setup (remove or fix
omissions and errors) and also customize your setup for future invocations
of nclaunch or vsim by following the process in “Setup Diagnostics and
Customization” on page 8-18.
The following example changes the folder location to VHDLproj and then
calls the function vsim. Because the command line omits the 'vsimdir'
and 'startupfile' properties, vsim creates a temporary DO file. The
8-6
Startup for HDL Cosimulation
'tclstart' property specifies Tcl commands that load and initialize the HDL
simulator for test bench instance modsimrand.
cd VHDLproj
vsim('tclstart',...
'vsimmatlab modsimrand; matlabtb modsimrand 10 ns -socket 4449')
The following example changes the folder location to VHDLproj and then
calls the function vsim. Because the function call omits the 'vsimdir'
and 'startupfile' properties, vsim creates a temporary DO file. The
'tclstart' property specifies a Tcl command that loads the VHDL entity
parse in library work for cosimulation between vsim and Simulink. The
'socketsimulink' property specifies TCP/IP socket communication on the
same computer, using socket port 4449.
cd VHDLproj
vsim('tclstart', 'vsimulink work.parse', 'socketsimulink', '4449')
The following example has the HDL compilation and simulation commands
run when you start the ModelSim software from MATLAB.
vsim('tclstart',
{'vlib work', 'vlog +acc clocked_inverter.v hdl_top.v', 'vsim +acc hdl_top' });
This next example loads the HDL simulation just as in the previous example
but it also loads in the Link to Simulink library, uses socket number 5678
to communicate with cosimulation blocks in Simulink models, and uses an
HDL time precision of 10 ps.
vsim('tclstart',
{'vlib work', 'vlog -novopt clocked_inverter.v hdl_top.v',
'vsimulink hdl_top -socket 5678 -t 10ps'});
Or
vsim('tclstart',
{'vlib work', 'vlog -novopt clocked_inverter.v hdl_top.v',
'vsimulink hdl_top -t 10ps'},
'socketsimulink', 5678);
8-7
8 HDL Cosimulation Reference
Starting the Cadence Incisive Simulator from MATLAB. To start the HDL
simulator from MATLAB, enter nclaunch at the MATLAB command prompt:
The following example changes the folder location to VHDLproj and then calls
the function nclaunch. Because the command line omits the 'hdlsimdir'
and 'startupfile' properties, nclaunch creates a temporary file. The
'tclstart' property specifies Tcl commands that load and initialize the HDL
simulator for test bench instance modsimrand.
cd VHDLproj
nclaunch('tclstart',...
'hdlsimmatlab modsimrand; matlabtb modsimrand 10 ns -socket 4449')
The following example changes the folder location to VHDLproj and then calls
the function nclaunch. Because the function call omits the 'hdlsimdir'
and 'startupfile' properties, nclaunch creates a temporary file. The
'tclstart' property specifies a Tcl command that loads the VHDL entity
parse in library work for cosimulation between nclaunch and Simulink. The
'socketsimulink' property specifies TCP/IP socket communication on the
same computer, using socket port 4449.
cd VHDLproj
nclaunch('tclstart', 'hdlsimulink work.parse', 'socketsimulink', '4449')
3 Run ncsim in the xterm shell having it call back to the hdlserver to run
your matlabcp function as usual.
The MATLAB script can then change test parameters and run more tests.
8-8
Startup for HDL Cosimulation
After you have the configuration files, you can start the ModelSim software
from the shell by typing:
The configuration file mainly defines the -foreign option to vsim which in turn
loads the HDL Verifier shared library and specifies its entry point.
You can also specify any other existing configuration files you may also be
using with this call.
If you are performing this step manually, the following use of -foreign with
vsim loads the HDL Verifier client shared library and specifies its entry point:
8-9
8 HDL Cosimulation Reference
where path is the path to this particular HDL Verifier library. See“HDL
Verifier Libraries” on page 8-11 to find the applicable library name for your
machine. Use design_name if you want to also start the simulation.
Note You can also issue this exact same command from inside the HDL
simulator.
After you have the configuration files, you can start the HDL simulator from
the shell by typing:
Either way, you must also specify the path to the configuration file if it does
not reside in the same folder as ncsim.exe.
You can also specify any other existing configuration files you may also be
using with this call.
8-10
Startup for HDL Cosimulation
3 Run ncsim in the xterm shell, having it call back to the hdlserver to run
your matlabtb function as usual.
4 Specify that the matlabtb function use the touch command on a file to
signal completion while a MATLAB script polls for completion.
The MATLAB script can then change test parameters and run more tests.
If you have any of these conditions, choose the version of the HDL Verifier
library that matches the compiler used for that code:
If you do not link any other code into your HDL simulator, you can use
any version of the supplied libraries. The HDL Verifier launch command
(nclaunch or vsim) chooses a default version of this library.
Library Names
The HDL Verifier HDL libraries use the following naming format:
edalink/extensions/version/arch/lib{version_short_name}{client_server_tag}
_{compiler_tag).{libext}
where
8-11
8 HDL Cosimulation Reference
Not all combinations are supported. See “Default Libraries” on page 8-12
for valid combinations.
Default Libraries
HDL Verifier scripts fully support the use of default libraries.
The following table lists all the libraries shipped with the verification software
for each supported HDL simulator. The default libraries for each platform
are in bold text.
8-12
Startup for HDL Cosimulation
Note ModelSim uses gcc412 by default; HDL Verifier uses tmwgcc or tmwvs
by default. Therefore, if you are compiling HDL code in ModelSim make
sure you are compiling with the same library that HDL Verifier is using;
either tmwgcc or twmvs by default or gcc412 if you so specified with the
vsim command.
8-13
8 HDL Cosimulation Reference
In this example, you are using the 32-bit Linux version of IUS 11.10-s005
on the same 64-bit Linux machine that is running MATLAB. Because you
have your own C++ application, and you are linking into ncsim that you used
twmgcc to compile, you are using the HDL Verifier version compiled with
tmwgcc, instead of using the default library version compiled with GCC 4.1.
In MATLAB:
The PATH is changed so that we get the desired version of the HDL simulator
tools. Note that the nclaunch MATLAB command will detect the use of the
32-bit version of the HDL simulator and use the linux32 library folder in the
8-14
Startup for HDL Cosimulation
The library resolution can be verified using ldd from within the ncsim console
GUI.
In this example, you are running the 64-bit Linux version of Cadence Incisive
10.2-s040; it does not matter what machine MATLAB is running on. Instead
of using the default library version compiled with GCC 3.2.3 in the Cadence
Incisive distribution, you are using the version compiled with GCC 4.4.
The PATH is changed so that we get the desired version of the Cadence
Incisive tools. Although ncsim will find any GCC libs in its installations,
8-15
8 HDL Cosimulation Reference
You can check the library resolution using ldd as in the previous example.
In this example, you run the 32-bit Linux version of ModelSim SE 10 software
on the same 64-bit Linux machine which is running MATLAB. Because you
want to incorporate some SystemC designs, you are using theHDL Verifier
version compiled with gcc450. You can download this version of GCC with
its associated system libraries from Mentor Graphics, instead of using the
default library version compiled with tmwgcc.
In MATLAB:
8-16
Startup for HDL Cosimulation
You change the PATH so that you get the desired version of the ModelSim
software. You change the LD_LIBRARY_PATH because the HDL simulator
does not add the path to the system libraries. The HDL Verifier function
vsim detects the use of the 32-bit version of the HDL simulator and uses the
linux32 library folder in the verification software installation; there is no
need to specify the libdir parameter in this case.
The library resolution can be verified using ldd from within the ModelSim
GUI:
In this example, you are running the 64-bit Linux version of QuestaSim 10.1a.
It does not matter which machine is running MATLAB. Instead of using the
HDL Verifier default library version compiled with tmwgcc, you are using the
version compiled with GCC 4.5.0. You can download this version of GCC with
its associated system libraries from Mentor Graphics.
8-17
8 HDL Cosimulation Reference
You change the PATH so that you get the desired version of the ModelSim
software. You change the LD_LIBRARY_PATH because the HDL simulator
does not add the path to the system libraries unless you are working with
10.1+ and have placed GCC at the root of the ModelSim installation.
You can check the library resolution using ldd as in the previous example.
The setup script creates a configuration file containing the location of the
specified HDL Verifier MATLAB and Simulink libraries. You can then
include this configuration with any other calls you make using the command
vsim (ModelSim) or ncsim (Incisive) from the HDL simulator. You only need
to run this script once.
8-18
Startup for HDL Cosimulation
Note The HDL Verifier configuration and diagnostic script works only on
UNIX and Linux. Windows users: please see instructions below.
matlabroot/toolbox/edalink/foundation/hdllink/scripts
Refer to “HDL Verifier Libraries” on page 8-11 for the application library
for your platform.
After you have created your configuration files, see “Starting the HDL
Simulator from a Shell” on page 8-9.
The following is an example of running the setup script under the following
conditions:
% syscheckmq
********************************************************************************
8-19
8 HDL Cosimulation Reference
The script first returns the location of the HDL simulator installation
(vsim.exe). If it does not find an installation, you receive an error message.
Either provide the path to the installation or quit the script and install the
HDL simulator. You are then prompted to accept this installation or provide
a path to another one, after which you receive a message confirming the HDL
simulator installation:
Found /hub/share/apps/HDLTools/ModelSim/modelsim-6.4a-tmw-000/modeltech/bin/vsim
on the path.
Press Enter to use the path we found or enter another one:
********************************************************************************
/hub/share/apps/HDLTools/ModelSim/modelsim-6.4a-tmw-000/modeltech/bin/vsim -version
Model Technology ModelSim SE-64 vsim 6.4a Simulator 2008.08 Aug 28 2008
ModelSim mode: 32 bits
********************************************************************************
Next, the script needs to know where it can find the HDL Verifier libraries.
The script then runs a dependency checker to check for supporting libraries.
If any of the libraries cannot be found, you probably need to append your
environment path to find them.
8-20
Startup for HDL Cosimulation
********************************************************************************
This next step loads the HDL Verifier libraries and compiles a test module to
verify the libraries loaded as expected.
Press Enter to load HDL Verifier or enter 'n' to skip this test:
Reading /mathworks/hub/share/apps/HDLTools/ModelSim/modelsim-6.4a-tmw-000/se/modeltech/
linux_x86_64/../modelsim.ini "worklfx9019" maps to directory worklfx9019.
(Default mapping)
Model Technology ModelSim SE-64 vlog 6.4a Compiler 2008.08 Aug 28 2008
-- Compiling module d9019
********************************************************************************
Reading /mathworks/hub/share/apps/HDLTools/ModelSim/modelsim-6.4a-tmw-000/se/modeltech/tcl
/vsim/pref.tcl
# 6.4a
8-21
8 HDL Cosimulation Reference
# Loading work.d9019
# Loading /tmp/lfmconfig/linux64/liblfmhdlc_tmwgcc.so
# exit
********************************************************************************
Next, the script checks a TCP connection. If you choose to skip this step, the
configuration file specifies use of shared memory. Both shared memory and
socket configurations are in the configuration file; depending on your choice,
one configuration or the other is commented out.
Press Enter to check for TCP connection or enter 'n' to skip this test:
Lastly, the script creates the configuration file, unless for some reason you
choose not to do so at this time.
********************************************************************************
********************************************************************************
Diagnosis Completed
8-22
Startup for HDL Cosimulation
After the script is complete, you can leave the configuration files where they
are or move them to wherever it is convenient.
% syscheckin
********************************************************************************
The script first returns the location of the HDL simulator installation
(ncsim.exe). If it does not find an installation, you receive an error message.
Either provide the path to the installation or quit the script and install the
HDL simulator. You are then prompted to accept this installation or provide
a path to another one, after which you receive a message confirming the HDL
simulator installation:
********************************************************************************
/hub/share/apps/HDLTools/IUS/IUS-61-tmw-000/lnx/tools/bin/64bit/ncsim -version
TOOL: ncsim(64) 06.11-s005
Cadence Incisive mode: 64 bits
********************************************************************************
Next, the script needs to know where it can find the HDL Verifier libraries.
8-23
8 HDL Cosimulation Reference
The script then runs a dependency checker to check for supporting libraries.
If any of the libraries cannot be found, you probably need to append your
environment path to find them.
********************************************************************************
This next step loads the HDL Verifier libraries and compiles a test module to
verify the libraries loaded as expected.
Press Enter to load HDL Verifier or enter 'n' to skip this test:
********************************************************************************
8-24
Startup for HDL Cosimulation
Next, the script checks a TCP connection. If you choose to skip this step, the
configuration file specifies use of shared memory. Both shared memory and
socket configurations are in the configuration file; depending on your choice,
one configuration or the other is commented out.
Press Enter to check for TCP connection or enter 'n' to skip this test:
Lastly, the script creates the configuration file, unless for some reason you
choose not to do so at this time.
********************************************************************************
********************************************************************************
Diagnosis Completed
After the script is complete, you can leave the configuration files where they
are or move them to wherever it is convenient.
8-25
8 HDL Cosimulation Reference
1 Create a MATLAB configuration file. You may name it whatever you like;
there are no file-naming restrictions. Enter the following text:
where path is the path to the particular HDL Verifier shared library you
want to invoke (in this example. See “HDL Verifier Libraries” on page 8-11).
2 Create a Simulink configuration file and name it. There are no file-naming
restrictions. Enter the following text:
8-26
Startup for HDL Cosimulation
Where path is the path to the particular HDL Verifier shared library you
want to invoke. See “HDL Verifier Libraries” on page 8-11.
Note If you are going to use a TCP/IP socket connection, first confirm that
you have an available port to put in this configuration file. Then, comment
out whichever type of communication you will not be using.
After you have finished creating the configuration files, you can leave the files
where they are or move them to another location that is convenient.
Cross-Network Cosimulation
• “Why Perform Cross-Network Cosimulation?” on page 8-27
• “Preparing for Cross-Network Cosimulation” on page 8-27
• “Performing Cross-Network Cosimulation Using MATLAB” on page 8-30
• “Performing Cross-Network Cosimulation Using Simulink” on page 8-32
8-27
8 HDL Cosimulation Reference
ModelSim Users
• Create and compile your HDL design, and create your MATLAB
function (for MATLAB cosimulation) or Simulink model (for Simulink
cosimulation).
• If you are going to cosimulate with Simulink, use the -novopt option
when you compile so that the design is not optimized, and include the
-novopt option when you issue the vsim command (see “Performing
Cross-Network Cosimulation Using Simulink” on page 8-32). Using the
-novopt option retains some unused signals from the design which are
required by the Simulink model to run and display the results.
Incisive Users
Create, compile, and elaborate your HDL design, and create your MATLAB
function (for MATLAB cosimulation), or Simulink model (for Simulink
cosimulation).
2 Copy HDL Verifier libraries to the machine with the HDL simulator
a Go to the system where you installed MATLAB. Then, find the folder in
the MATLAB distribution where the HDL Verifier libraries reside.
You can usually find the libraries in the default installed folder:
matlabroot/toolbox/edalink/extensions/adaptor/platform/productlibraryname_
compiler_tag.ext
where the variable shown in the following table have the values
indicated.
8-28
Startup for HDL Cosimulation
Variable Value
matlabroot The location where you installed the
MATLAB software; default value is
"MATLAB/version" where version is the
installed release (for example, R2009a).
adaptor incisive or modelsim
8-29
8 HDL Cosimulation Reference
Variable Value
compiler_tag The compiler used to create the library
(for example, gcc32 or spro). For more
information, see “HDL Verifier Libraries”
on page 8-11.
ext dll (dynamic link library—Windows only)
or so ( shared library extension)
For a list of all the HDL Verifier HDL shared libraries shipped, see
“Default Libraries” on page 8-12.
b From the MATLAB machine, copy the HDL Verifier libraries you
plan to use (which you determined in step 2) to the machine where
you installed the HDL simulator. Make note of the location to which
you copied the libraries; you’ll need this information when you are
actually establishing the connection to the HDL simulator. For purposes
of this example, the sample code refers to the destination folder as
"HDLSERVER_LIB_LOCATION".
ModelSim Users
hdldaemon('socket',0)
hdldaemon('socket',4449)
8-30
Startup for HDL Cosimulation
2 On the machine with the HDL simulator, launch the HDL simulator from a
shell with the following command:
where the arguments shown in the following table have the values
indicated.
Argument Value
library_name The name of the library you
copied to the machine with the
HDL simulator (in “Preparing for
Cross-Network Cosimulation” on
page 8-27).
design_name The VHDL or Verilog design you
want to load
Incisive Users
hdldaemon('socket',0)
Or assign one:
hdldaemon('socket',4449)
2 Create a MATLAB configuration file (for loading the functions used in the
HDL simulator) with the following contents:
-loadcfc /HDLSERVER_LIB_LOCATION/library_name:matlabclient
//TCL wrappers for MATLAB commands
8-31
8 HDL Cosimulation Reference
3 On the machine with the HDL simulator, launch the HDL simulator from a
shell with the following command:
where the arguments shown in the following table have the values
indicated.
Argument Value
matlab_config.file The name of the MATLAB
configuration file (from step 3)
design_name The VHDL or Verilog design you
want to load
ModelSim Users
1 Launch the HDL simulator from a shell with the following command:
8-32
Startup for HDL Cosimulation
where the arguments shown in the following table have the values
indicated.
Argument Value
library_name The name of the library you
copied to the machine with the
HDL simulator (in “Preparing for
Cross-Network Cosimulation” on
page 8-27).
socket_num The socket number you have chosen
for this connection
design_name The VHDL or Verilog design you
want to load
2 On the machine with MATLAB and Simulink, start Simulink and open
your model.
Incisive Users
1 Launch the HDL simulator from a shell with the following command:
8-33
8 HDL Cosimulation Reference
where the arguments shown in the following table have the values
indicated.
Argument Value
library_name The name of the library you
copied to the machine with the
HDL simulator (in “Preparing for
Cross-Network Cosimulation” on
page 8-27).
socket_num The socket number you have chosen
for this connection
design_name The VHDL or Verilog design you
want to load
2 On the machine with MATLAB and Simulink, start Simulink and open
your model.
a Clear the check box labeled The HDL simulator is running on this
computer. HDL Verifier changes the Connection method to Socket.
b In the Host name box, enter the host name of the machine where the
HDL simulator is located.
c In the Port number or service box, enter the socket number from
step 1.
d Click OK to exit block dialog box, and save your changes.
Next, run your simulation, add more blocks, or make other desired changes.
For instructions on using Simulink and the HDL simulator for cosimulation,
see “Simulink as a Test Bench” on page 4-2 or “Component Simulation with
Simulink” on page 5-2.
8-34
Test Bench and Component Function Options
8-35
8 HDL Cosimulation Reference
When you use use_instance_obj, HDL Verifier passes an HDL instance object
to the function specified with the -mfunc argument. The function called has
the following signature:
function MyFunctionName(hdl_instance_obj)
The HDL instance object (hdl_instance_obj) has the fields shown in the
following table.
>> hdl_instance_obj.simstatus
ans=
Init
8-36
Test Bench and Component Function Options
In MATLAB:
>> hdl_instance_obj.instance
ans=
osc_top
argument Read only Stores the argument set by the -argument option of matlabcp.
For example:
>> hdl_instance_obj.argument
ans=
foo
8-37
8 HDL Cosimulation Reference
hdl_instance_obj.portinfo.field1.field2.field3
tscale Read only Stores the resolution limit (tick) in seconds of the HDL
simulator. This field value is a read-only property.
>> hdl_instance_obj.tscale
ans=
1.0000e-009
tnow Read only Stores the current time. This field value is a read-only
property.
8-38
Test Bench and Component Function Options
>> hdl_instance_obj.portvalues
ans =
Read Only Input ports:
clk_enable: []
clk: []
reset: []
Read/Write Output ports:
sine_out: [22x1 char]
linkmode Read only Stores the status of the callback. The HDL Verifier software
sets this field to testbench if the callback is associated with
matlabtb and component if the callback is associated with
matlabcp. This field value is a read-only property.
>> hdl_instance_obj.linkmode
ans=
component
function osc_filter(obj)
8-39
8 HDL Cosimulation Reference
if (strcmp(obj.simstatus,'Init'))
ud = struct('Nbits', 22, 'Norder', 31, 'clockperiod', 80e-9, 'phase', 1));
eval(obj.argument);
if (~exist('oversample','var'))
error('HdlLinkDemo:UseInstanceObj:BadCtorArg', ...
'Bad constructor arg to osc_filter callback. Expecting
''oversample=value''.');
end
ud.oversample = oversample;
ud.oversampleperiod = ud.clockperiod/ud.oversample;
ud.InDelayLine = zeros(1,ud.Norder+1);
centerfreq = 70/256;
passband = [centerfreq-0.01, centerfreq+0.01];
b = fir1((ud.Norder+1)*ud.oversample-1, passband./ud.oversample);
ud.Hresp = ud.oversample .* b;
obj.userdata = ud;
end
...
8-40
Test Bench and Component Function Options
For more information on using tnext and tnow for simulation scheduling, see
“Schedule Component Functions Using the tnext Parameter” on page 2-21.
The following table describes each of the test bench and component function
parameters and the roles they play in each of the functions.
8-41
8 HDL Cosimulation Reference
If you are using matlabcp, initialize the function outputs to empty values at
the beginning of the function as in the following example:
tnext = [];
oport = struct();
Note When you import VHDL signals, signal names in iport, oport, and
portinfo are returned in all capitals.
You can use the port information to create a generic MATLAB function that
operates differently depending on the port information supplied at startup.
For more information on port data, see “Gaining Access to and Applying Port
Information” on page 8-44.
8-42
Test Bench and Component Function Options
The function name oscfilter, differs from the entity name u_osc_filter.
Therefore, the component function name must be passed in explicitly to the
matlabcp command that connects the function to the associated HDL instance
using the -mfunc parameter.
The function definition specifies all required input and output parameters, as
listed here:
oport Forces (by deposit) values onto the signals connected to the
entity’s output ports, filter1x_out, filter4x_out and
filter8x_out.
tnext Specifies a time value that indicates when the HDL simulator
will execute the next callback to the MATLAB function.
iport Receives HDL signal values from the entity’s input port,
osc_in.
tnow Receives the current simulation time.
portinfo For the first call to the function, receives a structure that
describes the ports defined for the entity.
The following figure shows the relationship between the HDL entity’s ports
and the MATLAB function’s iport and oport parameters (example shown
is for use with ModelSim).
oport.filter1x_out
iport.osc_in osc_filter.vhd oport.filter4x_out
oport.filter8x_out
8-43
8 HDL Cosimulation Reference
portinfo.field1.field2.field3
The following table lists possible values for each field and identifies the port
types for which the values apply.
8-44
Test Bench and Component Function Options
The first call to the MATLAB function has three arguments including the
portinfo structure. Checking the number of arguments is one way you can
verify that portinfo was passed. For example:
if(nargin ==3)
tscale = portinfo.tscale;
end
8-45
8 HDL Cosimulation Reference
You will still experience block simulation latency for pure combinational
circuits even with direct feedthrough applied if your HDL design contains any
of the following conditions:
When you are simulating a sequential circuit that has a register on the
datapath from input port to output port, specifying direct feedthrough does
not affect the timing of that datapath.
Read the following sections to learn more about using direct feedthrough:
You can also examine the example “Simulate HDL Design with Pure
Combinational Datapath” to see how you might apply this feature.
8-46
Direct Feedthrough Cosimulation
4 Click Apply.
8-47
8 HDL Cosimulation Reference
Without direct feedthrough applied, the HDL output has a one-sample delay
compared with the Simulink reference signal, as shown in the following Scope
window.
8-48
Direct Feedthrough Cosimulation
This delay occurs from simulating a pure combinational HDL design without
applying direct feedthrough.
8-49
8 HDL Cosimulation Reference
8-50
Simulation Speed Improvement Tips
8-51
8 HDL Cosimulation Reference
8-52
Simulation Speed Improvement Tips
See “Working with Signals” in the DSP System Toolbox documentation for
detailed information about frame-based processing.
Use of frame-based signals affects only the Simulink side of the cosimulation.
The behavior of the HDL code under simulation in the HDL simulator does
not change in any way. Simulink assumes that HDL simulator processing is
sample based. Simulink assembles samples acquired from the HDL simulator
into frames as required. Conversely, Simulink transmits output data to the
8-53
8 HDL Cosimulation Reference
HDL simulator in frames, which are unpacked and processed by the HDL
simulator one sample at a time.
Specify VHDL signals as scalars values, not vectors or arrays (with the
exception of bit vectors. VHDL and Verilog bit vectors are converted to the
suitably-sized fixed-point scalar data type by the HDL Cosimulation block).
8-54
Simulation Speed Improvement Tips
\toolbox\edalink\extensions\modelsim\modelsimdemos\frame_filter_cosim
\toolbox\edalink\extensions\modelsim\modelsimdemos\VHDL\frame_demos\lp_fir_8k.vhd
The filter was designed with FDATool and the code was generated by the
Filter Design HDL Coder.
The Audio Source Signal From Workspace block provides an input signal
from the workspace variable mtlb. The block is configured for an 8 kHz
sample rate, with a frame size of 80, as shown in this figure.
8-55
8 HDL Cosimulation Reference
The sample rate and frame size of the input signal propagate throughout
the model.
The VHDL code file lp_fir_8k.vhd implements a simple lowpass FIR filter
with a cutoff frequency of 1500 Hz. The HDL Simulator block simulates this
HDL module. The HDL Simulator block ports and clock signal are configured
to match the corresponding signals on the VHDL entity.
8-56
Simulation Speed Improvement Tips
2 Set up and change to a writable working folder that is outside the context
of your MATLAB installation folder.
matlabroot\toolbox\edalink\extensions\modelsim\modelsimdemos\frame_cosim
8-57
8 HDL Cosimulation Reference
open frame_filter_cosim.mdl
6 Load the source speech signal, which will be filtered, into the MATLAB
workspace.
load mtlb
If you have a compatible sound card, you can play back the source signal by
typing the following commands at the MATLAB command prompt:
a = audioplayer(mtlb,8000);
play(a);
vsim
8 At the ModelSim prompt, create a design library, and compile the VHDL
filter code from the source file lp_fir_8k.vhd, by typing the following
commands:
vlib work
vmap work work
vcom lp_fir_8k.vhd
vsimulink lp_fir_8k
ans =
8-58
Simulation Speed Improvement Tips
2.7190
The timing in this code excerpt is typical for a run of this model given a
simulation Stop time of 1 second and a frame size of 80 samples. Timings
are system-dependent and will vary slightly from one simulation run to
the next.
Take note of the timing you obtained. For the next simulation run, you will
change the model to sample-based operation and obtain a comparative
timing.
11 MATLAB stores the filtered audio signal returned from ModelSim in the
workspace variable audiobuff1. If you have a compatible sound card, you
can play back the filtered signal to hear the effect of the lowpass filter. Play
the signal by typing the following commands at the MATLAB command
prompt:
b = audioplayer(audiobuff1,8000);
play(b);
12 Open the block parameters dialog box of the Audio Source Signal From
Workspace block and set the Samples per frame property to 1, as shown
in this figure.
8-59
8 HDL Cosimulation Reference
13 Close the dialog box, and select the Simulink window. Select
Simulation > Update diagram.
Now the source signal (and all signals inheriting from it) is a scalar.
restart
ans =
8-60
Simulation Speed Improvement Tips
3.8440
8-61
8 HDL Cosimulation Reference
8-62
Race Conditions in HDL Simulators
For cases where your active HDL clock edge and your intrinsic Simulink
active clock edges are at the same frequency, you can promote desired data
propagation by offsetting one of those edges. Because the Simulink sample
rates are always aligned with time 0, you can accomplish this offset by shifting
the active clock edge in the HDL off of time 0. If you are coding the clock
stimulus in HDL, use a delay operator ("after" or "#") to accomplish this offset.
When using a Tcl "force" command to describe the clock waveform, you can
simply put the first active edge at some nonzero time. Using a nonzero value
allows a Simulink sample rate that is the same as the fundamental clock rate
in your HDL. This example shows a 20 ns clock (so the Simulink sample rates
will also be every 20 ns) with an active positive edge that is offset from time
0 by 2 ns (example shown for use with Incisive):
For HDL Cosimulation blocks with Clock panes, you can define the clock
period and active edge in that pane. The waveform definition places the
non-active edge at time 0 and the active edge at time T/2. This placement
sets the maximum setup and hold times for a clock with a 50% duty cycle.
If the Simulink sample rates are at a different frequency than the HDL clocks,
then you must synchronize the signals between the HDL and Simulink as you
would do with any multiple time-domain design, even one in pure HDL. For
example, you can place two synchronizing flip-flops at the interface.
If your cosimulation does not include clocks, then you must also treat the
interfacing of Simulink and the HDL code as being between asynchronous
time domains. You may need to over-sample outputs to see that all data
transitions are captured.
8-63
8 HDL Cosimulation Reference
However, when you use the -time scheduling option to matlabtb or matlabcp,
or use "tnext" within the MATLAB function itself, the driving of signal values
or sampling of signal values cannot be guaranteed in relation to any HDL
signal changes. It is as if the potential race conditions in that time-based
scheduling are like an implicit clock that is unknown to the HDL engine and
not visible by just looking at the HDL code.
The remedies are the same as for the Simulink signal interfacing: make sure
that the sampling and driving of signals does not occur at the same simulation
times as the MATLAB function calls.
Further Reading
Problems interfacing designs from test benches and foreign languages,
including race conditions in pure HDL environments, are well-known and
extensively documented. Some texts that describe these issues include:
8-64
Data Type Conversions
To program a MATLAB function for an HDL model, you must understand the
type conversions required by your application. You may also need to handle
differences between the array indexing conventions used by the HDL you are
using and MATLAB (see following section).
The data types of arguments passed in to the function determine the following:
The following table summarizes how the HDL Verifier software converts
supported VHDL data types to MATLAB types based on whether the type is
scalar or array.
8-65
8 HDL Cosimulation Reference
8-66
Data Type Conversions
The following table summarizes how the HDL Verifier software converts
supported Verilog data types to MATLAB types. The software supports only
scalar data types for Verilog.
8-67
8 HDL Cosimulation Reference
bit 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
-
dim1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
dim2 4 4 4 4 3 3 3 3 2 2 2 2 4 4 4 4 3 3 3 3 2 2 2 2
dim3 8 7 6 5 8 7 6 5 8 7 6 5 8 7 6 5 8 7 6 5 8 7 6 5
bit 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
-
dim1 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
dim2 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3 3 3
dim3 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2
Therefore, if H is the HDL array and M is the MATLAB matrix, the following
indexed values are the same:
b1 H(0,4,8) = M(1,1,1)
b2 H(0,4,7) = M(2,1,1)
b3 H(0,4,6) = M(3,1,1)
b4 H(0,4,5) = M(4,1,1)
b5 H(0,3,8) = M(1,2,1)
b6 H(0,3,7) = M(2,2,1)
...
b19 H(1,3,6) = M(3,2,2)
b20 H(1,3,5) = M(4,2,2)
8-68
Data Type Conversions
datas(inc+1) = double(idata);
8-69
8 HDL Cosimulation Reference
Examples
The following code excerpt illustrates data type conversion of data passed
in to a callback:
8-70
Data Type Conversions
Note When data values are returned to the HDL simulator, the char array
size must match the HDL type, including leading zeroes, if applicable. For
example:
oport.signal = dec2mvl(2)
will only work if signal is a 2-bit type in HDL. If the HDL type is anything
else, you must specify the second argument:
oport.signal = dec2mvl(2, N)
Array of STD_LOGIC_VECTOR, Declare the data as an array of type character with a size that
STD_ULOGIC_VECTOR, is equivalent to the VHDL port size. See “Array Indexing
BIT_VECTOR, SIGNED, or Differences Between MATLAB and HDL” on page 8-68.
UNSIGNED
8-71
8 HDL Cosimulation Reference
iport.int = int32(1:10)';
REAL Declare the data as an array of type double with a size that is
equivalent to the VHDL port size. For example:
iport.dbl = ones(2,2);
8-72
Data Type Conversions
Character array for standard Use the dec2mvl function to convert the integer. For example:
logic or bit representation
oport.slva =dec2mvl([23 99],8)';
iport.bit = '1';
8-73
8 HDL Cosimulation Reference
Simulation Timescales
In this section...
“Overview to the Representation of Simulation Time” on page 8-74
“Defining the Simulink and HDL Simulator Timing Relationship” on page
8-75
“Setting the Timing Mode with HDL Verifier” on page 8-76
“Relative Timing Mode” on page 8-77
“Absolute Timing Mode” on page 8-82
“Timing Mode Usage Considerations” on page 8-84
“Setting HDL Cosimulation Block Port Sample Times” on page 8-86
• ModelSim Users:
To determine the current ModelSim resolution limit, enter echo
$resolution or report simulator state at the ModelSim prompt. You
can override the default resolution limit by specifying the -t option on the
ModelSim command line, or by selecting a different Simulator Resolution
in the ModelSim Simulate dialog box. Available resolutions in ModelSim
are 1x, 10x, or 100x in units of fs, ps, ns, us, ms, or sec. See the ModelSim
documentation for further information.
• Incisive Users:
To determine the current HDL simulator resolution limit, enter echo
$timescale at the HDL simulator prompt. See the HDL simulator
documentation for further information.
8-74
Simulation Timescales
The relationship between Simulink and the HDL simulator timing affects
the following aspects of simulation:
8-75
8 HDL Cosimulation Reference
signal rate on the Simulink model port to the lowest possible number of
HDL simulator ticks.
The Timescales pane lets you choose an optimal timing relationship between
Simulink and the HDL simulator, either by entering the HDL simulator
equivalent or by letting HDL Verifier calculate a timescale for you.
You can choose to have HDL Verifier calculate a timescale while you are
setting the parameters on the block dialog by clicking the Timescale option
then clicking Determine Timescale Now or you can have HDL Verifier
calculate the timescale when simulation begins by selecting Automatically
determine timescale at start of simulation.
The next figure shows the default settings of the Timescales pane (example
shown is for use with ModelSim).
8-76
Simulation Timescales
For instructions on setting the timing mode either manually or with the
Timescales dialog box, see the Timescales pane in the HDL Cosimulation
block reference.
8-77
8 HDL Cosimulation Reference
The following pseudocode shows how Simulink time units are converted to
HDL simulator ticks:
InTicks = N * tInSecs
where InTicks is the HDL simulator time in ticks, tInSecs is the Simulink
time in seconds, and N is a scale factor.
8-78
Simulation Timescales
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ENTITY inverter IS PORT (
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
8-79
8 HDL Cosimulation Reference
The next figure shows the ModelSim wave window after a cosimulation run
of the example Simulink model for 60 ns. The wave window shows that
ModelSim simulated for 60 ticks (60 ns). The inputs change at multiples of 24
ns and the outputs are read from ModelSim at multiples of 12 ns. The clock is
driven low and high at intervals of 5 ns.
Now consider a cosimulation of the same model, this time configured with a
scale factor of 100 in the Timescales pane.
The ModelSim wave window in the next figure shows that Simulink port
and clock times were scaled by a factor of 100 during simulation. ModelSim
simulated for 6 microseconds (60 * 100 ns). The inputs change at multiples of
24 * 100 ns and outputs are read from ModelSim at multiples of 12 * 100 ns.
The clock is driven low and high at intervals of 500 ns.
8-80
Simulation Timescales
8-81
8 HDL Cosimulation Reference
The previous example was excerpted from the HDL Verifier Inverter tutorial.
For more information, see HDL Verifier demos.
In absolute timing mode, all sample times and clock periods in Simulink are
quantized to HDL simulator ticks. The following pseudocode illustrates the
conversion:
8-82
Simulation Timescales
where:
8-83
8 HDL Cosimulation Reference
8-84
Simulation Timescales
The following example demonstrates how to set the timing relationship in the
1
following scenario: you want to use a sample period of in Simulink,
which corresponds to a noninteger time period. 3Hz
The key idea here is that you must always be able to relate a Simulink time
with an HDL tick. The HDL tick is the finest time slice the HDL simulator
recognizes; for ModelSim, the default tick is 1 ns, but it can be made as
precise as 1 fs.
8-85
8 HDL Cosimulation Reference
Therefore, the solution is to "snap" either the Simulink sample time or the
HDL sample time (via the timescale) to valid numbers. There are infinite
possibilities, but here are some possible ways to perform a snap:
• Change Simulink sample times from 1/3 sec to 0.33333 sec and set the
cosimulation block timescale to ’1 second in Simulink = 1 second in the
HDL simulator’. If you are specifying a clock in the HDL Cosimulation
block Clocks pane, its period should be 0.33333 sec.
• Keep Simulink sample times at 1/3 sec. and 1 second in Simulink = 6 ticks
in the HDL simulator.
- If you are specifying a clock in the HDL Cosimulation block Clocks
pane, its period should be 1/3. Briefly, this specification tells Simulink to
make each Simulink sample time correspond to every (1/3*6) = 2 ticks,
regardless of the HDL time resolution.
- If your default HDL simulator resolution is 1 ns, that means your HDL
sample times are every 2 ns. This sample time will work in a way so that
for every Simulink sample time there is a corresponding HDL sample
time.
- However, Simulink thinks in terms of 1/3 sec periods and the HDL in
terms of 2 ns periods. Thus, you could get confused during debug. If you
want this to match the real period (such as to 5 places, i.e. 333.33ms),
you can follow the next option listed.
• Keep Simulink sample times at 1/3 sec and 1 second in Simulink =
0.99999e9 ticks in the HDL simulator. If you are specifying a clock in the
HDL Cosimulation block Clocks pane, its period should be 1/3.
8-86
Simulation Timescales
• After Simulink sets the input port sample periods, it applies user-specified
output sample times to all output ports. Sample times must be explicitly
defined for all output ports.
8-87
8 HDL Cosimulation Reference
In the following example excerpt, the shaded area shows a clock, a reset, and
a clock enable signal as input to a multiple HDL Cosimulation block model.
These signals are created using two Simulink data type conversion blocks and
a constant source block, which connect to the HDL Cosimulation block labeled
"Manchester Receiver Subsystem".
8-88
Clock, Reset, and Enable Signals
Simulink attempts to create a clock that has a 50% duty cycle and a predefined
phase that is inverted for the falling edge case. If applicable, Simulink
degrades the duty cycle to accommodate odd Simulink sample times, with a
worst case duty cycle of 66% for a sample time of T=3.
8-89
8 HDL Cosimulation Reference
Whether you have configured the Timescales pane for relative timing mode
or absolute timing mode, the following restrictions apply to clock periods:
• If you specify an explicit clock period, you must enter a sample time equal
to or greater than 2 resolution units (ticks).
• If the clock period (whether explicitly specified or defaulted) is not an even
integer, Simulink cannot create a 50% duty cycle, and therefore the HDL
Verifier software creates the falling edge at
clockperiod / 2
(rounded down to the nearest integer).
The following figure shows a timing diagram that includes rising and falling
edge clocks with a Simulink sample time of T=10 and an HDL simulator
resolution limit of 1 ns. The figure also shows that given those timing
parameters, the clock duty cycle is 50%.
t
1 ns
HDL Simulator Resolution Limit
1 In the HDL simulator, determine the clock signal path names you plan to
define in your block. To do so, you can use the same method explained for
8-90
Clock, Reset, and Enable Signals
determining the signal path names for ports in step 1 of “Map HDL Signals
to Block Ports” on page 4-17.
2 Select the Clocks tab of the Block Parameters dialog box. Simulink
displays the dialog box as shown in the next figure (example shown for
use with Incisive).
4 Edit the clock signal path name directly in the table under the Full HDL
Name column by double-clicking the default clock signal name (/top/clk).
Then, specify your new clock using HDL simulator path name syntax. See
“Specify HDL Signal/Port and Module Paths for Cosimulation” on page
4-18.
The HDL simulator does not support vectored signals in the Clocks pane.
Signals must be logic types with 1 and 0 values.
8-91
8 HDL Cosimulation Reference
6 The Period field specifies the clock period. Accept the default (2), or
override it by entering the desired clock period explicitly by double-clicking
in the Period field.
7 When you have finished editing clock signals, click Apply to register your
changes with Simulink.
The following dialog box defines the rising-edge clock clk for the HDL
Cosimulation block, with a default period of 2 (example shown for use with
Incisive).
8-92
Clock, Reset, and Enable Signals
8-93
8 HDL Cosimulation Reference
8-94
TCP/IP Socket Ports
When you set up communication between computers, you must specify the
host name as well as the port name on the client side.
Examples:
<port-num> 4449
<port-alias> matlabservice
<host>:<port-num> compa:4449
<port-alias>@<host-ia> [email protected]
Note that TCP/IP port filtering on either the client or server side can cause
the HDL Verifier interface to fail to make a connection. If you get an error,
remove filtering (see OS user guide), or try a different port.
8-95
8 HDL Cosimulation Reference
8-96
9
System Objects
9-2
Create System Objects
flag = isChangedProperty(H,'Normalize')
The output data from the step method is stored in Y, which, in this case,
is the FFT of X.
9-3
9 System Objects
To display a particular property value, use the handle of the created object
followed by the property name: <handle>.<Name>.
Example
This example retrieves and displays the TransferFunction property value
for the previously created DigitalFilter object:
H.TransferFunction
9-4
Set Up System Objects
Note When you use Name-Value pair syntax, the object sets property values
in the order you list them. If you specify a dependent property value before its
parent property, an error or warning may occur.
H1 = dsp.DigitalFilter('CoefficientsSource','Input port')
where
H1.CoefficientsSource = 'Property'
or
set(H1,'CoefficientsSource','Property')
9-5
9 System Objects
same as the order in which the properties are displayed. Refer to the object
reference page for details.
H2 = dsp.FIRDecimator(3,[1 .5 1])
9-6
Process Data Using System Objects
Common Methods
All System objects support the following methods, each of which is described
in a method reference page associated with the particular object. In cases
where a method is not applicable to a particular object, calling that method
has no effect on the object.
9-7
9 System Objects
Method Description
step Processes data using the algorithm defined by the
object. As part of this processing, it initializes needed
resources, returns outputs, and updates the object
states. After you call the step method, you cannot
change any input specifications (i.e., dimensions, data
type, complexity). During execution, you can change
only tunable properties. The step method returns
regular MATLAB variables.
Example: Y = step(H,X)
release Releases any special resources allocated by the object,
such as file handles and device drivers, and unlocks
the object. For System objects, use the release
method instead of a destructor. See “Understand
System object Modes” on page 9-10.
clone Creates another object with the same property values
isLocked Returns a logical value indicating whether the object
is locked. See “Understand System object Modes” on
page 9-10.
reset Resets the internal states of the object to the initial
values for that object
isDone Applies to source objects only. Returns a logical value
indicating whether the step method has reached
the end of the data file. If a particular object does
not have end-of-data capability, this method value
returns false.
isChangedProperty Returns true if the specified tunable property value
has changed since the last call to step.Example: flag
= isChangedProperty(obj,'propertyName')
info Returns a structure containing characteristic
information about the object. The fields of this
structure vary depending on the object. If a particular
object does not have characteristic information, the
structure is empty.
9-8
Process Data Using System Objects
Method Description
getNumInputs Returns the number of inputs (excluding the object
itself) expected by the step method. This number
varies for an object depending on whether any
properties enable additional inputs.
getNumOutputs Returns the number of outputs expected from the step
method. This number varies for an object depending
on whether any properties enable additional outputs.
getDiscreteState Returns the discrete states of the object in a structure.
If the object is unlocked (when the object is first
created and before you have run the step method
on it or after you have released the object), the
states are empty. If the object has no discrete states,
getDiscreteState returns an empty structure.
These advantages make System objects particularly well suited for processing
streaming data, where segments of a continuous data stream are processed
iteratively. This ability to process streaming data provides the advantage of
not having to hold large amounts of data in memory. Use of streaming data
also allows you to use simplified programs that use loops efficiently.
9-9
9 System Objects
The object initializes and locks when it begins processing data. The typical
way in which an object becomes locked is when the step method is called on
that object. To determine if an object is locked, use the isLocked method. To
unlock an object, use the release method. When the object is locked, you
cannot change any of the following:
Several System objects do not allow changing the complexity of inputs from
real to complex. You can, however, change the input complexity from complex
to real without unlocking the object.
These restrictions allow the object to maintain states and allocate memory
appropriately.
9-10
Tuning System object™ Properties in MATLAB®
help dsp.FFT.Normalize
where
Note Unless otherwise specified, System object properties are not tunable.
For objects that do not support variable-size input, if you change the input
dimensions while the object is in locked mode, the object produces a warning
and unlocks. The object then reinitializes the next time you call the step
method. See the object’s reference page for more information. You can change
the value of a tunable property and the input size without a warning or error
being produced. For all other changes at runtime, an error occurs.
9-11
9 System Objects
9-12
FPGA-in-the-Loop
About FPGA-in-the-Loop
(FIL) Simulation
10 About FPGA-in-the-Loop (FIL) Simulation
Overview
FPGA-in-the-Loop (FIL) simulation provides the capability to use Simulink or
MATLAB software for testing designs in real hardware for any existing HDL
code. The HDL code can be either manually written or software generated
from a model subsystem.
You must have HDL code to perform FIL simulation. There are two FIL
workflows:
Note The FIL Wizard uses any synthesizable HDL code including code
automatically generated from Simulink models by HDL Coder software
• You have MATLAB code or a Simulink model and an HDL Coder license
(HDL workflow advisor).
Note When you use FIL in the Workflow Advisor, HDL Coder uses the
loaded design to create the HDL code.
10-2
FPGA-in-the-Loop (FIL) Simulation
No matter which workflow you choose, FIL performs the following processes
when it creates the block or System object:
• Generates a FIL block or FIL System object that represents the HDL code
• Provides synthesis, logical mapping, place-and-route (PAR), programming
file generation, and communications channel.
• Loads the design onto an FPGA
All these capabilities are specifically designed for a particular board and
tailored to your RTL code.
As part of FIL simulation, the block or System object and your model or
application:
10-3
10 About FPGA-in-the-Loop (FIL) Simulation
Note When programming the FPGA, HDL Verifier assumes that there is
only one download cable connected to the Host PC and it can be automatically
recognized by the FPGA programming software. If this is not the case, use
FPGA programming software to program your FPGA with the correct options.
System-Level View. All DUT I/Os are routed to Simulink through the FIL
comm logic.
10-4
FPGA-in-the-Loop (FIL) Simulation
Communication Channel
FIL provides the communication channel for sending and receiving data
between Simulink and the FPGA. This channel uses a Gigabit Ethernet
connection. Because communication between Simulink and the FPGA is
strictly synchronized, the FIL simulation provides a more dependable
verification method.
• Generates HDL code for the specified DUT and creates an ISE project.
• Along with your FPGA design software, synthesizes, maps, places and
routes, and creates a programming file for the FPGA.
• Downloads the programming file to the FPGA on the development board
through the board’s normal configuration connection. Typically, that
connection is a serial line over a USB cable (see board manufacturer’s
instructions for how to make this connection).
- For FIL simulation blocks, clicking Load on the FIL block mask initiates
the programming file download.
10-5
10 About FPGA-in-the-Loop (FIL) Simulation
10-6
11
FIL Preparation
Note The FIL Wizard uses any synthesizable HDL code including code
automatically generated from Simulink models by HDL Coder software
• You have MATLAB code or a Simulink model and an HDL Coder license
(HDL workflow advisor).
Note When you use FIL in the Workflow Advisor, HDL Coder uses the
loaded design to create the HDL code.
For either workflow, the first three steps are the same:
For the next step, click on the link for the workflow you are going to follow:
• If you have existing HDL code, select block or System object generation
using the FIL Wizard:
- “FIL Block Generation” on page 12-2
- “FIL System Object Generation” on page 12-12
• If you need the HDL workflow advisor to generate HDL code, select block
or System object generation using HDL workflow advisor:
11-2
FPGA-in-the-Loop Simulation Workflows
Note To use the HDL Coder HDL workflow advisor for Simulink to generate
a FIL interface, you must have an HDL Coder license.
11-3
11 FIL Preparation
Next Steps
• If you are creating a FIL System object, next go to “Apply FIL System
Object Requirements” on page 11-5.
• If you are creating a FIL block, next go to “Apply FIL Block Requirements”
on page 11-10.
11-4
Prepare DUT For FIL Interface Generation
Next Steps
• If you are creating a FIL System object, next go to “Apply FIL System
Object Requirements” on page 11-5.
• If you are creating a FIL block, next go to “Apply FIL Block Requirements”
on page 11-10.
11-5
11 FIL Preparation
Note If a design does not fit in the device or does not meet timing goals, the
software may not be able to create the programming file. In such situations,
you may see a warning that the design does not meet the timing goals, but
it will still generate a programming file, or you may get an error and no
programming file. Either make changes to some part of your design, or use a
different development board.
After FIL interface generation is complete, you can use the method
programFPGA to load the programming file to the FPGA board and make any
adjustments to runtime options and signal attributes.
When you are ready to begin, read through the following topics and make sure
your DUT adheres to the rules and guidelines described in each section:
When you are finished with these sections, next go to either “FIL System
Object Generation” on page 12-12 or “FIL with HDL Workflow Advisor In
MATLAB” on page 13-9.
11-6
Prepare DUT For FIL Interface Generation
Category Considerations
HDL files All HDL names must be legal as defined in the VHDL
1993 standard.
Top-level design • The top-level design must be VHDL or Verilog.
• The top-level HDL file should contain an entity/module
with the same name as the file name.
• FIL block generation supports both combinatorial
and sequential logic. For combinatorial logic, CLK,
CLK_ENABLE, and RESET are not required.
Inputs and • Input and output ports should be of the following
outputs types:
- std_logic (VHDL)
- std_logic_vector (VHDL)
- Reg, wire (Verilog)
• Vector ports range must be:
- Descending (e.g. 9 DOWNTO 0, 9:0)
- Literal (e.g. (a DOWNTO b) is not supported)
- Descending TO syntax is not supported
• For Verilog, ports names must be lowercase. Module
name must be lowercase, also.
• All input and output ports should be included.
• There must be at least one output port.
11-7
11 FIL Preparation
Category Considerations
Clock • Sequential HDL design must have only one clock
at the top entity. Clock and reset are required. For
combinatorial HDL design, the clock bundle is not
required.
• Clock should be named: clock or clk. Using these
names is not a requirement, but if the clock is not
named clock or clk, you must designate which signal
is the clock signal in the FIL Wizard.
• Clock port should be 1-bit. For VHDL, it must be of
type std_logic.
Reset • The HDL design must have a reset to be able to reset
the FPGA prior to simulation.
• For sequential design, there should be only one reset.
Clock and reset are required. For combinatorial HDL
design, the clock bundle is not required.
• Reset should be named: reset or rst. Using these
names is not a requirement, but if the reset is not
named reset or rst, you must designate which signal
is the reset signal in the FIL Wizard.
• Reset port should be 1-bit. For VHDL, these ports
must be of type std_logic.
Clock enable • For sequential design, if you choose a clock enable,
there should be only one.
• Clock enable port should be 1-bit. For VHDL, these
ports must be of type std_logic.
• If you have a clock enable, it should be named one
of the following: clock_enable, clock_enb, clock_en,
clk_enable, clk_enb, clk_en, ce. Using these names
is not a requirement, but if the clock enable is not
named one of these names, you must designate which
signal is the clock enable signal in the FIL Wizard.
11-8
Prepare DUT For FIL Interface Generation
Category Considerations
DUT entity All the ports at DUT level should be well defined and the
bit width should be specified. Using a variable as the bit
width is not allowed.
Clock edge Clock the DUT input and output ports by positive edge.
Negative edge is not allowed.
Non-supported • Bidirectional ports
data types
• Arrays, record types
Non-supported • VHDL configuration statement
constructs
• Verilog include files
• Macros
• Escaped names
• Generics (VHDL), Parameters (Verilog)
• Duplicated port names (Verilog)
FIL input and • Total input must be less than 1467 bytes
output data set
Where total input data set equals the sum of the input
limits
size rounded up to bytes
• Output data set must also be less than 1467 bytes
Where total output data set equals the sum of the
output size rounded up to bytes * overclocking factor
Output frame The frame size is calculated by the following formula:
size output frame size = input frame size * overclocking /
downsample
11-9
11 FIL Preparation
• Integer
• Logical
• Fixed point
11-10
Prepare DUT For FIL Interface Generation
Note If a design does not fit in the device or does not meet timing goals, the
software may not be able to create the programming file. In such situations,
you may see a warning that the design does not meet the timing goals, but
it will still generate a programming file, or you may get an error and no
programming file. Either make changes to some part of your design, or use a
different development board.
After FIL interface generation is complete, you can use the FIL block mask to
load the programming file to the FPGA board and make any adjustments to
runtime options and signal attributes.
When you are ready to begin, read through the following topics and make sure
your DUT adheres to the rules and guidelines described in each section:
When you are finished with these sections, next go to “FIL Block Generation”
on page 12-2 or “FIL with HDL Workflow Advisor In Simulink” on page 13-2.
Category Considerations
HDL files All HDL names must be legal as defined in the VHDL
1993 standard.
Top-level design • The top-level design must be VHDL or Verilog.
• The top-level HDL file should contain an entity/module
with the same name as the file name.
• FIL block generation supports both combinatorial
and sequential logic. For combinatorial logic, CLK,
CLK_ENABLE, and RESET are not required.
11-11
11 FIL Preparation
Category Considerations
Inputs and • Input and output ports should be of the following
outputs types:
- std_logic (VHDL)
- std_logic_vector (VHDL)
- Reg, wire (Verilog)
• Vector ports range must be:
- Descending (e.g. 9 DOWNTO 0, 9:0)
- Literal (e.g. (a DOWNTO b) is not supported)
- Descending TO syntax is not supported
• For Verilog, ports names must be lowercase. Module
name must be lowercase, also.
• All input and output ports should be included.
• There must be at least one output port.
Clock • Sequential HDL design must have only one clock
at the top entity. Clock and reset are required. For
combinatorial HDL design, the clock bundle is not
required.
• Clock should be named: clock or clk. Using these
names is not a requirement, but if the clock is not
named clock or clk, you must designate which signal
is the clock signal in the FIL Wizard.
• Clock port should be 1-bit. For VHDL, it must be of
type std_logic.
11-12
Prepare DUT For FIL Interface Generation
Category Considerations
Reset • The HDL design must have a reset to be able to reset
the FPGA prior to simulation.
• For sequential design, there should be only one reset.
Clock and reset are required. For combinatorial HDL
design, the clock bundle is not required.
• Reset should be named: reset or rst. Using these
names is not a requirement, but if the reset is not
named reset or rst, you must designate which signal
is the reset signal in the FIL Wizard.
• Reset port should be 1-bit. For VHDL, these ports
must be of type std_logic.
Clock enable • For sequential design, if you choose a clock enable,
there should be only one.
• Clock enable port should be 1-bit. For VHDL, these
ports must be of type std_logic.
• If you have a clock enable, it should be named one
of the following: clock_enable, clock_enb, clock_en,
clk_enable, clk_enb, clk_en, ce. Using these names
is not a requirement, but if the clock enable is not
named one of these names, you must designate which
signal is the clock enable signal in the FIL Wizard.
DUT entity All the ports at DUT level should be well defined and the
bit width should be specified. Using a variable as the bit
width is not allowed.
Clock edge Clock the DUT input and output ports by positive edge.
Negative edge is not allowed.
11-13
11 FIL Preparation
Category Considerations
Non-supported • Bidirectional ports
data types
• Arrays, record types
Non-supported • VHDL configuration statement
constructs
• Verilog include files
• Macros
• Escaped names
• Generics (VHDL), Parameters (Verilog)
• Duplicated port names (Verilog)
Category Considerations
General model • Use Single tasking solver mode (set with Configuration
rules Parameters). HDL Verifier FIL does not support
multitasking solver mode.
• Choose discrete, fixed-step solvers or variable-step
solvers. HDL Verifier FIL supports both types of
solvers.
Incompatibilities Be aware that HDL Verifier FIL simulation currently
with Simulink does not support the following:
11-14
Prepare DUT For FIL Interface Generation
Category Considerations
11-15
11 FIL Preparation
• OCF =
fastest_dut_sample_rate/fastest_input_sample_rate
Or
• OCF = input_sample_time /
fastest_dut_sample_time
Where sample_time = 1/samplerate.
11-16
Prepare DUT For FIL Interface Generation
1/1500
11-17
11 FIL Preparation
1 Make sure that the power switch is OFF and remains OFF.
3 Plug the power supply adapter cable into the FPGA development board.
4 Use the JTAG download cable to connect the FPGA development board
with the computer.
6 Make sure that all jumpers on the FPGA development board are in the
factory default position.
Note When programming the FPGA, HDL Verifier assumes that there is
only one download cable connected to the Host PC and it can be automatically
recognized by the FPGA programming software. If this is not the case, use
FPGA programming software to program your FPGA with the correct options.
11-18
Set Up Hardware and Hardware Tools
one method. Choose one of the following setup instructions based on the
connection method you are going to use for FIL
JTAG Connection
1 If you are using Linux, make sure that the Quartus II 64-bit library
folder (for example, /usr/local/quartus/linux64) is on the path in the
LD_LIBRARY_PATH environment variable before you start MATLAB.
Ethernet Connection
Follow these instructions to set up a Gigabit Ethernet network adapter on
your computer for FIL simulation.
Windows 7 Setup
1 Open the Control Panel and type "view network connections" in the search
bar. Select View network connections in the search results.
2 Right-click the connection icon to your FPGA development board, and select
Properties from the pop-up menu.
11-19
11 FIL Preparation
11-20
Set Up Hardware and Hardware Tools
Your TCP/IP properties should look similar to those shown in the following
figure:
11-21
11 FIL Preparation
2 Click Network and Sharing Center, and then click Manage network
connections.
3 Right-click the connection icon to your FPGA development board, and select
Properties from the pop-up menu.
11-22
Set Up Hardware and Hardware Tools
Windows XP Setup
3 Right-click the connection icon to your FPGA development board, and select
Properties from the pop-up menu.
Linux Setup
Use the ifconfig command to set up your local address. For example:
In this example, eth1 is the second Ethernet adapter on the Linux computer.
Check your system to determine which Ethernet adapter is connected to the
FPGA development board. The above command sets the local IP address to
11-23
11 FIL Preparation
• Windows:
This example assumes that the Xilinx ISE design suite is installed at
C:\Xilinx\14.2\ISE_DS\ISE\bin\nt64.
• Linux:
This example assumes that the Xilinx ISE design suite is installed at
/local/Xilinx/14.2/ISE_DS/ISE/bin/lin64.
Note If you are using the miniBEE® BEEcube® hardware platform, make
sure you have the latest firmware for the miniBEE BEEcube board. See the
vendor site if you need to download this firmware.
Altera
Set up your system environment for accessing from MATLAB with the
function hdlsetuptoolpath. For example:
This example assumes that the Altera® FPGA design software is installed
at C:\Altera\12.0\quartus\bin64.
11-24
FPGA Reset
FPGA Reset
The following table lists which push button on the FPGA board is connected
to the reset pin.
11-25
11 FIL Preparation
11-26
12
>> filWizard
filWizard('./Subsystem_fil/Subsystem_fil.mat')
12-2
FIL Interface Generation with the FIL Wizard
2 Board Name: Select an FPGA development board. If you have not yet
downloaded an HDL Verifier FPGA board support package, see “FPGA
Board Support Packages for FIL” on page 16-2. (If you do not see any
boards listed, then you have not yet downloaded a support package). If you
plan to define a custom board yourself, see “FPGA Board Customization”
on page 17-2.
12-3
12 FIL Interface Generation and Simulation
4 Advanced Options
Option Instructions
Board IP address Use this option for setting the board’s IP address
if it is not the default IP address (192.168.0.2).
You may need to change your computer’s IP
address to a different subnet from 192.168.0.x
when you set up the network adapter. You would
also need to change the address if the default
board IP address 192.168.0.2 is in use by another
device.. If so, change the Board IP address
according to the following guidelines:
12-4
FIL Interface Generation with the FIL Wizard
Option Instructions
5 Click Next.
12-5
12 FIL Interface Generation and Simulation
1 Specify the HDL design to be cosimulated in the FPGA. These are the HDL
design files to be verified on the FPGA board.
Indicate source files by clicking Add. Select files using the file selection
dialog.
12-6
FIL Interface Generation with the FIL Wizard
The FIL Wizard attempts to identify the source files; if any of the file types
is not what you wanted, you can change it by selecting from the drop-down
list at File Type. Acceptable file types are:
• VHDL
• Verilog
• Netlist
• Tcl script
• Constraints
• Others
"Others" refers to the following:
– For Altera, any files specified here as Other are added to the FPGA
project, but they have no impact on the generated block. For example,
you can put some comments in a “readme” file and include it in this
file list.
– For Xilinx, any files specified here as Other may be any file accepted
by Xilinx ISE. ISE looks at the file extension to determine how to use
this file. For example, if you add foo.vhd to the list and specify it as
Other, ISE will treat the file as a VHDL file.
Check the box on the row of the HDL file that contains the top-level HDL
module in the column titled Top-level. The FIL Wizard automatically fills
the Top-level module name field with the name of the selected HDL file.
If the top-level module name and file name do not match, you can manually
change the top-level module name in this dialog box. You must indicate the
top-level module before the FIL Wizard can continue.
3 (Optional) To display the full paths to the source files, check the box titled
Show full paths to source files.
4 Click Next.
12-7
12 FIL Interface Generation and Simulation
1 Review the port listing. The FIL Wizard parses the top-level HDL module
to obtain all the I/O ports and display them in the DUT I/O Ports table.
The parser attempts to automatically determine the possible port types by
checking the port names. The wizard then displays these signals under
Port Type.
12-8
FIL Interface Generation with the FIL Wizard
Reset, or, if desired, a Clock enable signal. The port types specified in
this table must be the same as in the HDL code. There must be at least
one output port.
Click Regenerate to reload the table with the original port definitions
(from the HDL code).
2 Click Next.
12-9
12 FIL Interface Generation and Simulation
1 Specify output data types. The wizard attempt to do this for you; if any
output data type is not what you expected, you can manually change the
type.
2 Click Next.
12-10
FIL Interface Generation with the FIL Wizard
• Specify the folder for the output files. You can use the default option.
Usually the default is a sub-folder named after the top-level module,
located under the current directory.
• Note the Summary displays the locations of the ISE project file and the
FPGA programming file. You may need those two files for advanced
operations on the FIL block mask.
12-11
12 FIL Interface Generation and Simulation
1 The FIL Wizard generates a FIL block named after the top-level module
and places it in a new model.
2 After new model generation, the FIL Wizard opens a command window.
• In this window, the FPGA design software performs synthesis, fit, PAR,
timing analysis, and FPGA programming file generation.
• When the process completes, a message in the command window
prompts you to close the window.
12-12
FIL Interface Generation with the FIL Wizard
Xilinx ISE
Set up your system environment for accessing Xilinx ISE from MATLAB with
the function hdlsetuptoolpath. This function adds the required folders to
the MATLAB search path using the Xilinx installation folder as its argument.
For example:
This example assumes that the Xilinx ISE design suite is installed at
C:\Xilinx\14.2\ISE_DS\ISE\bin\nt64.
Altera
Set up your system environment for accessing from MATLAB with the
function hdlsetuptoolpath. For example:
This example assumes that the Altera FPGA design software is installed
at C:\Altera\12.0\quartus\bin64.
>> filWizard
filWizard('./Subsystem_fil/Subsystem_fil.mat')
12-13
12 FIL Interface Generation and Simulation
(This page is for FIL System object. For Simulink block FIL options, see “Step
3: Set FIL Options for FIL Block” on page 12-3.)
2 Board Name: Select an FPGA development board. If you have not yet
downloaded an HDL Verifier FPGA board support package, see “FPGA
Board Support Packages for FIL” on page 16-2. (If you do not see any
boards listed, then you have not yet downloaded a support package). If you
12-14
FIL Interface Generation with the FIL Wizard
3 Advanced Options
Option Instructions
Board IP address Use this option for setting the board’s IP address
if it is not the default IP address (192.168.0.2).
You may need to change your computer’s IP
address to a different subnet from 192.168.0.x
when you set up the network adapter. You would
also need to change the address if the default
board IP address 192.168.0.2 is in use by another
device.. If so, change the Board IP address
according to the following guidelines:
12-15
12 FIL Interface Generation and Simulation
Option Instructions
4 Click Next.
12-16
FIL Interface Generation with the FIL Wizard
(This page is for FIL System object. For Simulink block HDL source files, see
“Step 4: Add HDL Source Files for FIL Block” on page 12-6.)
1 Specify the HDL design to be cosimulated in the FPGA. These are the HDL
design files to be verified on the FPGA board.
12-17
12 FIL Interface Generation and Simulation
Indicate source files by clicking Add. Select files using the file selection
dialog.
The FIL Wizard attempts to identify the source files; if any of the file types
is not what you wanted, you can change it by selecting from the drop-down
list at File Type. Acceptable file types are:
• VHDL
• Verilog
• Netlist
• Tcl script
• Constraints
• Others
"Others" refers to the following:
– For Altera, any files specified here as Other are added to the FPGA
project, but they have no impact on the generated System object. For
example, you can put some comments in a “readme” file and include it
in this file list.
– For Xilinx, any files specified here as Other may be any file accepted
by Xilinx ISE. ISE looks at the file extension to determine how to use
this file. For example, if you add foo.vhd to the list and specify it as
Other, ISE will treat the file as a VHDL file.
Check the box on the row of the HDL file that contains the top-level HDL
module in the column titled Top-level. The FIL Wizard automatically fills
the Top-level module name field with the name of the selected HDL file.
If the top-level module name and file name do not match, you can manually
change the top-level module name in this dialog box. You must indicate the
top-level module before the FIL Wizard can continue.
3 (Optional) To display the full paths to the source files, check the box titled
Show full paths to source files.
4 Click Next.
12-18
FIL Interface Generation with the FIL Wizard
(This page is for FIL System object. For Simulink block verify DUT I/O ports,
see “Step 5: Verify DUT I/O Ports for FIL Block” on page 12-8.)
1 Review the port listing. The FIL Wizard parses the top-level HDL module
to obtain all the I/O ports and display them in the DUT I/O Ports table.
The parser attempts to automatically determine the possible port types by
12-19
12 FIL Interface Generation and Simulation
checking the port names. The wizard then displays these signals under
Port Type.
Click Regenerate to reload the table with the original port definitions
(from the HDL code).
2 Click Next.
12-20
FIL Interface Generation with the FIL Wizard
(This page is for FIL System object. For Simulink block output types, see
“Step 6: Specify Output Types for FIL Block” on page 12-10.)
1 Specify output data types. The wizard attempts to do this for you; if any
output data type is not what you expected, you can manually change the
type.
12-21
12 FIL Interface Generation and Simulation
Select from:
• Fixedpoint
• Integer
• Logical
2 Click Next.
12-22
FIL Interface Generation with the FIL Wizard
(This page is for FIL System object. For Simulink block build options, see
“Step 7: Specify Build Options for FIL Block” on page 12-11.)
• Specify the folder for the output files. You can use the default option.
Usually the default is a sub-folder named after the top-level module,
located under the current directory.
12-23
12 FIL Interface Generation and Simulation
• Note the Summary displays the locations of the ISE project file and the
FPGA programming file. You may need those two files for advanced
operations on the FIL System object.
function toplevel_programFPGA
12-24
FIL Interface Generation with the FIL Wizard
%
% fft8_fil methods:
%
% step - See above description for use of this method
% release - Allow property value and input characteristics changes, and
% release connection to FPGA board
% clone - Create fft8_fil object with same property values
% isLocked - Locked status (logical)
% programFPGA - Load the programming file in the FPGA
%
% fft8_fil properties:
%
% DUTName - DUT top level name
% InputSignals - Input paths in the HDL code
% InputBitWidths - Width in bit of the inputs
% OutputSignals - Output paths in the HDL code
% OutputBitWidths - Width in bit of the outputs
% OutputDataTypes - Data type of the outputs
% OutputSigned - Sign of the outputs
% OutputFractionLengths - Fraction lengths of the outputs
% OutputDownsampling - Downsampling factor and phase of the outputs
% OverclockingFactor - Overclocking factor of the hardware
% SourceFrameSize - Frame size of the source (only for HDL source block)
% Connection - Parameters for the connection with the board
% FPGAVendor - Name of the FPGA chip vendor
% FPGABoard - Name of the FPGA board
% FPGAProgrammingFile - Path of the Programming file for the FPGA
% ScanChainPosition - Position of the FPGA in the JTAG scan chain
%
% File Name: fft8_fil.m
% Created: 26-Apr-2012 18:18:06
%
% Generated by FIL Wizard
properties (Nontunable)
DUTName = 'fft8';
end
methods
function obj = fft8_fil
12-25
12 FIL Interface Generation and Simulation
• In this window, the FPGA design software performs synthesis, fit, PAR,
and FPGA programming file generation.
• When the process completes, a message in the command window
prompts you to close the window.
12-26
Perform FPGA-in-the-Loop Simulation
12-27
12 FIL Interface Generation and Simulation
2 Double-click the FIL block in your Simulink model to open the block mask.
3 On the Main tab, click Load to download the programming file to the
FPGA.
The load process may take from a few minutes to several minutes or longer,
depending on how large the subsystem is. Sometimes, the process can take
an hour and a half or longer for large subsystems.
4 If your board is connected to the host computer through the JTAG cable,
a message window appears. It indicate that the FPGA programming file
has loaded as expected. Click OK.
If you are using an Ethernet connection, you can test if the FPGA board
is connected to your host computer through the ping test. Launch a
command-line window, and enter the following command:
If you changed the board IP address when you set up the network adapter,
replace 192.168.0.2 with your board IP address. If the Gigabit Ethernet
connection has been set up, you should see the ping reply from the FPGA
development board.
12-28
Perform FPGA-in-the-Loop Simulation
On Linux hosts, to program the bit file onto Altera boards, you would normally
need to be a superuser. This can impose testing restriction on these boards.
However, there is a way to avoid being a superuser to program the bit file.
# Altera USB-Blaster
12-29
12 FIL Interface Generation and Simulation
• Option 2: Add the following lines to any of the rule files already existing
under /etc/udev/rules.d/
# Altera USB-Blaster
Run Simulation
In Simulink, click Simulation > Run or the Run Simulation button in your
Simulink model window. The results of the FIL simulation should match
those of the Simulink reference model or of the original HDL code.
Note Regarding initialization: Simulink starts from time 0 every time, which
means the RAM in Simulink is initialized to zero. However, this is not true in
hardware. If you have RAM in your design, the first simulation will match
Simulink, but any subsequent runs may not match.
MYFIL - toplevel_fil
12-30
Perform FPGA-in-the-Loop Simulation
MYFIL.set('FPGAProgrammingFile','c:\work\filfiles')
MYFIL.FPGAProgrammingFile='c:\work\filfiles'
• Edit toplevel_fil.m directly, but then you must instantiate the object
again, if you had already done so previously.
• programFPGA function:
./toplevel_fil/toplevel_programFPGA
• programFPGA method:
MYFIL.programFPGA
Run Simulation
1 Write your MATLAB code to use the System object, if you haven’t already
done so.
2 Run your MATLAB code as you normally would. Make sure you have
followed“Ethernet Connection” on page 11-19 before beginning.
The first call to the step method establishes communication with the FPGA
board.
12-31
12 FIL Interface Generation and Simulation
12-32
13
Note You must have an HDL Coder license to generate HDL code using
the HDL Workflow Advisor.
3 For Folder, enter the folder name where the project files are to be placed.
The default is hdl_prj under the current working folder.
13-2
FIL with HDL Workflow Advisor In Simulink®
13-3
13 FIL Using HDL Coder HDL Workflow Advisor
• FPGA-in-the-Loop Connection:
- For all Xilinx supported boards, the connection is set to Ethernet.
- For Altera boards that support only a JTAG connection, the connection
is set to JTAG
- For Altera board that support either a JTAG or an Ethernet connection,
the connection is set to Ethernet but you may change it to JTAG.
• Board Address:
When an Ethernet connection is selected, you can adjust the board IP and
MAC addresses, if necessary.
Address Instructions
Board IP address Use this option for setting the board’s IP address
if it is not the default IP address (192.168.0.2).
You may need to change your computer’s IP
address to a different subnet from 192.168.0.x
when you set up the network adapter. You
would also need to change the address if the
default board IP address 192.168.0.2 is in use by
another device. If so, change the Board IP address
according to the following guidelines:
13-4
FIL with HDL Workflow Advisor In Simulink®
Address Instructions
13-5
13 FIL Using HDL Coder HDL Workflow Advisor
13-6
FIL with HDL Workflow Advisor In Simulink®
• The HDL Workflow Advisor generates a FIL block named after the top-level
module and places it in a new model. The next figure shows an example of
the new model containing the FIL block.
13-7
13 FIL Using HDL Coder HDL Workflow Advisor
• After new model generation, the HDL Workflow Advisor opens a command
window:
- In this window, the FPGA design software performs synthesis, fit, PAR,
timing analysis, and FPGA programming file generation.
- When the process completes, a message in the command window
prompts you to close the window.
• The HDL Workflow Advisor builds a testbench model around the generated
FIL block.
13-8
FIL with HDL Workflow Advisor In MATLAB®
Note You must have an HDL Coder license to generate HDL code using
the HDL Workflow Advisor.
2 Log outputs for comparison plots: This optional selection lets you log
and plot the outputs of the reference design function and the FPGA.
13-9
13 FIL Using HDL Coder HDL Workflow Advisor
3 Board Name: Select one of the FPGA development boards. If you have
not yet downloaded an HDL Verifier FPGA board support package, select
Get more boards. Then return to this step after you have downloaded
an FPGA board support package.
4 Connection:
Address Instructions
Board IP Address Use this option for setting the board’s IP address
if it is not the default IP address (192.168.0.2).
You may need to change your computer’s IP
address to a different subnet from 192.168.0.x
when you set up the network adapter. You
would also need to change the address if the
default board IP address 192.168.0.2 is in use by
another device. If so, change the Board IP address
according to the following guidelines:
13-10
FIL with HDL Workflow Advisor In MATLAB®
Address Instructions
6 Additional files
Enter the names of any additional source files for the DUT. If you have
more than one additional source file, use the ... button to add more.
If you want the HDL Workflow Advisor to launch the FIL simulation, check
the box for Simulate generated FPGA-in-the-Loop test bench.
13-11
13 FIL Using HDL Coder HDL Workflow Advisor
13-12
FIL with HDL Workflow Advisor In MATLAB®
13-13
13 FIL Using HDL Coder HDL Workflow Advisor
13-14
14
Troubleshooting
FPGA-in-the-Loop
14 Troubleshooting FPGA-in-the-Loop
Troubleshooting FIL
If you get a message or error at any time during the FIL process (from
generating the FIL block to running the simulation), consult one of the
following tables for a possible reason and solution.
RAM in design Simulink starts from The workaround is to reload the FPGA before
does not time 0 every time, which re-running the simulation.
match up means the RAM in
to Simulink Simulink is initialized to
RAM zero. However, this is not
after first true in hardware. If you
simulation have RAM in your design,
run the first simulation will
match Simulink, but any
subsequent runs may not
match.
14-2
Troubleshooting FIL
14-3
14 Troubleshooting FPGA-in-the-Loop
Failed to load The Altera Quartus II Put the Altera Quartus II executables on the
shared library executables are not on the system path. If using Linux, make sure that the
sld_hapi.dll system path. Quartus II library is on LD_LIBRARY_PATH
(JTAG before you start MATLAB
connection)
Failed to load Two possible reasons: • Make sure you are using Altera Quartus II
shared library version 13.1 or higher on the host computer.
• The version of Altera
libsld_hapi_dll_loader.so
• Make sure that the Quartus II library is on
(JTAG Quartus II on the
LD_LIBRARY_PATH before you start MATLAB
connection) host computer is not
supported.
• The Altera Quartus II
executables are not on
the system path.
Unable to find JTAG cable is not Use the JTAG download cable to connect the FPGA
the JTAG connected. It is also development board with the computer.
communication possible that the JTAG
cable attached cable is defective.
to the host
computer
(JTAG
connection)
14-4
Troubleshooting FIL
14-5
14 Troubleshooting FPGA-in-the-Loop
14-6
15
FIL Examples
• MATLAB
• Simulink
• Fixed-Point Designer
• HDL Verifier
• FPGA design software (Xilinx® ISE® design suite or Altera® Quartus® II
design software)
• One of the supported FPGA development boards and accessories
• For connection using Ethernet: Gigabit Ethernet Adapter installed on host
computer, Gigabit Ethernet crossover cable
• For connection using JTAG: JTAG cable with USB Blaster I or II, USB
Blaster driver
Prerequisites:
MATLAB® and FPGA design software can either be locally installed on your
computer or on a network accessible device. If you use software from the
network you will need a second network adapter installed in your computer
to provide a private network to the FPGA development board. Consult the
hardware and networking guides for your computer to learn how to install
the network adapter.
15-2
Verify HDL Implementation of PID Controller Using FPGA-in-the-Loop
2 Connect the AC power cord to the power plug. Plug the power supply
adapter cable into the FPGA development board.
4 Use the JTAG download cable to connect the FPGA development board
with the computer.
5 Make sure that all jumpers on the FPGA development board are in the
factory default position.
Skip this step if you are using JTAG connection for simulation. For connection
with Ethernet, you must have a Gigabit Ethernet network adapter on your
computer to run this example.
3 Right click the connection icon to your FPGA development board and select
Properties from the pop-up menu.
15-3
15 FIL Examples
2 Click Network and Sharing Center, and then click Manage network
connections.
3 Right click the connection icon to your FPGA development board and select
Properties from the pop-up menu.
3 Right click the connection icon to your FPGA development board and select
Properties from the pop-up menu.
On Linux®:
Use the ifconfig command to set up your local address. For example:
15-4
Verify HDL Implementation of PID Controller Using FPGA-in-the-Loop
In this example, eth1 is the second Ethernet adapter on the Linux computer.
Check your system to determine which Ethernet adapter is connected to the
FPGA development board. The above command sets the local IP address to
192.168.0.1. If this address is in use by another computer on your network,
change it to any available IP address on this subnet, such as 192.168.0.100.
Set up an examples folder, copy example files, set up access to FPGA design
software, and open model.
1. Create a folder outside the scope of your MATLAB installation folder into
which you can copy the example files. The folder must be writable. This
example assumes that the folder is located at C:\MyTests.
2. Start MATLAB and set the current directory in MATLAB to the folder you
just created. For example:
cd C:\MyTests
copyFILDemoFiles('pid')
• D_component.vhd
• I_component.vhd
• Controller.vhd
15-5
15 FIL Examples
Run this model now and observe the desired and actual motor positions in
the scope.
From the Code menu in the fil_pid model window, select Verification
Wizards -> FPGA-in-the-Loop (FIL)....
15-6
Verify HDL Implementation of PID Controller Using FPGA-in-the-Loop
filWizard
2. For Board Name, select the FPGA development board connected to your
host computer. If your board is not on the list, select one of the following
options:
• "Get more boards..." to download the FPGA board support package(s) (this
option starts the Support Package Installer).
• "Create custom board..." to create the FPGA board definition file for your
particular FPGA board (this option starts the New FPGA Board Manager).
3. Select the connection for simulation. The available connection methods are
Ethernet and JTAG. Not all boards support both connection methods.
• The subnet address, typically the first three bytes of board IP address,
must be the same as those of the host IP address.
• The last byte of the board IP address must be different from that of the
host IP address.
15-7
15 FIL Examples
• The board IP address must not conflict with the IP addresses of other
computers.
For example, if the host IP address is 192.168.8.2, then you can use
192.168.8.3 if it is available. Do not change Board MAC address.
1. Click Add and browse to the directory you created in Prepare Example
Resources.
• Controller.vhd
• D_component.vhd
• I_component.vhd
These are the HDL design files to be verified on the FPGA board. 3. In the
Source Files table, check the checkbox on the row of file Controller.vhd to
specify that this HDL file contains the top-level HDL module.
The FIL Wizard automatically fills the Top-level module name field with
the name of the selected HDL file; in this case, Controller. In this example,
the top-level module name matches the file name so that you do not need to
change it. If the top-level module name and file name did not match, you
would manually correct the top-level module name in this dialog.
15-8
Verify HDL Implementation of PID Controller Using FPGA-in-the-Loop
The FIL Wizard parses the top-level HDL module Controller in Controller.vhd
to obtain all the I/O ports and display them in the DUT I/O Ports table. The
parser attempts to automatically determine the possible port types by looking
at the port names and displays these signals under Port Type.
1. Review the port listing. If the parser assigned an incorrect port type for
any given port, you can manually change the signal. For synchronous design,
specify a Clock, Reset, or Clock enable signal. In this example, the FIL Wizard
automatically fills the table correctly.
1. Specify the folder for the output files. For this example, use the default
option, which is a subfolder named Controller_fil under the current
directory.
The Summary displays the locations of the ISE project file and the FPGA
programming file. You may need those two files for advanced operations.
15-9
15 FIL Examples
• After new model generation, the FIL Wizard opens a command window
where the FPGA design software performs synthesis, fit, place-and-route,
timing analysis, and FPGA programming file generation.
In the fil_pid model, replace the Controller subsystem with the FIL block
generated in the new model. The modified fil_pid model now appears as
shown in the following illustration:
2. Double-click the FIL block in the fil_pid model to open the block mask.
15-10
Verify HDL Implementation of PID Controller Using FPGA-in-the-Loop
If your board is connected to the host computer through the JTAG cable
properly, a message window displays to indicate that the FPGA programming
file is loaded successfully. Click OK to dismiss this dialog.
4. Ethernet connection only: You can test if the FPGA board is connected to
your host computer properly through the ping test. Launch a command-line
window and enter the following command:
If you changed the board IP address when you set up the network adapter,
replace 192.168.0.2 with your board IP address. If the Gigabit Ethernet
connection has been set up properly, you should see the ping reply from the
FPGA development board.
2. When the simulation is done, view the waveform of the desired and actual
positions of the motor in the scope. Note that the results of FIL simulation
should match those of the Simulink reference model that you simulated in
Prepare Example Resources.
15-11
15 FIL Examples
Requirements
• MATLAB
• Simulink
• HDL Verifier
• Fixed-Point Designer
• Signal Processing Toolbox
• DSP System Toolbox
• Filter Design HDL Coder (optional)
• FPGA design software (Xilinx® ISE® design suite or Altera® Quartus® II
design software)
• One of the supported FPGA development boards and accessories (the
ML403 board is not supported for this example)
• For connection using Ethernet: Gigabit Ethernet Adapter installed on host
computer, Gigabit Ethernet crossover cable
• For connection using JTAG: JTAG cable with USB Blaster I or II, USB
Blaster driver
15-12
Verify Digital Up-Converter Using FPGA-in-the-Loop
15-13
15 FIL Examples
hcic.inputfraclength = 15;
The frequency response of the cascade filter is shown in the following figure.
fvtool(hduc);
When the cascade filter is ready, generate HDL code for the DUC using
the Filter Design HDL Coder function generatehdl, with the property
’AddPipelineRegisters’ set to ’on’.
This option inserts pipeline registers between filter stages, and allows the
generated filter to be synthesized at a higher clock frequency.
If you do not have Filter Design HDL Coder, you can copy pre-generated HDL
files to the current directory using this command:
>> copyFILDemoFiles('duc');
15-14
Verify Digital Up-Converter Using FPGA-in-the-Loop
The FIL Wizard guides you in configuring settings necessary for building
FPGA-in-the-Loop. Launch the wizard with the following command:
>> filWizard
2. In Source Files, add the following generated HDL files for the DUC to
the source file table using Browse.
hdlduc.vhd
hdlduc_stage1.vhd
hdlduc_stage2.vhd
hdlduc_stage3.vhd
3. In DUT I/O Ports, the input and output port information, such as port
name, direction, width and port type are automatically generated from the
HDL file. Port types, such as Clock and Data, are generated based on port
names; you may change the selection as necessary. For this example, the
generated port types are correct, and you can click Next.
4. In Build Options, specify the folder for FIL output files. You can use the
default value for this example. Click Build. Clicking Build causes the FIL
15-15
15 FIL Examples
The FPGA project compilation process takes several minutes. When the
process is finished, you are prompted to close the command-line window.
Close this window now.
1. Open the test bench model fil_duc_model and copy the generated FIL
block into the model.
2. Double-click the FIL block to open the block mask. Click Load to program
the FPGA with the generated programming file.
4. On the FIL block mask, click on the Signal Attributes tab. Change the data
type for filter_out to fixdt(1,20,-1) to match the data type of the behavioral
filter block.
15-16
Verify Digital Up-Converter Using FPGA-in-the-Loop
Run simulation. Observe the output waveforms from the behavioral filter
block, the FIL block, and the error margin. Because the behavioral filter
block does not have pipeline registers, there are small differences between
the behavioral filter block output and the FIL block output. These errors
are within the error margin.
15-17
15 FIL Examples
15-18
16
You download FPGA board support packages using the Support Package
Installer. See “Support Packages and Support Package Installer” on page
16-12.
After you have downloaded an FPGA board support package, you can use
“FPGA-in-the-Loop (FIL) Simulation” on page 10-2.
16-2
Support Package for BEEcube® miniBEE® Hardware Platform
• The FIL workflow generates a Xilinx binary FPGA programming file (BIN)
for the miniBEE hardware.
• FIL uses the SelectMAP executable from BEEcube for programming the
FPGA.
• The generated FIL HDL code for miniBEE employs the BEEcube PCI
Express IP for connection.
• The FIL host uses the BEEcube PCI Express driver to communicate with
the FPGA board.
The FPGA board support package for BEEcube miniBEE hardware platform
is also supported for FIL with HDL Coder, for the following workflows:
• Simulink–to–HDL
• MATLAB–to–HDL
16-3
16 HDL Verifier FPGA Board Support Packages
16-4
Support Package for BEEcube® miniBEE® Hardware Platform
16-5
16 HDL Verifier FPGA Board Support Packages
16-6
Open Examples for This Support Package
16-7
16 HDL Verifier FPGA Board Support Packages
Note For other types of examples, open the Help browser and search for your
product name followed by “examples”.
16-8
Open Examples for This Support Package
16-9
16 HDL Verifier FPGA Board Support Packages
Before starting, select a computer to use for downloading. This computer must
have the same base product license and platform as the computers upon which
you are installing the support package. For example, suppose you want to
install a Simulink support package on a group of computers that are running
64-bit Windows. To do so, you must first download the support package using
a computer that has a Simulink license and is running 64-bit Windows.
This action creates a subfolder within the Download folder that contains
the files required for each support package.
5 Make the new folder available to for installation on other computers. For
example, you can share the folder on the network, or copy the folder to
portable media, such as a USB flash drive.
16-10
Install This Support Package on Other Computers
3 Click Browse to specify the location of the support package folder on the
network or portable media.
16-11
16 HDL Verifier FPGA Board Support Packages
A support package file has a *.zip extension. This type of file contains
MATLAB files, MEX files, and other supporting files required to install the
support package. Use Support Package Installer to install these support
package files.
16-12
Support Packages and Support Package Installer
You can start Support Package Installer in one of the following ways:
16-13
16 HDL Verifier FPGA Board Support Packages
16-14
17
Feature Description
Both HDL Coder and HDL Verifier software include a set of predefined FPGA
boards you can use with the Turnkey or FPGA-in-the-Loop (FIL) workflows
(you can view the lists of these supported boards in the HDL Workflow
Advisor or in the FIL Wizard). With the FPGA Board Manager, you can add
additional boards to use either of these workflows. All you need to add a board
is the relevant information from the board specification documentation.
The FPGA Board Manager is the hub for accessing wizards and dialog
boxes that take you through the steps necessary to create a custom board
configuration. You can also access options to import a custom board, remove a
board, make a copy of a board for further modification, and verify a new board.
To begin, review the “FPGA Board Requirements” on page 17-3 and then
follow the steps described in “Create Custom FPGA Board Definition” on
page 17-8.
17-2
FPGA Board Customization
FPGA Device
Select one of the following links to view a current list of supported FPGA
device families:
The following MathWorks tools are required to use FIL or FPGA Turnkey.
17-3
17 FPGA Board Customization
• Clock: An external clock connected to the FPGA is required. The clock can
be differential or single-ended. The accepted clock frequency is from 5
MHz to 300 MHz. When used with FIL, there are additional requirements
to the clock frequency (see “Ethernet Connection Requirements for
FPGA-in-the-Loop” on page 17-4).
• Reset: An external reset signal connected to the FPGA is optional. When
supplied, this signal functions as the global reset to the FPGA design.
• JTAG download cable: A JTAG download cable that connects host PC
and FPGA board is required for the FPGA programming. The FPGA must
be programmable using Xilinx iMPACT or Altera Quartus II.
Supported Ethernet PHY Device. On the FPGA board, the Ethernet MAC
is implemented in FPGA. An Ethernet PHY chip is required to be on the
FPGA board to connect the physical medium to the Media ACcess (MAC)
layer in the FPGA.
Note When programming the FPGA, HDL Verifier assumes that there is
only one download cable connected to the Host PC and it can be automatically
recognized by the FPGA programming software. If this is not the case, use
FPGA programming software to program your FPGA with the correct options.
The FIL feature is tested with the following Ethernet PHY chips and may not
work with other Ethernet PHY devices.
17-4
FPGA Board Customization
Ethernet PHY Interface. The Ethernet PHY chip must be connected to the
FPGA using one of the following interfaces:
Interface Note
Gigabit Media Independent Interface Only 1000 Mbits/s speed is
(GMII) supported using this interface.
Reduced Gigabit Media Independent Only 1000 Mbits/s speed is
Interface (RGMII) supported using this interface.
Serial Gigabit Media Independent Only 1000 Mbits/s speed is
Interface (SGMII) supported using this interface.
Media Independent Interface (MII) Only 100 Mbits/s speed is supported
using this interface.
Note For GMII, the TXCLK (clock signal for 10/100 Mbits signal) signal is
not required because only 1000 Mbits/s speed is supported.
The RGMII v2.0 standard allows the transmitter to integrate this delay so
that PC board delay is not required. Marvell Alaska 88E1111 has internal
17-5
17 FPGA Board Customization
registers to add internal delays to RX and TX clocks. The internal delays are
not added by default. This means you use the MDIO module to configure
Marvell 88E1111 to add internal delays. (See “FIL I/O” on page 17-32 for the
usage of the MDIO module.)
Not all external clock frequencies can derive an exact 125 MHz clock
frequency. The acceptable clock frequencies vary depending on the FPGA
device family. The recommended clock frequencies are 50, 100, 125, and 200
MHz.
Hardware.
Software.
• Altera Quartus II
- Windows
Requires Quartus II version 13.0 or higher, Quartus II executable
directory must be on system path
- Linux
Requires Quartus II version 13.1 or higher, Quartus II library directory
must be on LD_LIBRARY_PATH before starting MATLAB, only 64-bit
Quartus are supported
17-6
FPGA Board Customization
17-7
17 FPGA Board Customization
For validation, you must have Xilinx or Altera on your path. Use the
function hdlsetuptoolpath to configure the tool for use with MATLAB.
For example:
3 Open the New FPGA Board Wizard by clicking Create New Board. For a
description of all the tasks you can perform with the FPGA Board Manager,
see “FPGA Board Manager” on page 17-23.
5 Save the board definition file. This is the last step and is automatically
instigated when you click Finish in the New FPGA Board Wizard. See
“Save Board Definition File” on page 17-18.
Your custom board definition now appears in the list of available FPGA
Boards in the FPGA Board Manager. If you are using HDL Workfow Advisor,
it also shows in the Target platform list.
Follow the example “Create Xilinx KC705 Evaluation Board Definition File”
on page 17-9 for a demonstration of adding a custom FPGA board with the
New FPGA Board Manager.
17-8
Create Xilinx KC705 Evaluation Board Definition File
Overview
For FPGA-in-the-Loop, you can use your own qualified FPGA board even if
is not in the pre-registered FPGA board list supplied by MathWorks. Using
the New FPGA Board Wizard, you can create a board definition file that
describes your custom FPGA board.
In this example, you can follow the workflow of creating a board definition file
for the Xilinx KC705 evaluation board to use with FIL simulation.
17-9
17 FPGA Board Customization
This example uses the KC705 Evaluation Board for the Kintex-7 FPGA
User Guide, published by Xilinx.
• For validation, you must have Xilinx or Altera on your path. Use the
function hdlsetuptoolpath to configure the tool for use with MATLAB.
For example:
• If you want to verify programming the FPGA board after you add its
definition file, you will need to have the custom board attached to your
computer. However, having the board connected is not necessary for
creating the board definition file.
>>fpgaBoardManager
2 Click Create Custom Board to open the New FPGA Board Wizard.
17-10
Create Xilinx KC705 Evaluation Board Definition File
17-11
17 FPGA Board Customization
17-12
Create Xilinx KC705 Evaluation Board Definition File
The information you just entered can be found in the KC705 Evaluation
Board for the Kintex-7 FPGA User Guide.
2 Click Next.
a Select FIL Interface. This option is required for using your board with
FPGA-in-the-Loop.
b Select GMII in the PHY Interface Type. This option indicates that
the onboard FPGA is connected to the Ethernet PHY chip via a GMII
interface.
c Leave the User-defined I/O option in the FPGA Turnkey Interface
section unchecked. FPGA Turnkey workflow is not the focus of this
example.
d Clock Frequency: Enter 200. Note that this Xilinx KC705 board has
multiple clock sources. This 200 MHz clock is one of the recommended
clock frequencies for use with Ethernet interface (50, 100, 125, and
200 MHz).
e Clock Type: Select Differential.
h Resent Pin Number: Enter AB7. This will supply a global reset to
the FPGA.
i Active Level: Select Active-High.
You can obtain all necessary information from the board design
specification.
17-13
17 FPGA Board Customization
2 Click Next.
Note that pin numbers for RXD and TXD signals are entered from the
least significant digit (LSD) to the most significant digit (MSB), separated
by a comma.
17-14
Create Xilinx KC705 Evaluation Board Definition File
17-15
17 FPGA Board Customization
5 Click Next.
17-16
Create Xilinx KC705 Evaluation Board Definition File
Note For validation, you must have Xilinx or Altera on your path. Use the
function hdlsetuptoolpath to configure the tool for use with MATLAB. For
example:
2 If you have the board attached, check the Include FPGA board in the
test option. You will need to supply the IP address of the FPGA Board.
This example assumes the Xilinx KC705 board is attached to your host
computer and it has an IP address of 192.168.0.2.
3 Click Run Selected Test(s). The tests will take about 10 minutes to
complete.
17-17
17 FPGA Board Customization
17-18
Create Xilinx KC705 Evaluation Board Definition File
17-19
17 FPGA Board Customization
2 You can view the new board in the board list from either the FIL Wizard or
the HDL Workflow Advisor.
a Start the FIL Wizard from the MATLAB prompt.
>>filWizard
The Xilinx KC705 board appears in the board list and you can select it
for FPGA-in-the-Loop simulation.
17-20
Create Xilinx KC705 Evaluation Board Definition File
The Xilinx KC705 board appears in the board list and you can select it
for FPGA-in-the-Loop simulation.
17-21
17 FPGA Board Customization
17-22
FPGA Board Manager
Introduction
The FPGA Board Manager is the portal to managing custom FPGA boards.
You can create a new board definition file or edit an existing one. You can
even import a custom board from an existing board definition file.
You start the FPGA Board Manager by one of the following methods:
17-23
17 FPGA Board Customization
17-24
FPGA Board Manager
Filter
Choose one of the following views:
• All boards
• Only those that were preinstalled with HDL Verifier or HDL Coder
• Only custom boards
Search
Find a specific board in the list or those boards that fully or partially match
your search string.
3 When the download is complete, you can see the new boards in the board
list in the FPGA Board Manager.
17-25
17 FPGA Board Customization
View/Edit
View board configurations and modify the information. You may view a
read-only file but not edit it. See “FPGA Board Editor” on page 17-39.
Remove
Remove custom board from the list. This action does not delete the board
definition XML file.
Clone
Makes a copy of an existing custom board for further modification.
Validate
Runs the validation tests for FIL See “Run Optional Validation Tests” on
page 17-16.
17-26
New FPGA Board Wizard
Adding Boards Once for Multiple Users To add new boards globally,
follow these instructions. Note that to access a board added globally, all users
must be using the same MATLAB installation.
matlabroot/toolbox/shared/eda/board/boardfiles
3 After copying the XML file, restart MATLAB. The new board appears in
the FPGA board list for either or both the FIL and Turnkey workflows.
All boards under this directory will show-up in the FPGA board list
automatically for users with the same MATLAB installation. You do not need
to use FPGA Board Manager to add these boards again.
The workflow for adding a new FPGA board contains these steps:
17-27
17 FPGA Board Customization
In this section...
“Basic Information” on page 17-29
“Interfaces” on page 17-30
“FIL I/O” on page 17-32
“Turnkey I/O” on page 17-34
“Validation” on page 17-37
“Finish” on page 17-38
17-28
New FPGA Board Wizard
Basic Information
Device Information:
17-29
17 FPGA Board Customization
- Package: Use the board specification file to select the correct package.
- Speed: Use the board specification file to select the correct speed.
- JTAG Chain Position: Value indicates the starting position for JTAG
chain. Consult the board specification file for this information.
Interfaces
• FIL Interface: To use this board with FIL, select this option. Next, select
one of the following PHY Interface types:
- Gigabit Ethernet — GMII
17-30
New FPGA Board Wizard
Note Not all interfaces are available for all boards. Availability depends
on the board you selected in Basic Information.
• FPGA Turnkey Interface: If you want to use with board with the HDL
Coder FPGA Turnkey workflow, select User-defined I/O.
• FPGA Input Clock. Clock details are required for both workflows. You
can find all necessary information in the board specification file.
- Clock Frequency. Must be between 5 and 300. For an Ethernet
interface, the suggested clock frequencies are 50, 100, 125, and 200 MHz.
- Clock Pin Number . Must be specified. Example: N10.
- Clock Type : Single_Ended or Differential.
• Reset (Optional). If you want to indicate a reset, find the pin number and
active level in the board specification file, and enter that information.
- Reset Pin Number. Leave empty if you do not have one.
- Active Level : Active-Low or Active-High.
17-31
17 FPGA Board Customization
FIL I/O
Signal List: You must provide all the FPGA pin numbers for the specified
signals. You can find this information in the board specification file. For
vector signals, list all pin numbers on the same line, separated by commas.
Generate MDIO module to override PHY settings: See the next section
on FPGA Board Management Data Input/Output Bus (MDIO) to determine
when to use this feature. If you do select this option, enter the PHY address.
17-32
New FPGA Board Wizard
Currently only the Marvell 88E1111 PHY chip is supported by this MDIO
module implementation. Do not select this checkbox if you are not using
Marvell 88E1111.
• GMII mode: The PHY device can start up using other modes, such as
RGMII/SGMII. The generated MDIO module sets the PHY chip in GMII
mode.
• RGMII mode: The PHY device can start up using other modes, such as
GMII/SGMII. The generated MDIO module sets the PHY device in RGMII
mode. In addition, the module sets the PHY chip to add internal delay
for RX and TX clocks.
• SGMII mode: The PHY device can start up using other modes, such as
RGMII/GMII. The generated MDIO module sets the PHY chip in SGMII
mode.
• MII mode: The generated MDIO module sets the PHY device in GMII
compatible mode. The module also sets the autonegotiation register to
remove the 1000 Base-T capability advertisement. This reset ensures that
the autonegotiation process does not select 1000 Mbits/s speed, which is
not supported in MII mode.
17-33
17 FPGA Board Customization
Specifying the PHY Address: The PHY address is a 5-bit integer. The
value is determined by the CONFIG[0] and CONFIG[1] pin on Marvell
88E1111 PHY device. See the board manual for this value.
Turnkey I/O
Note You provide FIL I/O for an Ethernet connection only. You must define
at least one output port for the Turnkey I/O interface.
17-34
New FPGA Board Wizard
Signal List: You must provide all the FPGA pin numbers for the specified
signals. You can find this information in the board specification file. For
vector signals, list all pin numbers on the same line, separated by commas.
The number of pin numbers must match the bit width of the corresponding
signal.
Add New: You are prompted to enter all entries in the signal list manually.
Add Using Template: The wizard prepopulates a new signal entry for
UART, LED, GPIO, or DIP Switch signals with the following:
The following example demonstrates using the Add Using Template feature.
3 Pull down the I/O list and select from the following options:
17-35
17 FPGA Board Customization
4 Click OK.
5 The wizard adds the specified signal (or signals) to the I/O list.
17-36
New FPGA Board Wizard
Validation
FPGA-in-the-Loop Test
17-37
17 FPGA Board Customization
Finish
When you have completed validation, click Finish. See “Save Board
Definition File” on page 17-18.
17-38
FPGA Board Editor
In this section...
“General” on page 17-39
“Interface” on page 17-41
General
17-39
17 FPGA Board Customization
Device Information:
• FPGA Input Clock. Clock details are required for both the FIL and
Turnkey workflows. You can find all necessary information in the board
specification file.
- Clock Frequency. Must be between 5 and 300. For an Ethernet
interface, the suggested clock frequencies are 50, 100, 125, and 200 MHz.
- Clock Pin Number . Must be specified. Example: N10.
- Clock Type : Single_Ended or Differential.
• Reset (Optional). If you want to indicate a reset, find the pin number and
active level in the board specification file, and enter that information.
- Reset Pin Number. Leave empty if you do not have one.
- Active Level : Active-Low or Active-High.
17-40
FPGA Board Editor
Interface
The Interface page describes the supported FPGA I/O Interfaces. Select any
listed interface and click View to see the Signal List. If the board definition
file has write permission, you can also Add New interface or Remove an
interface.
17-41
17 FPGA Board Customization
17-42
SystemC TLM 2.0 Generation
18-2
TLM Generation Algorithms
18-3
18 How TLM Component Generation Works
The following diagram illustrates the complete set of articles you can generate
including the TLM component, the TLM component test bench, and the set of
test vectors to be executed by the test bench. Simulink generates these vectors
while performing model execution when you verify the TLM component from
within Simulink (see “Run TLM Component Test Bench” on page 22-8).
18-4
The TLM Generation Process
18-5
18 How TLM Component Generation Works
3 (Optional) If you want, restore any desired configuration sets at this time.
Because the topic of configuration sets is outside the scope of this workflow
description, refer to the section "Overview of Model Referencing" in the
Simulink documentation.
18-6
Generated TLM Files
• C/C++ code containing the Simulink model behavior (.cpp and .h files)
• Virtual platform TLM component class (.cpp and .h files)
• TLM component documentation (HTML)
• TLM component test bench (if specified) (.cpp and .h files)
• Test bench stimulus and expected response vectors (MATLAB formatted
data)
• Makefiles for building the TLM component and standalone test bench
(makefile format)
18-7
18 How TLM Component Generation Works
After code generation is complete, you can then use these generated files
(outputs) to create the standalone TLM executable. See “Export TLM
Component” on page 23-4.
18-8
19
TLM Component
Architecture
19 TLM Component Architecture
The following diagram illustrates the simplest behavior you can specify for
the generated TLM component. It contains no memory map or command and
status register and executes transactions immediately.
19-2
TLM Component Architecture
There are a number of options you can use to control the architecture of
the generated TLM component. Incorporating a memory map is one of the
most effective options. The following figure demonstrates the behavior of a
generated TLM component with a full complement of features enabled.
19-3
19 TLM Component Architecture
You can set options for the following TLM component features:
19-4
TLM Component Architecture
Memory Mapping
• “No Memory Map” on page 19-5
• “Automatically Generated Memory Map with Single Address” on page 19-7
• “Automatically Generated Memory Map with Individual Addresses” on
page 19-9
No Memory Map
The no memory map option generates a TLM component with only one read
and one write register without any address. The Simulink model inputs are
represented by the write register and the outputs are represented by the
read register.
19-5
19 TLM Component Architecture
Without a memory map, the generated TLM component has the following
characteristics:
19-6
TLM Component Architecture
• When input registers are full, this condition triggers (schedules) execution
of the behavior in the SystemC simulator. Output registers are handled
the same way.
• All defaults for commands and status are applied.
When you generate the TLM component with this option, you can use it in
a virtual platform (VP) as:
19-7
19 TLM Component Architecture
The Simulink model inputs are represented by the write register, and
the outputs are represented by the read register. HDL Verifier software
automatically assigns the addresses required to access those specific registers
during code generation. Those addresses give the specific offsets required to
address each individual register via read and write operations. Definition of
the base address for the entire generated TLM component should be defined
by the virtual platform that the TLM component resides in. The offset address
definitions appear in a definition file that is generated along with the TLM
component.
With a single address memory map, the generated TLM component has the
following characteristics:
• Has a single input register and a single output register, and optional
command and status register and test and set register.
• Must have an address in the read and write requests during SystemC
simulation to select specific registers on the device.
- Receives all input data in a single write request, and a read request
receives all output data in the return value
• Has input and output registers either sized to hold an entire data set
required or created by the TLM component when it executes the behavior
(algorithm step function) in your virtual platform environment
• If a command and status register is not used or if the command and status
register is used and the default values apply, when input register is full,
content is pushed into buffer, which then triggers (schedules) execution of
the behavior in the SystemC simulator. If the command and status register
19-8
TLM Component Architecture
is used and the Push Input Command is set to 1, the initiator module
moves the input data set from the input register to the input buffer. Output
registers are handled the same way.
• If a command and status register is not used, all defaults for commands
and status are applied.
When you generate the TLM component with this option, you can use it in a
virtual platform (VP) as a standalone component in a test bench, or you can
attach it to a communication channel.
19-9
19 TLM Component Architecture
With an individual address memory map, the generated TLM component has
the following characteristics:
• Each input register and each output register has its own address as well as
an optional command and status register and test and set register.
• Must have an address in the read and write requests during SystemC
simulation to select specific registers on the device.
- Each input and output register must be accessed individually.
19-10
TLM Component Architecture
• Initiator module can write or read each input and output register in
multiple and/or partial transactions.
• The size of each input and output register is the size of the data.
• Execution is triggered when all input has been written or when command
and set register bits are set to Automatic. If set to manual, the initiator
module moves the input data set from the input register to the input buffer.
• Output registers are refreshed when all output registers have been read
or when command and set registers bits are set to Automatic. If set to
manual, the initiator module moves the output data set from the output
buffer to the output register.
When you generate the TLM component with this option, you can use it in a
virtual platform (VP) as a standalone component in a test bench, or you can
attach it to a communication channel.
Write-Only Bits
Write-only (WO) bits assert mutually exclusive commands. You can assert
only one command bit in any single write operation to the CSR. If more than
one command bit is set in the write to the CSR, the command is undefined.
You activate each command by writing a 1 to a command bit in the register.
Then, each command bit is automatically cleared after the command has been
executed. You do not have to write a 0 to the register to clear a command bit.
Write-Only bits are always returned as 0 in any read of the CSR. Writing a
command does not overwrite the Read/Write or Write-Only bits.
Read-and-Write Bits
Use Read and Write (R/W) bits to obtain the current status and setting. R/W
bit are sticky, meaning that after you set them by writing a 1 to the bit in the
register, an R/W bit remains set until a 0 is written to the same bit or the
19-11
19 TLM Component Architecture
A single write operation to the CSR sets all Read-and-Write bits in the
register. You can choose to set only some of the bits and maintain the
previous values of others. Before you do so, you must first read the CSR and
then modify the values according to your requirements. After you complete
modifications, you can write the entire 32 bits back to the CSR.
Read-Only Bits
Read-Only (RO) bits provide status information. The generated TLM
component automatically sets and clears their values, and an initiator module
can read them to learn status. Read-Only bits do not change their actual
values during any read or write of the CSR.
Register Definition
The following table contains the entire register definition.
19-12
TLM Component Architecture
19-13
19 TLM Component Architecture
19-14
TLM Component Architecture
19-15
19 TLM Component Architecture
19-16
TLM Component Architecture
19-17
19 TLM Component Architecture
19-18
TLM Component Architecture
Interrupt
You can choose to have an interrupt signal added to the generated TLM
component. The TLM component will assert this signal whenever new outputs
are available in any output register. The signal is automatically cleared
whenever a value is read from any output register.
The Interrupt signal is an ordinary SystemC boolean signal active high. The
Interrupt Active bit in the Status Register reflects the state of the interrupt
signal.
Algorithm Execution
You can choose between having a SystemC thread or a callback function in
your generated TLM component.
• SystemC thread: When the input buffers are full or when you write
a specific command in the command and status register and event is
triggered that the system scheduler picks up. It then executes that
19-19
19 TLM Component Architecture
Introduction
The TLM generator allows you to enable or disable input and output
data buffering between the TLM component interface and the algorithm
processing. For the cases when you have selected temporal decoupling, see
“Temporal Decoupling” on page 19-22.
Register
When you disable buffering, the TLM Component reads and writes inputs
and outputs directly from the interface register during algorithm processing.
Do not allow an initiator to perform a read or write of the registers during
algorithm processing; this action could corrupt the processing results. After
the initiator writes all input registers (if in AUTO mode) or when the initiator
writes the START command in the CSR, the algorithm begins processing.
HDL Verifier generates all timings using a SystemC wait function.
19-20
TLM Component Architecture
Buffering
When you enable buffering, the TLM component queues the inputs and
the outputs in FIFOs between the interface and the algorithm processing.
You define the depth of the FIFOs in the TLM generator GUI. The TLM
component pushes the content of the input registers in the input queue under
either of the following conditions:
• After the initiator writes all input registers (if in AUTO mode)
• When the initiator writes the PUSH command in the CSR
The component replaces the content of the output registers with new outputs
coming from the output queue (if any are available) under either of the
following conditions:
• After the initiator reads all output registers (if in AUTO mode)
• When the initiator writes the PULL command in the CSR
19-21
19 TLM Component Architecture
Temporal Decoupling
• “Temporal Decoupling Overview” on page 19-22
• “Temporal Decoupling and No Buffering” on page 19-24
• “Temporal Decoupling and Buffering” on page 19-25
19-22
TLM Component Architecture
simulation time. Because the use of temporal decoupling can change the event
order and process execution order, the simulation could lose some accuracy.
In this first diagram, the simulation does not use temporal decoupling.
Without temporal decoupling, all the threads execute in sequential order and
to exchange the three data the component requires nine context switches.
19-23
19 TLM Component Architecture
With temporal decoupling, the TLM component modifies the execution order.
To exchange the three data, the simulation only requires three context
switches. It only requires three context switches because each thread must
reach the end of its quantum before giving control back to the simulation.
Even with temporal decoupling, the events and data exchanged between each
thread happen at the same simulation time as without temporal decoupling.
The component does not trigger events immediately but stores them in
temporal queues with a timestamp (built using the local time converted into
simulation time). When the triggering time is due, the queue triggers the
event at the exact simulation time.
For cases when you do not select temporal decoupling, see “Register and
Buffering” on page 19-20.
19-24
TLM Component Architecture
19-25
19 TLM Component Architecture
and the algorithm processing. You define the simulated depth of the FIFOs
in the TLM generator GUI. When a thread writes data in those queues, the
queue sorts the data by timestamp. In order to reproduce the behavior of a
FIFO that allows queuing of data in the limit of its simulated depth, when a
thread reads the queue, it receives the last Nth written data before its actual
local time (where N is the FIFO depth) . Imagine the FIFO depth as a sliding
window: the data a particular thread is viewing is limited to the simulated
depth of the FIFO and its view of the data moves or "slides" forward as local
time advances. The following image illustrates a FIFO temporal queue:
The TLM component also queues all events exchanged between the interface
and the processing parts of the TLM component in temporal queues. HDL
Verifier generates all timings using a timing annotation to the local time.
19-26
TLM Component Architecture
At runtime, you can dynamically control the TLM component via a backdoor
interface to enable and disable the return of timing information. See the
generated test bench code for details (locate mw_backdoorcfg_IF).
19-27
19 TLM Component Architecture
19-28
20
For this example, we use a Simulink model of a FIR filter as the basis of
the SystemC/TLM generation.
• MATLAB
• Simulink
• Simulink Coder
• HDL Verifier
• SystemC 2.3 (includes the TLM library)
Open the FIR Filter model or, in the MATLAB command window, execute
the following:
>> openTlmgDemoModel('intro');
20-2
Getting Started with TLM Generator
c. Under System target file, click Browse to select the TLM generator
target. You can choose tlmgenerator_grt.tlc to use Simulink Coder or
tlmgenerator_ert.tlc to use Embedded Coder for HDL Code generation. For
this example, select tlmgenerator_grt.tlc.
• TLM Mapping
• TLM Processing
• TLM Timing
• TLM Testbench
• TLM Compilation
In the TLM Mapping tab, Socket Mapping allows you to select the number
of sockets for input data, output data, and control. Select the option, Three
separate TLM sockets for input data, output data, and control.
20-3
20 Getting Started with TLM Component Generation
The TLM Socket options allow you to define three different memory maps
for your generated TLM component.
For this example, select the following for the input and output data sockets:
• Auto-generated memory map for the input and output data sockets
• Individual input and output address offsets for each data socket.
This option generates a TLM component with one read register per model
output and one write register per model input with individual addresses.
Each Simulink model input is bound to its corresponding write register and
each output is bound to its corresponding read register.
• No memory map: This option generates a TLM component with only one
read and one write register without any address. The Simulink model
inputs are bound to the write register and the outputs are bound to the
read register.
• [Auto-generated memory map with] Single input and output address
offsets: This option generates a TLM component with only one read and
one write register with one address each. The Simulink model inputs are
bound to the write register and the outputs are bound to the read register.
When you generate the component with a memory map, you can add a
command and status register, a test and set register, and tunable parameter
registers.
For this example, select the following for the Control TLM Socket:
20-4
Getting Started with TLM Generator
Although not used in this example, a test and set register can be used as
a mutex when multiple initiators access the component during SystemC
simulation.
In the TLM Generation pane, select the TLM Processing tab. The
Algorithm Processing and the Interface processing options allow you
to define different buffering and processing behaviors for your generated
TLM component.
The step function timing is determined by the value in the Algorithm step
function timing (ns) field. The algorithm timing is counted with a wait()
in the thread or, if temporal decoupling is enabled, the algorithm timing is
counted with a quantum and time annotation in the thread or callback.
For this example, select SystemC Thread and enter 100 in the field for
Algorithm step function timing.
20-5
20 Getting Started with TLM Component Generation
• Enable payload buffering: This option adds fifo of definable size between
the input/output interface and the processing in the generated component.
When you select this option, you must also provide the Payload input
buffer depth and the Payload output buffer depth.
• Create an interrupt request port on the generated TLM component:
This option creates an interrupt port (type signal, bool>) that is triggered
every time a set of input has been processed.
Select the TLM Timing tab. The Interface Timing section allows you to
define the timing of the component input/output interface and processing
thread.
For this example, the input and output delays are counted with wait() in the
interface or, if the temporal decoupling is enabled, they are annotated to the
received transaction and sent back to the initiator. Set a time value of 5ns
for each of the transactions of Input Data Interface Timing, Output Data
Interfacing Timing, and Control Interface Timing.
Select the TLM Testbench tab. The TLM Generator target can generate a
stand-alone SystemC/TLM test bench alongside the TLM component to verify
the generated algorithm in the context of a TLM initiator/target pair. The
20-6
Getting Started with TLM Generator
TLM Testbench view provides run-time options for when the test bench code
is generated and executed.
• Choose to see verbose messages echoed to the command window during the
SystemC/TLM execution including TLM transaction and synchronization
messages.
• Indicate that the test bench should execute with or without timing
annotations.
• Indicate whether the initiator controls moving input and output datasets
between the registers and the buffers or whether the component performs
the moves automatically.
For this example, select Generate testbench, With timing for Run-time
timing mode, and Automatic for both Input buffer triggering mode and
Output buffer triggering mode.
After code generation has successfully occurred for a component and test
bench, the Verify TLM Component button becomes enabled. Verify TLM
Component performs the following:
The compilation of the generated files assumes the presence of make and a
compatible GNU-compiler, gcc, in your path on Linux®, or Visual Studio®
compiler in your path on Windows®.
20-7
20 Getting Started with TLM Component Generation
Select the TLM Compilation tab. This pane provides options to control the
generation of makefiles used to compile the generated code.
Compiler Options:
The SystemC and TLM include library path options allow you to specify
where the makefiles can find the SystemC and TLM installations. The
default values allow you to use environment variables so that updates to
your SystemC or TLM installations do not require updating your Simulink
models. You can set up the environment prior to invoking MATLAB or use
the MATLAB setenv command.
For this example, these are the environment variable values that were tested
with standard OSCI installations located in /tools:
• SYSTEMC_INC_PATH=/tools/systemc-2.3.0/include
• SYSTEMC_LIB_PATH=/tools/systemc-2.3.0/lib-linux64
• SYSTEMC_LIB_NAME=libsystemc.a (Linux) or systemc.lib (Windows)
• TLM_INC_PATH=/tools/systemc-2.3.0/include
Component Naming:
This option allows you to add your own tag to the name of the generated
component. The generated component name is built according to the following
cases:
9. Select Report
20-8
Getting Started with TLM Generator
Select Report in the left-hand pane. For this example, select Create code
generation report and Open report automatically. These options
generate a html report during component generation. The Code generation
report details the contents of each generated file.
Select Debug in the left-hand pane. The Debug pane allows you to choose
the verbose option during component generation. This option could be helpful
to track a problem when it occurs during component generation.
In the model window, right-click on the DualFilter block and select C/C++
Code > Build This Subsystem in the context menu to start TLM component
generation.
>> buildTlmgDemoModel('intro');
During execution, you will be prompted to select the tunable parameters. The
dropdown list of each coefficient allows you to select the storage class of the
variable. The Storage Class options are:
20-9
20 Getting Started with TLM Component Generation
The option Simulink Global has been selected for this example. Click Build.
The TLM generation is completed when you see the following message appear
in the MATLAB command window:
Open the generated files in the MATLAB web browser by clicking on the links
in the generated report or in the MATLAB Editor (the generated files and
report are located in your current working directory):
• DualFilter_VP/DualFilter_intro_tlm_doc/html/DualFilter_codegen_rpt.html
• DualFilter_VP/DualFilter_intro_tlm/include/DualFilter_intro_tlm_def.h
• DualFilter_VP/DualFilter_intro_tlm/include/DualFilter_intro_tlm.h
• DualFilter_VP/DualFilter_intro_tlm/src/DualFilter_intro_tlm.cpp
• DualFilter_VP/DualFilter_intro_tlm_tb/src/DualFilter_intro_tlm_tb.h
• DualFilter_VP/DualFilter_intro_tlm_tb/src/DualFilter_intro_tlm_tb.cpp
• DualFilter_VP/DualFilter_intro_tlm_tb/src/DualFilter_intro_tlm_tb_main.cpp
20-10
Getting Started with TLM Generator
c. In the TLM Testbench pane, click Verify TLM Component, to run the
generated testbench.
>> verifyTlmgDemoModel('intro')
The option to generate test bench allows you to see how the test bench initiator
threads interact and synchronize with the target. Look for the comparison
result at the end of the log and verify that there is no data miscompare.
20-11
20 Getting Started with TLM Component Generation
20-12
Getting Started with TLM Generator
20-13
20 Getting Started with TLM Component Generation
20-14
21
9 (Optional) “Run TLM Component Test Bench” on page 22-8 (verify TLM
component)
21-2
TLM Component Generation Overview
21-3
21 Generate TLM Component
5 Click OK to see the new TLM Generator option under Code Generation.
21-4
Select TLM Generator System Target
21-5
21 Generate TLM Component
2 Socket Mapping
Select either One combined TLM socket for input data, output data,
and control or Three separate TLM sockets for input data, output
data, and control. (“Single or Multiple Sockets” on page 19-5)
3 For each socket, choose the socket mapping type. For a description of the
options available under Memory Map Type, see “Memory Mapping” on
page 19-5.
• No memory map
• Auto-generated memory map
21-6
Select TLM Mapping Options
21-7
21 Generate TLM Component
a Select the Auto-generated memory map type for each TLM socket:
21-8
Select TLM Mapping Options
• Include a test and set register in the memory map (“Test and Set
Register” on page 19-19)
• Include tunable parameter registers in the memory map (“Tunable
Parameter Registers” on page 19-19).
21-9
21 Generate TLM Component
4 Interface Processing
21-10
Select TLM Timing Options
2 Combined Interface Timing (one combined TLM socket for input data,
output data, and control)
3 Input Data Interface Timing (separate TLM socket for input data)
4 Output Data Interface Timing (separate TLM socket for output data)
21-11
21 Generate TLM Component
21-12
Select TLM Testbench Options
• Whether the test bench should execute with or without timing annotations
(Run-time timing mode)
• Whether the initiator controls moving input and output datasets between
the registers and the buffers or if the component moves the datasets
automatically.
• With timing
• Without timing
• Automatic
• Manual
Note You must select Include a command and status register in the
memory map in the TLM Generation tab for this field to be enabled.
21-13
21 Generate TLM Component
• Automatic
• Manual
Note You must select Include a command and status register in the
memory map in the TLM Generation tab for this field to be enabled.
7 Component Verification
After code generation is successfully completed, you can use Verify TLM
Component to perform the following actions:
• Build the generated code using make and generated makefiles.
• Run Simulink to capture input stimulus and expected results.
• Covert the Simulink data to TLM vectors.
• Run the standalone SystemC/TLM test bench executable.
• Convert the TLM results back to Simulink data.
• Perform a data comparison.
• Generate a Figure window for any signals that had data mis-compares.
21-14
Select TLM Compilation Options
2 Compilation Options
As part of using the generated TLM component, you must compile the
generated files using a generated makefile provided by HDL Verifier
software. Use the options on the TLM Compilation tab to specify certain
makefile attributes before you generate code.
a Enter path to include SystemC
3 Component Naming
21-15
21 Generate TLM Component
Note You must generate the component and test bench on the architecture
you plan to use when running the SystemC simulation.
For more about using the generated TLM component, see “Export TLM
Component” on page 23-4.
21-16
22
You can configure the generated test bench to specify the timing mode and
the triggering modes for input and output buffering. The latter choice
allows you to indicate whether the initiator module controls moving input
and output data sets between the registers and the buffers or whether the
component performs the moves automatically. Optionally, the test bench can
also produce verbose messages at runtime to help you see the status of the
SystemC simulation.
22-2
Testing TLM Components
The information you provide is used to construct makefile. You can use
these makefiles to build the component and test bench. You can also use
this makefile to build an executable of the TLM component and test bench
outside of the MATLAB environment.
Report Generation
The tlmgenerator target supplies an HTML document containing details
about the generated component. The document contains links to the
generated source code files. Report generation can be configured via the
Simulink Coder Report pane in the configuration parameters. Report
generation is not strictly a test bench feature, but the process does include
use of test bench files.
22-3
22 Run TLM Component Test Bench
22-4
Testing TLM Components
22-5
22 Run TLM Component Test Bench
Verbose Messaging
This option generates verbose messages during test bench execution. The
default is not to generate these messages.
With timing mode not selected, the target does not annotate TLM component
transaction with any delays. The initiator module and target only perform
synchronization using zero-time wait calls.
22-6
TLM Component Test Bench Generation Options
Manual mode enables an initiator module to read only partial output data
sets, saving simulation time by avoiding TLM component transactions that
are not wanted. For example, if the target uses a full memory map and the
initiator module is only interested in the data for one of the outputs, the
initiator module can manually move the algorithm results to the register.
The initiator module can then execute TLM component transactions only for
the output of interest.
22-7
22 Run TLM Component Test Bench
Note You must generate the component and test bench before you can select
Verify TLM Component. See “Generate Component and Test Bench” on
page 21-16.
22-8
23
/systemc-2.2.0/include
/systemc-2.2.0/lib
23-2
TLM Component Compiler Options
• Windows: systemc.lib
• Linux: libsystemc.a
Alternately, you can use the default and define $SYSTEMC_LIB_NAME in your
system.
/tlm-2.0.1/include
23-3
23 Export TLM Component to SystemC Environment
23-4
Export TLM Component
include/model_name_usertag_tlm_def.h
This file contains addresses and
definitions to communicate with the
component through the TLM target
port using a TLM generic payload.
The files are sorted in subdirectories
by source and header.
HDL Verifier provides a makefile for
you to build a static library from these
source files.
These files contain the core behavior
model_name_usertag_tlm_tb include/model_name_usertag _tlm_tb.h of the test bench.
src/model_name_usertag_
tlm_tb.cpp
src/model_name_usertag_
tlm_tb_main.cpp
This file instantiates and binds the
component and the test bench together.
The files are sorted in subdirectories
by source and header.
HDL Verifier software provides
a makefile for you to build an
executable from these source file and
the component static library. This
executable requires the following:
23-5
23 Export TLM Component to SystemC Environment
Linux Users
If you want to obtain symbols for source code debugging, use the all-debug
target instead of all.
Windows Users
If you have not already, make sure that MATLAB\version\bin\win32 or
MATLAB\version\bin\win64 has been added to your user path.
You can choose one of the following ways to compile your project:
23-6
Export TLM Component
2 Load the compilation tool chain by entering the following at the system
prompt:
Win32 users:
X:\>"%VS80COMNTOOLS%\..\..\VC\vcvarsall" x86
Win64 users:
X:\>"%VS80COMNTOOLS%\..\..\VC\vcvarsall" x64
If you want to obtain symbols for source code debugging, use the
all-debug target instead of all.
5 When the system finishes compiling, locate a library
file named model_name_usertag_tlm.lib in the
model_name_VP/model_name_usertag_tlm/lib/ folder.
23-7
23 Export TLM Component to SystemC Environment
Linux Users
If you want to obtain symbols for source code debugging, use the all-debug
target instead of all.
Windows Users
If you have not already, make sure that MATLAB\version\bin\win32 or
MATLAB\version\bin\win64 has been added to your user path.
You can choose one of the following ways to compile your project:
23-8
Export TLM Component
2 Load the compilation tool chain by entering the following at the system
prompt:
Win32 users:
X:\>"%VS80COMNTOOLS%\..\..\VC\vcvarsall" x86
Win64 users:
X:\>"%VS80COMNTOOLS%\..\..\VC\vcvarsall" x64
If you want to obtain symbols for source code debugging, use the
all-debug target instead of all.
23-9
23 Export TLM Component to SystemC Environment
Where:
23-10
24
Configuration Parameters
for TLM Generator Target
24 Configuration Parameters for TLM Generator Target
TLM Mapping
• TLM Mapping: Specify options for socket and memory mapping. See
Select TLM Mapping Options.
• TLM Processing: Specify options for algorithm and interface processing.
See Select TLM Processing Options.
• TLM Timing: Specify options for combined interface timing, or for
individual timing for input data, output data, and control sockets. See.
Select TLM Timing Options.
• TLM Testbench: Specify options for the generation and runtime behavior
of a standalone SystemC/TLM component test bench. See Select TLM
Testbench Options.
• TLM Compilation: Specify generated TLM component compilation
options. See Select TLM Compilation Options.
24-2
TLM Component Generation
Socket Mapping
Choose the type of TLM socket for input data, output data, and control.
Settings. Default: One combined TLM socket for input data, output data,
and control
• One combined TLM socket for input data, output data, and control:
Create one combined TLM socket in the generated TLM component.
• Three separate TLM socket for input data, output data, and
control: Create three separate TLM sockets. Generate each data socket
with the following options:
- Auto-generated memory map (or without memory map)
- Command and status registers
- Test and set registers
- Tunable parameter registers
Setting this parameter to One combined TLM socket for input data,
output data, and control opens the Combined TLM Socket options
selection.
Setting this parameter to Three separate TLM socket for input data,
output data, and control opens the TLM Socket for Input Data, TLM
Socket for Output Data, and TLM Socket for Control with Memory
Map options selection.
Command-Line Information.
Parameter: tlmgComponentSocketMapping
Type: string
Value: |
Default:
24-3
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
24-4
TLM Component Generation
• Single input and output address offsets: Create a single address offset
for the inputs and a single address offset for the outputs
• Individual input and output address offsets: Generate an address for
each input and each output
Command-Line Information.
24-5
24 Configuration Parameters for TLM Generator Target
Settings. Default: On
On
Include a command and status register in the memory map
Off
Do not include a command and status register in the memory map
Command-Line Information.
Parameter:tlmgCommandStatusRegOnOff
Type: string
Value: 'on' | 'off'
Default: 'on'
24-6
TLM Component Generation
On
Include a test and set register in the memory map. Any read of this
register will return the current value and set the register to a new,
asserted value in an atomic operation.
Off
Do not include a test and set register in the memory map
Command-Line Information.
Parameter: tlmgTestAndSetRegOnOff
Type: string
Value: 'on' | 'off'
Default: 'off'
24-7
24 Configuration Parameters for TLM Generator Target
Settings. Default: On
On
Include tunable parameter registers in the memory map
Off
Do not include tunable parameter registers in the memory map
Command-Line Information.
Parameter: tlmgTunableParamRegOnOff
Type: string
Value: 'on' | 'off'
Default: 'on'
24-8
TLM Component Generation
TLM Processing
Command-Line Information.
Parameter: tlmgAlgorithmProcessingType
Type: string
Value: 'SystemC Thread' | 'Callback'
Default: 'SystemC Thread'
24-9
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
Parameter: tlmgAlgorithmProcessingTime
Type: int
Value:
Default: 100
24-10
TLM Component Generation
On
Enable quantum for loosely-timed simulation. Allows you to specify
the duration of the time quantum allocated to the generated TLM
component in your system simulation.
Off
Do not enable quantum
Command-Line Information.
Parameter: tlmgTempDecouplOnOff
Type: string
Value: 'on' | 'off'
Default: 'off'
24-11
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
Parameter: tlmgQuantumTime
Type: int
Value:
Default: 1000
24-12
TLM Component Generation
On
Enable payload buffering. Enabling payload buffering allows for a
different sample rate than was used in the original Simulink model.
Off
Do not enable payload buffering
Command-Line Information.
Parameter: tlmgPayloadBufferingOnOff
Type: string
Value: 'on' | 'off'
Default: 'off'
24-13
24 Configuration Parameters for TLM Generator Target
Settings. Default: 1
Command-Line Information.
Parameter: tlmgPayloadInBufferDepth
Type: int
Value:
Default: 1
24-14
TLM Component Generation
Settings. Default: 1
Command-Line Information.
Parameter: tlmgPayloadOutBufferDepth
Type: int
Value:
Default: 1
24-15
24 Configuration Parameters for TLM Generator Target
On
Create an interrupt request port on the generated TLM component.
This signal will be asserted whenever new outputs are available in the
output register(s) and will be automatically cleared whenever any value
is read from the output register(s).
Off
Do not create an interrupt request port on the generated TLM
component
Command-Line Information.
Parameter: tlmgIrqPortOnOff
Type: string
Value: 'on' | 'off'
Default: 'on'
24-16
TLM Component Generation
TLM Timing
Settings. Default: 10
Command-Line Information.
24-17
24 Configuration Parameters for TLM Generator Target
Settings. Default: 10
Command-Line Information.
24-18
TLM Component Generation
Settings. Default: 10
Command-Line Information.
24-19
24 Configuration Parameters for TLM Generator Target
Settings. Default: 10
Command-Line Information.
24-20
TLM Component Generation
TLM Testbench
Generate testbench
Generate a standalone SystemC test bench in order to verify the generated
TLM component using the same input stimulus as used in Simulink.
Settings. Default: On
On
Generate test bench for TLM component
Off
Do not generate test bench
Command-Line Information.
Parameter: tlmgGenerateTestbench
Type: string
Value: 'on' | 'off'
Default: 'on'
24-21
24 Configuration Parameters for TLM Generator Target
On
Test bench generates verbose runtime messages
Off
Test bench does not generate verbose messages
Command-Line Information.
Parameter: tlmgVerboseTbMessagesOnOff
Type: string
Value: 'on' | 'off'
Default: 'off'
24-22
TLM Component Generation
Command-Line Information.
Parameter: tlmgRuntimeTimingMode
Type: string
Value: 'With timing' | 'Without timing'
Default: 'With timing'
24-23
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
Parameter: tlmgInputBufferTriggerMode
Type: string
Value: 'Automatic' | 'Manual'
Default: 'Automatic'
24-24
TLM Component Generation
Command-Line Information.
Parameter: tlmgOutputBufferTriggerMode
Type: string
Value: 'Automatic' | 'Manual'
Default: 'Automatic'
24-25
24 Configuration Parameters for TLM Generator Target
TLM Compilation
24-26
TLM Component Generation
Command-Line Information.
Parameter: tlmgSystemCIncludePath
Type: string
Value:
Default: '$(SYSTEMC_INC_PATH)'
24-27
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
Parameter: tlmgSystemCLibPath
Type: string
Value:
Default: '$(SYSTEMC_LIB_PATH)'
24-28
TLM Component Generation
Command-Line Information.
Parameter: tlmgSystemCLibName
Type: string
Value:
Default: '$(SYSTEMC_LIB_NAME)'
24-29
24 Configuration Parameters for TLM Generator Target
Command-Line Information.
Parameter: tlmgTLMIncludePath
Type: string
Value:
Default: '$(TLM_INC_PATH)'
24-30
TLM Component Generation
Settings. No Default
Command-Line Information.
Parameter: tlmgUserTagForNaming
Type: string
Value:
Default:
24-31
24 Configuration Parameters for TLM Generator Target
24-32
SystemVerilog DPI Component
Generation
SystemVerilog DPI
Component Generation
Overview
You can export a Simulink subsystem with DPI interface for Verilog® or
SystemVerilog Simulation. To do so, you must wrap generated C code with a
DPI wrapper that communicates with a SystemVerilog thin interface function
in a SystemVerilog simulation.
If you have a license for the Embedded Coder, you can access this feature
through the Model Configuration Parameters dialog box.
The topics in this introductory section contain information you need to know
before you begin:
25-2
SystemVerilog DPI Component Generation
Data Types
Supported Simulink data types are converted to SystemVerilog data types, as
shown in the following table.
Simulink SystemVerilog
uint8 byte unsigned
uint16 shortint unsigned
uint32 int unsigned
uint64 longint unsigned
int8 byte
int16 shortint
int32 int
int64 longint
single shortreal
double real
boolean bit
vectors, matrices arrays
For example, a 4 by 2 matrix in
Simulink will be converted to a
one-dimensional array of 8 elements
in SystemVerilog.
Embedded Coder converts fixed data types to one of the supported Simulink
data types.
25-3
25 SystemVerilog DPI Component Generation
Note HDL Verifier does not support test bench generation for custom
generated SystemVerilog code. See “Customization” on page 25-7.
Generated Functions
All SystemVerilog code generated by the SystemVerilog DPI generator
contains these functions:
• Initialize function
The Initialize function is called at the beginning of the simulation. If
the asynchronous reset signal is high (goes from 0 to 1), Initialize is
called again.
25-4
SystemVerilog DPI Component Generation
For example:
• Output function
At the positive edge of clock, if clk_enable is high, the output function is
called first, and then the update function is called.
For example:
• Update function
At the positive edge of clock, if clk_enable is high, the update function
is called after the output function.
For example:
• Setparam function
If your system has tunable parameters, the generated SystemVerilog code
also contains a setparam function.
The generated SystemVerilog code does not call this function. Instead,
the default parameters are used. To change those parameters during
simulation, you must explicitly call this function.
The function details in the SystemVerilog code generated from your system
vary. You can examine the generated code for specifics. For an example of
the generated functions in context, see the example "Getting Started with
Customizing Generated SystemVerilog Code".
25-5
25 SystemVerilog DPI Component Generation
Parameter Tuning
You may want to run various simulations with various values for the
parameters in your Simulink model. If your system has tunable parameters,
the generated SystemVerilog code also contains a setparam function. The
generated SystemVerilog code does not call this function. Instead, the default
parameters are used. To change those parameters during simulation, you
must explicitly call this function.
To create a tunable parameter, you create a data object from your subsystem
before generating the SystemVerilog code using the DPI component generator.
For a full examples, see “Tune Gain Parameter During Simulation” on page
25-21.
The generated C code preserves this behavior, and the output comprises one
sampled delayed version of the input signal. However, in the SystemVerilog
wrapper file, the clock signal is used to synchronize the input and output
signals:
The output of the SystemVerilog module can only be updated on the rising
edge of the clock. This requirement introduces an extra sample delay, as
the next figure shows.
25-6
SystemVerilog DPI Component Generation
Customization
You can customize the generated SystemVerilog wrapper by modifying
the template shipped with HDL Verifier (svdpi_ert_template.vgt).
Alternatively, you can create your own custom template. You must provide
anchors for the generated code in your template and to verify that the
template generates valid SystemVerilog code.
You can also specify your own template file with the following conditions:
You can use these optional tokens to customize the generated code by
inserting them inside comment statements throughout the template:
• %<FileName>
• %<PortList>
• %<ImportInitFunction>
• %<ImportOutputFunction>
• %<ImportUpdateFunction>
• %<ImportSetParamFunction>
25-7
25 SystemVerilog DPI Component Generation
• %<CallInitFunction>
• %<CallUpdateFunction>
• %<CallOutputFunction>
Note The SystemVerilog DPI component generator does not generate a test
bench for a component that has been customized.
Limitations
• There is no support for complex data types.
• If you have matrices or vectors, HDL Verifier limits them to
one–dimensional array in SystemVerilog. For example, a 4-by-2 matrix
in Simulink is converted to a one-dimensional array of 8 elements in
SystemVerilog.
• SystemVerilog DPI Component Generation supports the following
subsystems for code generation only:
- Multirate
- Triggered subsystem
- Enabled subsystem
- Subsystem with action port
25-8
Generate SystemVerilog DPI Component and Test Bench
25-9
25 SystemVerilog DPI Component Generation
25-10
Generate SystemVerilog DPI Component and Test Bench
2 Click Build.
25-11
25 SystemVerilog DPI Component Generation
Note When you build the shared libraries, make sure that you use the correct
bit version of the tools. For example, if you are using 64-bit ModelSim on
Windows, use the 64-bit version of Visual Studio to build the shared libraries.
On Windows
1 Start Visual Studio x64 Win64 Command Prompt if you are using
64-bit ModelSim, or Visual Studio Command Prompt if you are using
32-bit ModelSim. You can find them under your Visual Studio installation
menu.
nmake -f makefile_dpi_vc.mk
When it is completed, you will see the libsubsystem_dpi.dll file that the
command generated, where subsystem is the name of the subsystem from
which you generated the DPI component. Next, go to “Run Generated Test
Bench” on page 25-13.
On Linux
25-12
Generate SystemVerilog DPI Component and Test Bench
make -f makefile_dpi_gcc.mk
When it is completed, you will see the libsubsystem_dpi.so file that the
command generated, where subsystem is the name of the subsystem from
which you generated the DPI component. Next, go to “Run Generated Test
Bench” on page 25-13.
2 Change your current directory to the dpi_tb folder under the code
generation directory in your HDL simulator installation.
do run_tb_mq.do
4 When the simulation finishes, you should see the following text printed
in your console:
sh run_tb_ncsim.sh
4 When the simulation finishes, you should see the following text printed
in your console:
25-13
25 SystemVerilog DPI Component Generation
25-14
Customize Generated SystemVerilog Code
25-15
25 SystemVerilog DPI Component Generation
You can select Edit to see the contents of the template. The following
example shows the content of the template file svdpi_ert_template.vgt:
25-16
Customize Generated SystemVerilog Code
For more about the customized template, see “Customization” on page 25-7.
25-17
25 SystemVerilog DPI Component Generation
You can generate C code from the command-line by using the MATLAB
command rtwbuild.
Note When you build the shared libraries, make sure that you use the correct
bit version of the tools. For example, if you are using 64-bit ModelSim on
Windows, use the 64-bit version of Visual Studio to build the shared libraries.
On Windows
1 Start Visual Studio x64 Win64 Command Prompt if you are using
64-bit ModelSim, or Visual Studio Command Prompt if you are using
32-bit ModelSim. You can find them under your Visual Studio installation
menu.
nmake -f makefile_dpi_vc.mk
After the shared library build completes, you see the libsubsystem_dpi.dll
file that the command generated, where subsystem is the name of the
subsystem from which you generated the DPI component.
On Linux
25-18
Customize Generated SystemVerilog Code
make -f makefile_dpi_gcc.mk
After the shared library build completes, you see the libsubsystem_dpi.so
file that the command generated, where subsystem is the name of the
subsystem from which you generated the DPI component.
25-19
25 SystemVerilog DPI Component Generation
'include "blk1_inc.sv"
DPI_blk1_initialize();
DPI_blk1_output( blk1_Y_Out1);
DPI_blk1_update( blk1_U_In1);
Example
'include "blk1_inc.sv"
module test_twoblock_tb;
initial begin
DPI_blk1_initialization();
end
always@(posedge clk)
begin
blk1_U_In1 = blk1_U_In1 + 1.0;
end
25-20
Tune Gain Parameter During Simulation
Example Setup
This example walks you through an example of how you can generate a
tunable parameter from a Simulink model and tune that parameter when you
run the generated SystemVerilog code.
The example model has a single gain block with a gain parameter that will
be tuned during simulation.
25-21
25 SystemVerilog DPI Component Generation
1 Open the Simulink Block Library and click Commonly Used Blocks.
3 Add a Delay. Double-click top open the block mask and set the Delay
length parameter to 2
4 Add a Gain block. Double-click to open the block mask and change the
value in the Gain parameter to gain.
gain = Simulink.Parameter
2 Next, type:
open('gain')
• Value: 2
• Data type: double
25-22
Tune Gain Parameter During Simulation
4 Click OK.
25-23
25 SystemVerilog DPI Component Generation
5 In the text box under Include directories, enter the folder that contains
svdpi.h; for example, c:\questa_sim_10.2a\include.
9 In the example model, right click the gain and delay blocks and select
Create Subsystem from Selection. For this example, rename the
subsystem GainSS.
10 Right click GainSS and select C/C++ Code > Build this subsystem.
25-24
Tune Gain Parameter During Simulation
// File: GainSS_dpi.sv
// Created: 2013-07-09 14:31:34
// Generated by MATLAB 8.2 and HDL Verifier 4.3
25-25
25 SystemVerilog DPI Component Generation
module GainSS_dpi(
input clk,
input clk_enable,
input reset,
input real GainSS_U_In1,
output real GainSS_Y_Out1
);
P_GainSS_T param;
initial begin
DPI_GainSS_initialize();
#100 param.gain = 6;
DPI_GainSS_setparam(param);
end
25-26
Tune Gain Parameter During Simulation
25-27
25 SystemVerilog DPI Component Generation
25-28
26
In this section...
“SystemVerilog DPI Overview” on page 26-3
“Customize SystemVerilog generated code” on page 26-4
“Source file template:” on page 26-5
“Generate test bench” on page 26-6
26-2
SystemVerilog DPI Pane
26-3
26 Context-Sensitive Help for Generated SystemVerilog DPI Component
Settings
Default: Off
On
Customize generated SystemVerilog code
Off
Do not customize generated SystemVerilog code
Dependencies
You must enter a template file in Source file template: if you want the
generator to include customized code.
26-4
SystemVerilog DPI Pane
26-5
26 Context-Sensitive Help for Generated SystemVerilog DPI Component
Settings
Default: Off
On
Create a test bench for the generated DPI component
Off
Do not create a test bench for the generated DPI component
26-6