Lab 7: Introduction to Verilog

Updated 2023 Robucci

Table of Contents


Lab 7: Introduction to Verilog

Discussion: Introduction to Verilog

Prelab Work


Discussion: Introduction to Verilog

What is Verilog

Verilog (IEEE 1364) and its decendent SystemVerilog is a hardware description language (HDL) that can be used to model electric systems for simulation and hardware synthesis and verification. In this course students will be primarily interested in learning the structural (i.e. netlist) capability of Verilog as well as a minimal code for a testbench.

Brief Overview of Verilog

🥅 Goal: Structural Syle
Verilog provides many features for describing and testing hardware including many coding/modeling styles. For this course, you should learn structural models and use of gate-level primitives. These terms are defined and differentiated from other options below. There will be minimal additional syntax used for testbenches, but you would only be modifying provided template code in this course.

🌪️ Avoid other features You may easily find descriptions of other features of Verilog that will not be used in this course, but what is not provided in this course should be avoided in this course.

Verilog coding styles

Types of primitives

Built-in primitives provide a starting set of building blocks for describing digital logic.

Introduction to design with Verilog

Consider the following circuit requirements

Design Requirements

These requirements can be expressesed as a truth table.

Desired Truth Table
Inputs a b Outputs x y
0 0 0 0
0 1 0 1
1 0 1 0
1 1 0 0

A visual a depiction of the module as a block can be useful.

Block Diagram of module with name myABModule; inputs a,b; and outputs x,y

Partitioning effort: For the sake of discussion, the design and the effort will be partitioned into two parts. The first part will target a design for output x, then another part will generate output y. Hierarchy will be employed for the overall design — meaning that rather than directly designing and constructing the entire circuit, submodules (also just called modules) will be designed that encapsulate a smaller digital logic design and then one more instances these modules will be used. A module is identified by its module name and may be used one or multiple times in a design, each time with a unique instance name .

Design of module using a netlist

The first module will be called myAModule, which will be designed to produce the first output.

The (sub)module will have the following design goals.

Design Goals for myAModule

Truth Table for myAModule
Inputs a b Output x
0 0 0
0 1 0
1 0 1
1 1 0

The following is an example design of module myAModule composed of a an AND gate and a NOT gate, shown as a schematic.

First module to design and sample design

Schematic vs Textual Netlists: Complex schematics can become cumbersome to generate, difficult to update with changes automatically tracked, and are not as portable as textual descriptions. However, it is not uncommon to use schematic-based tools, which provide visual representation, for smaller units of complexity or simple top-level descriptions. However, complex designs and automated design tool flows usually rely on the use of netlists represented in standard textual formats.

A netlist is a network description of components connected via nets. In Verilog, named nets are used rather than numbered nets, e.g. 0 1 2 3… A netlist module will typically have inputs and outputs, which may be called terminals or ports . Each net may be connected to multiple points, and some may be connected to ports . In Verilog, for nets inside a module that connect to a the module’s ports, the net name is the same as the port name.

A connection table may be used to visualize the connections in a network.

                                              Net
Terminal/Port
a b b_n y
MODULE OUTPUT PORT y ❌ ❌ ❌ ✅
MODULE INPUT PORT a ✅ ❌ ❌ ❌
MODULE INPUT PORT b ❌ ✅ ❌ ❌
NOT GATE OUTPUT ❌ ❌ ✅ ❌
NOT GATE INPUT ❌ ✅ ❌ ❌
AND GATE OUTPUT ❌ ❌ ❌ ✅
AND GATE FIRST INPUT ✅ ❌ ❌ ❌
AND GATE SECOND INPUT ❌ ❌ ✅ ❌

Graphical Grid Netlist: Similarly, a graphical depiction of network can be constructed. To do so a connection grid can be drawn to describe the connection of each net to multiple points, both ports of the module and other components. In such a depiction, each vertical and each horizontal line spans the extent of the grid unbroken. It may be useful to think of the vertical lines being “above” the horizontal lines. A vertical and horizontal line may be connected or unconnected at any given intersection.

Connection grid for depicting connections of nets in a netlist
graphical netlist depiction of myAModule

Textual Netlist: The final alternative to discuss here is a textual description of a module may be used with named nets. The following is uses a hypothetical syntax for description with gate connections described in the highlighted lines 5 and 6.

module name and terminals: myAModule y a b
module outputs: y
module inputs: a b
internal nets: b_n
instance type name and connections: and inst0 y a b_n
instance type name and connections: not inst1 y a b_n
Textual Description of a netlist using a Hypothetical Syntax

It is important to understand netlists as textual descriptions of connectivity rather than as a standard sequntial programs with elements executing in a particular order as they are provied. It is key to realize that the order of presentation of gates and instances doesn’t matter. The order of the AND GATE and NOT GATE could be rearranged without affecting the circuit.

This becomes important when writing netlists: the order of presentation for components in a Verilog netlist does not affect the description or operation of the circuit.

                                              Net
Terminal/Port
a b b_n y
MODULE OUTPUT PORT y ❌ ❌ ❌ ✅
MODULE INPUT PORT a ✅ ❌ ❌ ❌
MODULE INPUT PORT b ❌ ✅ ❌ ❌
AND GATE OUTPUT ❌ ❌ ❌ ✅
AND GATE FIRST INPUT ✅ ❌ ❌ ❌
AND GATE SECOND INPUT ❌ ❌ ✅ ❌
INVERTER OUTPUT ❌ ❌ ✅ ❌
INVERTER INPUT ❌ ✅ ❌ ❌

Note that in the hypothetical textual description of the netlist, the order of the instance specifications doe not matter – just as it should not matter if the some of the previous table were rearranged. In the following text, lines 5 and 6 are swapped.

module name and terminals: myAModule y a b
module outputs: y
module inputs: a b
internal nets: b_n
instance type name and connections: not inst1 y a b_n
instance type name and connections: and inst0 y a b_n
Textual Netlist usigng hypothetical syntax with swapped order of presentation of gates, which does not affect the function of the circuit
Graphical depiction of netlist description with swapped presentation order of the AND gate and OR gate which does not affect the function of the circuit.

Creating a Verilog Module as a Netlist

The circuit represented by the module described using Verilog is shown here. A module is created that can be use to build other circuits. The module is constructed logically using a NOT gate (inverter) and an AND gate.

Verilog looks like C, but is not a basic seqential programming language

Verilog syntax looks like C, but don’t learn to understand it as a typical programming language. First understand Verilog for describing netlists.

Verilog identifiers, like C

Verilog Reserved Keywords

These keywords cannot be used as identifiers (e.g. net names, module names)

List of Verilog Reserved Keywords

From 1995:

  • always
  • and
  • assign
  • begin
  • buf
  • bufif0
  • bufif1
  • case
  • casex
  • casez
  • cmos
  • deassign
  • default
  • defparam
  • disable
  • edge
  • else
  • end
  • endcase
  • endfunction
  • endmodule
  • endprimitive
  • endspecify
  • endtable
  • endtask
  • event
  • for
  • force
  • forever
  • fork
  • function
  • highz0
  • highz1
  • if
  • ifnone
  • initial
  • inout
  • input
  • integer
  • join
  • large
  • macromodule
  • medium
  • module
  • nand
  • negedge
  • nmos
  • nor
  • not
  • notif0
  • notif1
  • or
  • output
  • parameter
  • pmos
  • posedge
  • primitive
  • pull0
  • pull1
  • pulldown
  • pullup
  • rcmos
  • real
  • realtime
  • reg
  • release
  • repeat
  • rnmos
  • rpmos
  • rtran
  • rtranif0
  • rtranif1
  • scalared
  • small
  • specify
  • specparam
  • strong0
  • strong1
  • supply0
  • supply1
  • table
  • task
  • time
  • tran
  • tranif0
  • tranif1
  • tri
  • tri0
  • tri1
  • triand
  • trior
  • trireg
  • vectored
  • wait
  • wand
  • weak0
  • weak1
  • while
  • wire
  • wor
  • xnor
  • xor

From 2001:

  • automatic
  • cell
  • config
  • endconfig
  • endgenerate
  • generate
  • genvar
  • incdir
  • include
  • instance
  • liblist
  • library
  • localparam
  • noshowcancelled
  • pulsestyle_ondetect
  • pulsestyle_onevent
  • showcancelled
  • signed
  • unsigned
  • use

From System Verilog:

  • accept_on
  • alias
  • always_comb
  • always_ff
  • always_latch
  • assert
  • assume
  • before
  • bind
  • bins
  • binsof
  • bit
  • break
  • byte
  • chandle
  • checker
  • class
  • clocking
  • const
  • constraint
  • context
  • continue
  • cover
  • covergroup
  • coverpoint
  • cross
  • dist
  • do
  • endchecker
  • endclass
  • endclocking
  • endgroup
  • endinterface
  • endpackage
  • endprogram
  • endproperty
  • endsequence
  • enum
  • eventually
  • expect
  • export
  • extends
  • extern
  • final
  • first_match
  • foreach
  • forkjoin
  • global
  • iff
  • ignore_bins
  • illegal_bins
  • implies
  • import
  • inside
  • int
  • interface
  • intersect
  • join_any
  • join_none
  • let
  • local
  • logic
  • longint
  • matches
  • modport
  • new
  • nexttime
  • null
  • package
  • packed
  • priority
  • program
  • property
  • protected
  • pure
  • rand
  • randc
  • randcase
  • randsequence
  • ref
  • reject_on
  • restrict
  • return
  • s_always
  • s_eventually
  • s_nexttime
  • s_until
  • s_until_with
  • sequence
  • shortint
  • shortreal
  • solve
  • static
  • string
  • strong
  • struct
  • super
  • sync_accept_on
  • sync_reject_on
  • tagged
  • this
  • throughout
  • timeprecision
  • timeunit
  • type
  • typedef
  • union
  • unique
  • unique0
  • until
  • until_with
  • untypted
  • var
  • virtual
  • void
  • wait_order
  • weak
  • wildcard
  • with
  • within

C-Style Comments

Verilog supports C/C++ -style comments

//comment

/*comment*/

/* block
   comment */

Verilog Module Syntax

module myAModule( y, a, b );
  
  
  /*declare output(s)*/
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
  
  /*declare internal net(s)*/
  logic b_n;
  
  
  
  /*Instatiate Primitives/Gates*/
  
  //instatiate NOT
  not inst0 (b_n,b);
  
  
  
  //instatiate AND
  and inst1 (y,a,b_n);
  
  
  
endmodule


























In Verilog netlists, the order of instantiations does not matter.
In the following, the order of the NOT gate and AND gate are reversed, but it does not affect the circuit described.

module myAModule( y, a, b );
  
  /*declare output(s)*/
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
  
  /*declare internal net(s)*/
  logic b_n;
  
  /*Instatiate Primitives/Gates*/
  not inst0 (b_n,b);
  and inst1 (y,a,b_n);
  
endmodule

module myAModule( y, a, b );
  
  /*declare output(s)*/
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
  
  /*declare internal net(s)*/
  logic b_n;
  
  /*Instatiate Primitives/Gates*/
  and inst1 (y,a,b_n);
  not inst0 (b_n,b);
  
endmodule

Design for output y (Design Reuse)

The requirement for ouput y is as follows.

Truth Table for Logic for Output Y
Inputs a b Output y
0 0 0
0 1 1
1 0 0
1 1 0

It may be noticed that the previous module, myAModule can be creatively reused to produce the final output b, by swapping the input connections. The design job here is done, and the top-level design module can be completed next. Creative identification of opportunities for reuse is treasured in the practice of engineering.

One might define a new module called myBModule to wrap an underlying instance of myAModule within it, but for simplicity of discussion we’ll limit the overall design to only TWO levels of hierarchy by directly using a second instance of the module myAModule in the module myAModule.

Top Level Design and use of Module Instatiation

Common Hierarchical Schematic
Graphical Connection Grid Depiction of Heirarchical Netlist
Verilog Module for Design Top Called myABModule
module myABModule( x, y, a, b );
  
  /*declare output(s)*/
  output logic x;
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
 
  /*Instatiate Primitives/Gates*/
  myAModule instA (.y(x),.a(a),.b(b));
  myAModule instB (.y(y),.a(b),.b(a));
  
endmodule

Syntax for module instatiation

exapanding myAModule instB (.y(y),.a(b),.b(a)); for explanation:

myAModule 
          instB 
                (

                 .y(x),
                 .a(b),
                 .b(a)
                )
                 ;
←module name (what to instatiate)
←instance name: a locally unique identifier
←opening parenthesis to start port mapping (port connections)
• connections of ports to local nets:
  ←. followed by port name followed by  parenthesized local net name
  ←. followed by port name followed by  parenthesized local net name
  ←. followed by port name followed by  parenthesized local net name
←right parenthesis to end port mapping
←semicolon to complete module instantiation

Therefore, the following connections are specified for instB, an instance of module myAModule

Unused Ports

If any ports are skipped then they are left unconnected. For a novice, it is better to explicity provide the port and leave it empty and provide a comment to express designer’s intent rather than only skip it.

FullAdder myAdder (.sum(s),.carry_out(),.a(a),.b(b),.carry_in(c_in)); // port carry_out unused

or

FullAdder myAdder (.sum(s),.carry_out(/*unused*/),.a(a),.b(b),.carry_in(c_in));

rather than a missing port:

FullAdder myAdder (.sum(s),.a(a),.b(b),.carry_in(c_in));

Unconnected ouputs are not uncommon.

Unused Inputs, e.g. Unconnected Inputs

Unconnected inputs should be avoided in this course since they will usually cause a problem.

FullAdder myAdder (.sum(s),.a(a),.b(b)); //missing carry in
FullAdder myAdder (.sum(s),.a(a),.b(b),.carry_in() ); //unconnected input

Implicit vs Explicit Port Map

The previous explanation of instantiation syntax used the name of each port following a period. This is called an explicit port map since the name of each port is explicitly provided with each connection to a net. An alternate syntax is implicit port map, which relies on the port order provided in the module. DO NOT USE IMPLICIT PORT MAPPING SYNTAX FOR MODULES SUCH AS THIS: myAModule inst1 (y,b,a); Instating primitives however relies in implicit mapping, e.g. and inst5 (y,u,v);. Explicit port mapping allows you to skip or specify connections in any order, though this is not encouraged.

Flat Netlist (for comparison)

A flat design can be considered for comparison to the heirachical design.
Note that it has more internal nets exposed.

Flat Design (non-heirarchical design)
Flat Netlist for myABModule
module myABModule( x, y, a, b );
  
  /*declare output(s)*/
  output logic x;
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
  
  /*declare internal net(s)*/
  logic a_n;
  logic b_n;
  
  /*Instatiate Primitives/Gates/Modules*/
  not inst0 (b_n,b);
  and inst1 (x,a,b_n);
  not inst2 (a_n,a);
  and inst3 (y,a,b_n);
  
endmodule

A good practice for complex designs is to construct the top module using only instantiations of other modules, with all primitives encapsulated in those sub-modules. All sub-modules should typically be tested independently before testing the entire system. This is also good for maintenance (updates). If changes are made to sub-modules then the module can be tested separately from the rest of the system. It is also easier to document changes and identify likely sources of system bugs when a design is broken into well-maintained parts. In other words, a complex design description should not be flattened. Heirarchy is good for organization of design, documenation, testing, and maintanance. However, netlist flattening is performed in automated flows and flattened netlists are sometimes used in automated flows especially if the hierarchy cannot be preserved or is not useful.

Review/Thought 💭

What is a flat netlist vs a heirarchical netlist?
What does it mean to flatten a netlist?

Levels of abstraction and hierarchy

Abstraction is an essential concept in digital design. It can refer to using a simplified model of a complex entity, or hiding implementation. Abstraction can refer to functional abstraction, whereby implementation is hidden and only the interface is exposed. In this case if the implementation changes and the interface and functional abstract model stays the same, the entire system need not be updated. Abstraction can also refer to physical abstraction, which involves simplifying models for use in other domains. This frees the users of the model from concern with low level details so that they can concentrate on optimizing efforts at their level of expertise. Unfortunately details ignored through the processes of abtraction and presentatoin of simplified use-models can lead to security volunerabilities, but that is a conversation for another day.

Note that the module myAModule could have been implemented using a NOT gate and a NOR gate. The user of the module would see no functional difference in terms of the Boolean functional description. Both implementations satisfy the requirements provided by the Truth Table. This would be an example exercise of abstraction, by which an underlying implementation can be changed while maintaining functionality. Abstraction allows designers to work at different levels, either to break a large problem into manageable design tasks for the engineer, or to allow multiple engineers to work at different levels in parallel efforts.

In this course the lowest level of abstraction for digital logic design will be at the gate level, which is also the lowest level of concern for Verilog netlists in this course. In a physical implementation, the gates or effective combinations of gates are implemented with some physical devices like transistors which are implemented by some technology for physically producing the devices by a manufacturing process. Verilog has some ability to model circuits at lower levels, such as at switch-/transistor-level, but exploration there will not be in this course.

Verilog Primitives: the leaf cells of the hierarchy

The Verilog primitives to be concerned with in this course are as follows.
The first connection is the output. A variable number of inputs follows.
The not primitive has one input, but the others used in this course will have at least two and may have more inputs. The number of inputs is variable.

Primitive (Gate) Example Verilog Instantiation
not not inst0(a,b);
not inst1(y,x);
and and inst0(y,a,b);
and inst0(y,a,b,c);
nand nand inst0(y,a,b);
nand inst0(y,a,b,c);
or or inst0(a,r,t);
or inst0(y,m,n,o,p);
nor nor inst0(a,r,t);
nor inst0(y,m,n,o,p);
xor xor inst0(a,r,t);
xor inst0(y,m,n,o,p);
xnor xnor inst0(a,r,t);
xnor inst0(y,m,n,o);

Avoid other primitives

There are other primitives that can be found for Verilog, but those shall not be used in this course.

Dataflow Expressions (optional read)

Dataflow Expressions

In this course, only use dataflow expressions if expicitly allowed. Otherwise, use instatiation of primitives rather than dataflow expressions. This section is only provided for awareness and completeness.


Primitive (Gate)
Example Verilog Instantiation Closely Related Verilog Dataflow Expression Use
not not inst0(a,b); assign a=~b;
not inst1(y,x); assign y=~x;
and and inst0(y,a,b); assign y=a&b;
and inst0(y,a,b,c); assign y=a&b&c;
nand nand inst0(y,a,b); assign y=~(a&b);
nand inst0(y,a,b,c); assign y=~(a&b&c);
or or inst0(a,r,t); assign a=r|t;
or inst0(y,m,n,o,p); assign y=m|n|o|p;
nor nor inst0(a,r,t); assign a=~(r|t);
nor inst0(y,m,n,o,p); assign y=~(m|n|o|p);
xor xor inst0(a,r,t); assign a=r^t;
xor inst0(y,m,n,o,p); assign y=m^n^o^p;
xnor xnor inst0(a,r,t); assign a=r~^t; or
assign a=r^~t; or
assign a=~(r^t);
xnor inst0(y,m,n,o); assign y=~(m^n^o);
dont use the following: y=(m~^n~^o);

Dataflow Expressions are particularly useful for more compact descriptions of cascading logic.

  //instatiate NOT
  not inst0 (a_n,a);
  
  //instatiate AND
  and inst1 (y,a_n,b);
  a_n=a;
  y=a_n & b;
  y=(~a)&b;

Verilog is not a sequntial programming language — at the base level the statements are concurrent and represent parallel harware. Each statement or instantiation describes a distinct portion of the hardware design. Thinking of Verilog as a Hardware Description Language, the order of the descriptions does not matter.

  //instatiate NOT
  not myNot (a_n,a);
  
  //instatiate AND
  and myAnd (y,a_n,b);
  //instatiate AND
  and myAnd (y,a_n,b);

  //instatiate NOT
  not myNot (a_n,a);

Similarly, the order of presentation of the dataflow assignments does not matter.

  assign a_n=a;
  assign  y=a_n & b;
  assign  y=a_n & b;
  assign  a_n=a;

Discussion for Testbench

Once could say that Verilog appears to be a languge with many faces — another face will be seen when writing a Verilog testbench. Although students are not expected to learn all the styles and features of Verilog, a minmal preficiency in editing a template of a testbench for simulating Verilog modules. Students are not encouraged to develop a level of mastery of all styles of Verilog or of the minimal subset used in testbenches. The style of code used in testbenches is special and should not be applied when writing circuit descriptions / netlists. A testbench is not inteded to represent hardware. A testbench is used simply to support simulation of another module.

Level of Mastery of Testbench Code for this Course: Modifying Template Code

For the purpose of this course, it is fine to approach the writing of testbenches as an excercise in modifiying template code. Later courses are available for mastering design and writing testbenches.

Three commented file listings are provided below. Create three files and run the simulation.

// Filename: myABModule.sv
module myABModule( x, y, a, b );
  
  /*declare output(s)*/
  output logic x;
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
 
  /*Instatiate Primitives/Gates*/
  myAModule instA (.y(x),.a(a),.b(b));
  myAModule instB (.y(y),.a(b),.b(a));
  
endmodule
// Filename: myAModule.sv
module myAModule( y, a, b );
  
  /*declare output(s)*/
  output logic y;
  
  /*declare input(s)*/
  input  logic a;
  input  logic b;
  
  /*declare internal net(s)*/
  logic b_n;
  
  /*Instatiate Primitives/Gates*/
  and inst1 (y,a,b_n);
  not inst0 (b_n,b);
  
endmodule
// Filename: myABModule_tb.sv
//the next line assigns a physical unit and precision to the simulation time unit
`timescale 1ns/1ns

//Using the postfix _tb following the name of the module being tested is a common convention
module myABModule_tb; //testbench module has no ports.

  // define nets to connect to the module to be tested 
  logic       x, y, a, b;

  //instatiate design under test
  //it is not required, but a common convention is to name the
  //instance DUT with connections to testbench-local 
  myABModule DUT( .x(x),.y(y), .a(a),.b(b) ); 

  initial begin // initial keyword preceeds code to be run at the start of the simulation
                // keyword begin is like opening brace in C {
    //register a monitor: will automatically reprint any time one of the arguments are udpated
    //any string literial containing or more %b should be followed by the same number of many logic variables 
    //a string literial containing %t should be followed by $time instead of a net, 
    //  prints the virtual time in the simulation 
    // %10t means print time with 10 space for digits
    $monitor("%10t ", $time,"a=%b b=%b x=%b y=%b",a,b,x,y);

    //set initial values for inputs
    a=0; b=0;
    //any one-time immediate print are performed using a $display task  
    $display("initial values are set");
    #100; //advance one-hundred time units
    a=0; b=1; //set inputs to another state
    #100;
    a=1; b=0;
    #100;
    $display("last input comming now....");
    a=1; b=1;
    #100;

    $finish; // finish simulation 
  end //keyword end is like closing brace in C }

endmodule

To compile the simualtion, provide all of the module names and an appropriate output name using -o
the option -g2012 ensures that SystemVerilog, a modern Verilog standard, syntax is accepted

iverilog -g2012 myABModule_tb.sv myAModule.sv myABModule.sv -o myABModule_tb
./myABModule_tb

Here is the result

initial values are set
         0 a=0 b=0 x=0 y=0
       100 a=0 b=1 x=0 y=1
       200 a=1 b=0 x=1 y=0
last input comming now....
       300 a=1 b=1 x=0 y=0

Testbench Variant 1 (print annotated table):

This next variant uses $write, which is like $display but does not append a newline.

// Filename: myABModule_tb_test1.sv
//the next line assigns a physical unit to the simulation time unit
`timescale 1ns/1ns
module myABModule_tb_test1;

  logic       x, y, a, b;

  myABModule DUT( .x(x),.y(y), .a(a),.b(b) ); 

  
  initial
  begin
    $write("myABModule_tb_test1\n\n");
    
    $write("   Time    | Input | Output\n");
    $write("           |   a b |    x y\n");
    $write("-----------|-------|-------\n");
    a=0; b=0;
    #100;
    $write("%10t |   %b %b |    %b %b\n",$time,a,b,x,y);
    a=0; b=1;
    #100;
    $write("%10t |   %b %b |    %b %b\n",$time,a,b,x,y);
    $write("------------------------------- second half of test...\n");
    a=1; b=0;
    #100;
    $write("%10t |   %b %b |    %b %b",$time,a,b,x,y);
    $write("      <--- this result is interesting\n");
    a=1; b=1;
    #100;
    $write("%10t |   %b %b |    %b %b\n",$time,a,b,x,y);
    $finish; // finish simulation 
  end

endmodule

Run

iverilog -g2012 myABModule_tb_test1.sv myAModule.sv myABModule.sv  -o myABModule_tb_test1
./myABModule_tb_test1 

Result

myABModule_tb_test1

   Time    | Input | Output
           |   a b |    x y
-----------|-------|-------
       100 |   0 0 |    0 0
       200 |   0 1 |    0 1
------------------------------- second half of test...
       300 |   1 0 |    1 0      <--- this result is interesting
       400 |   1 1 |    0 0
       

Testbench Peering Down into the Heirarchy

Normally a Verilog module will be written with respect to the abstraction and the for the levels of heirarchy by only accessing “local” signals withing the same module. However, a testbench is not inteded to represent the design and there is good reason to bend the principle of abstraction and access nets deeper in the heirarchical netlist.

Heirarchial signal access is performed using instances names for each level e.g.

Testbench Variant 2 Heirarchial Signal Access

// Filename: myABModule_tb_test2.sv
`timescale 1ns/1ns
module myABModule_tb_test2;

  logic       x, y, a, b;

  myABModule DUT( .x(x),.y(y), .a(a),.b(b) ); 

  
  initial
  begin
    $write("myABModule_tb_test2\n\n");
    
    $write("   Time    | Input | Output | Internal Signals\n");
    $write("           |   a b |    x y | DUT.instA.b_n DUT.instB.b_n \n");
    $write("-----------|-------|---------\n");
    a=0; b=0;
    #100;
    $write("%10t |   %b %b |    %b %b |             %b             %b \n",$time,a,b,x,y,DUT.instA.b_n,DUT.instB.b_n);
    a=0; b=1;
    #100;
    $write("%10t |   %b %b |    %b %b |             %b             %b \n",$time,a,b,x,y,DUT.instA.b_n,DUT.instB.b_n);
    a=1; b=0;
    #100;
    $write("%10t |   %b %b |    %b %b |             %b             %b \n",$time,a,b,x,y,DUT.instA.b_n,DUT.instB.b_n);
    a=1; b=1;
    #100;
    $write("%10t |   %b %b |    %b %b |             %b             %b \n",$time,a,b,x,y,DUT.instA.b_n,DUT.instB.b_n);
    $finish; // finish simulation 
  end

endmodule

Run

iverilog -g2012 myABModule_tb_test2.sv myAModule.sv myABModule.sv  -o myABModule_tb_test2
./myABModule_tb_test2 

Result

myABModule_tb_test2

   Time    | Input | Output | Internal Signals
           |   a b |    x y | DUT.instA.b_n DUT.instB.b_n 
-----------|-------|---------
       100 |   0 0 |    0 0 |             1             1 
       200 |   0 1 |    0 1 |             0             1 
       300 |   1 0 |    1 0 |             1             0 
       400 |   1 1 |    0 0 |             0             0 

Prelab Work

Evironment and Tool Installation

If Using Windows

If you are using Windows, you need to install and test WLS2 with GUI support. At the time of this writing in March 2023, GUI support is builtin.

Overview

https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps
Fresh install - No prior WSL installation

Existing WSL Install
You may need to explicity switch to WLS2 if you are using WSL1 https://learn.microsoft.com/en-us/windows/wsl/basic-commands#set-wsl-version-to-1-or-2 , but otherwise the following commands should work.

Install WSL From Powershell Step-by-Step
  1. Run Windows Power Shell Run As Administrator)
    so that you can run this command wsl --install

  2. After launching the shell, a prompt will appear:

       >_  Administraor: Windows PowerShell

    Windows PowerShell
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    Try the new cross-platform PowerShell https://aka.ms/pscore6
    
    PS C:\Windows\system32>▂
    
  3. Enter the command wsl --install and press Enter:

       >_  Administraor: Windows PowerShell

    Windows PowerShell
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    Try the new cross-platform PowerShell https://aka.ms/pscore6
    
    PS C:\Windows\system32> wsl --install▂
    

    What will happen:

       >_  Administraor: Windows PowerShell

    Windows PowerShell
    Copyright (C) Microsoft Corporation. All rights reserved.
    
    Try the new cross-platform PowerShell https://aka.ms/pscore6
    
    PS C:\Windows\system32> wsl --install
    Installing: Virtual Machine Platform
    Virtual Machine Platform has been installed.
    Installing: Windows Subsystem for Linux
    Windows Subsystem for Linux has been installed.
    Installing: Windows Subsystem for Linux
    Windows Subsystem for Linux has been installed.
    Installing: Ubuntu
    Ubuntu has been installed.
    The requested operation is successful. Changes will not be effective until the system is rebooted.
    PS C:\Windows\system32>▂
    
  4. ↻ 💻 Restart the Windows Computer

  5. When the computer reboots, a Ubuntu terminal window may be started automatically. Otherwise Run it using the start menu
    Ubuntu App

  6. Oberve the following and then wait.

       Ubuntu / C:\Windows\System32\wsl.exe
    Ubuntu is already installed.
    Launching Ubuntu...
    Installing, this may take a few minutes
    
  7. Await the new UNIX username prompt.

       Ubuntu / C:\Windows\System32\wsl.exe
    Ubuntu is already installed.
    Launching Ubuntu...
    Installing, this may take a few minutes
    Please create a default UNIX user account. The username does not need to match your Windows username.
    For more information visit: https://aka.ms/wslusers
    Enter new UNIX username:
    
  8. Enter a username (I used robucci), and password (twice) and then observe the following.

       robucci@DESKTOP-2JDD74K: ~
     Ubuntu is already installed.
     Launching Ubuntu...
     Installing, this may take a few minutes
     Please create a default UNIX user account. The username does not need to match your Windows username.
     For more information visit: https://aka.ms/wslusers
     Enter new UNIX username: robucci
     New password:
     Retype new password:
     passwd: password updated successfully
     Installation successful!
     To run a command as adminisitrator (user "root"), use "sudo ".
     See "man sudo_root" for deatils.
      
     Welcome to Ubuntu 22.04.1 LTS (GNU/Linux 5. 15.90.1-microsoft-standard-WSL2 x86_64)
      
      * Documentation: https://help.ubuntu.com
      * Management: https://andscape.canonical.com
      * Support: https://ubuntu.com/advantage
      
     This message is shown once a day. To disable it please create the
     /home/robucci/.hushlogin file.
     robucci@DESKTOP-2JDD74K:~$
     
Update and Install Packages Test GUI
  1. Run update so that you can install packages

    sudo apt update
    
  2. Upgrade existing packages before install new ones (optional, but saves time later)

    sudo apt upgrade
    
  3. Test GUI/Graphics

    1. Install x11-apps
      sudo apt install x11-apps
      
    2. Test xclock. This program is usful for testing and monitoring that graphics are working.
      xclock
      

      Close the program.
    3. Run xeyes
      xeyes
      
      Oberve the following window, the eyes should follow the mouse. This verifies that mouse input is seen by GUI programs. Close the window.
Install IVERILOG AND GTKWAVE Tools

Install iverilog and gtkwave

sudo apt install gtkwave
sudo apt install iverilog
Verify that you can create files from the Linux Subsystem and access them from Windows File Explorer to otherwise access, read and edit them from native Windows programs
  1. Create an empty text file from within the Linux subsystem using the command line interface:
    touch testfile.txt
    
    This creates a new file that you can find from within Window File explorer.
  2. Open the standard Windows File Explorer
  3. Using the Location bar, goto the following: \\wsl$\Ubuntu\home\robucci (replace robucci with your UNIX username)
    You may also see a Linux filesystem/mountpoint directly:
    https://www.howtogeek.com/667273/windows-10s-file-explorer-is-getting-linux-files-and-tux/
  4. Be sure to find the file testfile.txt and try to open it (it will be empty at first)

If Using Apple/Mac

I don’t have access to this, but students and TA’s say that it is easy to isntall the required programs and I have seen iverilog and gtkwork programs work on Apple/Mac.
Google: how to install gtkwave and iverilog on macos
here is the first reference that I found: https://ee.sonoma.edu/resources/computer-hardware-and-software/icarus-and-gtkwave-mac

If Using Ubuntu and Linux

Make sure your list of available packages is up to date

sudo apt update

Install both programs

sudo apt install iverilog gtkwave

Installation on other distributions should be easy. Even downloading source code (git repos) and compiling from source is reasonable if you have some previous experience.

Icarus Verilog Tool-Test (hello world)

create a file named hello_world.sv, using your favorite editor

//File: hello_world.sv
module hello_world;
initial $display("Hello World!");
endmodule

Verilog Simulations works by generating an executable Run the following command to generate the executable.

iverilog -g2012 hello_world.sv -o hello_world

That creates creates hello_world. Verify this by listing the directory contents using the ls command

ls

In correctly setup environments you can directly run ./hello_world:

./hello_world

Result:

Hello World!

If the installation is not correct, you you’ll try to find and use vvp:

somepath/vpp ./hello_world

GTKWave Tool-Test

modify hello_world.sv

module hello_world;
initial $display("hello world");

   reg clk;
   initial clk=0;
   always #5 clk=~clk;

   initial #100 $finish;

   initial begin
      $dumpfile("hello_world.vcd");      
      $dumpvars;
      
   end
  
endmodule // hello_world

rerun the simulation as before

you should get a message that a waveform file has been generated:

hello world
VCD info: dumpfile hello_world.vcd opened for output.

Run gtkwave:

gtkwave hello_world.vcd

Use of Arrow Keys to JUMP From edge to edge

At the end of the video, the right → and left ← arrow keyboard keys are used to move the time cursor to the next and previous transitions. This is extremely useful and saves time. Don’t overlook or forget this feature.

Typically, use Append rather than insert, to add signals to the existing list.

Prelab Exercise and Submission

Lab Exercise

(Provided by Professor Phatak)

In the last Lab, you simultaneously minimized the switching expressions for all 7 signals needed to drive a 7-segment display.
Implement each of those switching expressions using AND, OR and NOT gates in structural Verilog; assuming that maximum fan-in of a gate (i.e., the maximum number of inputs that a/any gate can have is limited to 4).

Then simulate your 7-segment display in Verilog and show the printouts to the TA. Do you see any difference between the version where you assumed don’t cares (for inputs corresponding to decimal numbers 10 thru 15) and the version where there are no don’t cares (because you display hex digits A thru F corresponding to the inputs 10 thru 15) ?

Grading and Submission Details

  1. Prelab 10%…other portion of grade will be assigned considering the following
  2. Submit all code for modules and testbenches
  3. Submit results printout
  4. Submit a brief statement on completeness and correctness of design as well as implementation
  5. Demonstrate code operation to TA as/if requested

Provided Demonstration Code for Printing

The first half of the code prints binary values for a,b,c,d,e,f,g in a 2-D arrangement corresponding to positions in a 7-segment display.
The second half of the code prints ASCII characters by using %c in the formatting string and using ternary operator borrowed from C/C++ to optionally print characters | and _ or a space

Verilog and C/C++ expression: (a>b)?a:b , in assignment largest=(a>b)?a:b
Python expression: a if (a > b) else b, in assignment largest=a if (a > b) else b
https://www.geeksforgeeks.org/ternary-operator-in-python/

// Filename: abcdefg.sv
module abcdefg;
logic a,b,c,d,e,f,g;

initial begin

// 0
a=1;b=1;c=1;d=1;e=1;f=1;g=0;
$write(" 0:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 1
a=0;b=1;c=1;d=0;e=0;f=0;g=0;
$write(" 1:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 2
a=1;b=1;c=0;d=1;e=1;f=0;g=1;
$write(" 2:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 3
a=1;b=1;c=1;d=1;e=0;f=0;g=1;
$write(" 3:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 4
a=0;b=1;c=1;d=0;e=0;f=1;g=1;
$write(" 4:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 5
a=1;b=0;c=1;d=1;e=0;f=1;g=1;
$write(" 5:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 6
a=1;b=0;c=1;d=1;e=1;f=1;g=1;
$write(" 6:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 7
a=1;b=1;c=1;d=0;e=0;f=0;g=0;
$write(" 7:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 8
a=1;b=1;c=1;d=1;e=1;f=1;g=1;
$write(" 8:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);
// 9
a=1;b=1;c=1;d=1;e=0;f=1;g=1;
$write(" 9:\n");
$display("     %b    ",a);
$display("    %b %b    ",f,b);
$display("     %b    ",g);
$display("    %b %b    ",e,c);
$display("     %b    ",d);



$write("\nprettier:\n\n");


// 0
a=1;b=1;c=1;d=1;e=1;f=1;g=0;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
a=0;b=1;c=1;d=0;e=0;f=0;g=0;
// 1
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 2
a=1;b=1;c=0;d=1;e=1;f=0;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 3
a=1;b=1;c=1;d=1;e=0;f=0;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 4
a=0;b=1;c=1;d=0;e=0;f=1;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 5
a=1;b=0;c=1;d=1;e=0;f=1;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 6
a=1;b=0;c=1;d=1;e=1;f=1;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 7
a=1;b=1;c=1;d=0;e=0;f=0;g=0;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 8
a=1;b=1;c=1;d=1;e=1;f=1;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");
// 9 
a=1;b=1;c=1;d=1;e=0;f=1;g=1;
$display("     %c    ",a?"_":" ");
$display("    %c%c%c    ",f?"|":" ",g?"_":" ",b?"|":" ");
$display("    %c%c%c    ",e?"|":" ",d?"_":" ",c?"|":" ");

end

endmodule

Run:

iverilog -g 2012 abcdefg.sv -o abcdefg
./abcdefg 

Result:

 0:
     1    
    1 1    
     0    
    1 1    
     1    
 1:
     0    
    0 1    
     0    
    0 1    
     0    
 2:
     1    
    0 1    
     1    
    1 0    
     1    
 3:
     1    
    0 1    
     1    
    0 1    
     1    
 4:
     0    
    1 1    
     1    
    0 1    
     0    
 5:
     1    
    1 0    
     1    
    0 1    
     1    
 6:
     1    
    1 0    
     1    
    1 1    
     1    
 7:
     1    
    0 1    
     0    
    0 1    
     0    
 8:
     1    
    1 1    
     1    
    1 1    
     1    
 9:
     1    
    1 1    
     1    
    0 1    
     1    

prettier:

     _    
    | |    
    |_|    
          
      |    
      |    
     _    
     _|    
    |_     
     _    
     _|    
     _|    
          
    |_|    
      |    
     _    
    |_     
     _|    
     _    
    |_     
    |_|    
     _    
      |    
      |    
     _    
    |_|    
    |_|    
     _    
    |_|    
     _|   

Verilog/System Verilog Standard Documents

Lab 7: Introduction to Verilog

Discussion: Introduction to Verilog

Prelab Work

≡