You are on page 1of 41

Verilog Overview - The Verilog Hardware Description Language Introduction

As we know circuits and systems we are developing today Growing in capability and complexity Yesterday a sketch on a piece of paper and a handful of parts Sufficient to try out a design idea For contemporary designs Traditional approach no longer feasible Todays approach is driven by Significantly increased complexity Physical constraints Circuit will operate differently When spread out on bench vs. reduced to IC or PLD Most contemporary designs Mix of hardware and software Dont have luxury of approaching design in serial manner First hardware then software For now well focus on hardware side Today our design is Modeled using computer based tools and languages Synthesized into the desired hardware implementation

Tested to verify the design We use two key words here model and synthesize While test is important It applies no matter what approach is used Following up on these words Today as we progress through formal design process we Model the design Transform requirements into working HDL implementation Hardware Description Language Synthesize the model Transform modeled functionality Into switch level hardware implementation

Test First coarse grained functionality High level behaviour From input to output Then fine grained details Details of actual signals Amplitude Timing Ability to drive other devices Iterate Until we are satisfied This is engineering Then transform switch level implementation into Target is programmable logic device ASIC, FPGA, CPLD, Memory Some other combination of digital hardware

Why are We Modeling?

Primarily we use models to represent a description of Real system or one that will become real When it is designed and implemented Models Give us different views of our system External, internal, abstract, behavioural, structural Give us means to describe characteristics of system to be designed Provides basis for later verification Cheaper than building complete system To test design concept Faster to build and modify than full hw / sw implementation Allow us to execute test that may be too hazardous to run During preliminary development In design process Model precedes actual physical implementation Provides opportunity to explore alternative approaches Cheaply Quickly

Hardware Design Language HDL Based Design

Contemporary design executed using HDL Must still meet many of same initial requirements as traditional approaches Whether using pencil and paper or computer based tools Must still work from sound and solid Set of requirements Specification Tasks we must Identify requirements and formulate specification Functional decomposition Formulate architecture Map modules to architecture Design comprising modules

A number of languages that support such a design approach Verilog and VHDL Two of the more common SystemC For modeling both the hardware and software components Finding its way into an increasing number of designs in the embedded world
What is Verilog?

Verilog is a hardware design language Provides a means of specifying a digital system At a wide range of levels of abstraction Language supports Early conceptual stages of design With its behavioral level of abstraction Later implementation stages With its structural level of abstraction Ultimately switch level for implementation Language provides hierarchical constructs Allows the designer manage the complexity of contemporary designs Note: this description is an excerpt from the book Verilog Hardware Description Language, by Thomas and Moorby.

We will Begin with some useful information on Several different Verilog data types Follow with an introduction to Basic components and organization of a Verilog program Then examine gate-level or structural modeling in detail Combinational logic circuits Sequential circuits Examine some important tools and capabilities of language Facilitate fine grained modeling and test of a design Emphasizing last point important to recognize Design is only one aspect of the product development Each design must also be tested Confirm that it meets specified requirements and the objectives Of the modeling process To do so must have a specification Level of formality varies To that end will also discuss how one can formulate test suites To verify the intended operation. Material on testing will lay the foundation To enable developer to build test cases that will support testing to desired level
How to use Verilog

In order to model and simulate a digital circuit using Verilog we need to Create a Verilog source file using a text editor Compile and simulate the source file Debug if necessary by looking at the simulation output

Some Key Concepts in a Verilog Source File


Case-sensitivity

Verilog is case sensitive When you encounter an error while compiling a Verilog source file Look for case-errors

Edited by Foxit Reader Copyright(C) by Foxit Software Company,2005-2008 For Evaluation Only.

Modules General format

Verilog utilizes the concept of modules Think of a module as a "black box" To make a system consisting of modules We link up the individual black boxes with wires The concept of module permits the building of complex systems By linking lower-level designs Provides a structure for the design process The more modules we have The more complicated the design becomes In such cases, it is convenient to be able to verify functionality Module by module Here is general structure of module declared in Verilog.
module module_name[(outputs_list, inputs_list)]; outputs // outputs from the module inputs // inputs to the module reg // local storage in the module wire // conduction paths in the module code // your code ... ... endmodule

BLOCK

Module Declaration

Declaration begins with keyword module Module followed by Module name inputs_list and the outputs_list These are enclosed in ( ) Declaration terminated with ; The inputs_list and the outputs_list are optional You will use them most of the time The standard convention in Verilog is The outputs_list comes before the inputs_list When the module is declared

Edited by Foxit Reader Copyright(C) by Foxit Software Company,2005-2008 For Evaluation Only.

Inputs and Outputs

Following opening line For each item in the inputs_list and the outputs_list The input and output declarations Must be made following the module declaration.
Syntax output outputs_list; input inputs_list;

Variables and Nets

To begin to do real work Need variables and things To hold stuff and things like that Verilog collects these under terms variables and nets The language defines several different kinds of variables and nets Naturally these used to Hold logical signals Interconnect various components or modules That make up a Verilog model Variable Verilog variable like a variable in C, C++, or Java Can be assigned a value Will hold that value Until a subsequent assignment replaces the value Net Net represents a class of primitive data types Used to model a node or electrical connection in a circuit Cannot Be assigned to Hold a value Value results from being continuously driven By output of a logical device If a net is not driven Takes on the default value of z Meaning high impedance or floating or open.

Wire A wire type is a kind of net Like real world wires are used to Connect output of one logic element to Input(s) of other logical elements Because it is a net Value of a wire can only be changed As result of a gate or a behavioral statement driving it Reg A reg is a kind of variable Value of a reg or register Can be changed directly by an assignment One should not confuse the Verilog reg with the hardware register The reg is simply an entity that can hold a value Default value of a reg data type is x, or unknown The syntax for the reg and wire declarations is given as
Syntax reg regList; wire wireList;

Declaring Multi-Bit Signals

Often necessary to represent multi-bit wires In the jargon we call these busses Formally such sets called vectors A 3-bit wire that can carry digital signals representing the values 0..7 Called a 3 bit vector Types reg and wire can also be formed into a bus such as
Syntax Big Endian reg [msb:lsb] reg_list wire [msb:lsb] wire_list; Little Endian reg [lsb:msb] reg_list wire [lsb:msb] wire_list;

msb is the bit index of the most significant bit lsb is the bit index of the least significant bit

Edited by Foxit Reader Copyright(C) by Foxit Software Company,2005-2008 For Evaluation Only.

The value of the lsb index must be zero Since bit position 0 conventionally denotes the least-significant bit Such statements configure a set of individual wires So that they can now be treated as a group
wire [2:0] myWires; reg [15:0] aState; // a 3-bit signal (a bus) // a 16-bit state holding value

The declaration myWires above Declares a 3-bit signal that has MSB (the 22s place) as myWires[2] Middle bit of myWires[1]. LSB (the 20s place) as myWires[0] The individual signals can be used Just like any other binary value in Verilog
and a1(myWires[2], myWires[0], C);

the 2^2's place

(MSB)

output

inputs

Statement ANDs together C and the LSB of myWires Puts the result in the MSB of myWires. Note again We are not assigning conjunction to myWires[2] The output of gate a1 is driving that signal Only way myWires[2] can change If output of gate changes because input changed This multisignal or bus specification Can be extended to module input and output lists as well Multi-bit signals can be passed together to a module
module random(bus1, bus2); output [31:0] bus1; input [19:0] bus2; wire c; anotherRandom ar1(C, bus2, bus1); endmodule

Edited by Foxit Reader Copyright(C) by Foxit Software Company,2005-2008 For Evaluation Only.
Subsets of Multi-Bit Expressions

On occasion its necessary to break apart multi-bit values Can do that by selecting a subset of a value
32 bits
reg [31:0] myReg; initial myReg[3:1] = b101;

reg can be seen as a "array"

This would set myReg[3] = 1 myReg [2] = 0 myReg [1] = 1 All other bits of myReg will not be altered One can also use the same form to take a subset of a multi-bit wire Pass it as an input to another module
wire[31:0] myWires; output myWires[3:1];

Numbers

Verilog supports two types of number specification Sized Unsized Sized Numbers Sized numbers declaration comprises Size, base, value
Syntax

size base value


size specifies number of bits in number base identifies the base legal bases: d or D decimal o or O octal h or H - hexadecimal value numeric value in specified base

Examples

4b1010 // a 4 bit binary number 8d35 // an 8 bit (2 digit) decimal number 16hface // a 16 bit (4 digit) hex number

Edited by Foxit Reader Copyright(C) by Foxit Software Company,2005-2008 For Evaluation Only.

Unsized Numbers Unsized numbers Without a base specification Decimal by default Without a size specification Have simulator/machine default number of bits Must be at least 32
Examples

1010 o35 hface

// a 32 bit decimal number by default // a 32 bit octal number // a 32 bit hex number

Unknown or High Impedance Values Verilog supports numeric specification For numbers with unknown or high impedance bits/digits Symbols used for specification x unknown value z high impedance value
Examples

4b101x 8dz5

// // // 16hfzxe // //
The Verilog Models

a bit binary number with lsb unknown an 8 bit (2 digit) decimal number with high impedance ms digit a 16 bit (4 digit) hex number with high impedance and unknown digits

Will now examine models and modeling tools At each of the levels Once we have declared our module and variables We then need to define the circuit Lets stop for a minute and look at what we are doing

The Model As engineers We design a circuit We build the circuit We take the circuit to our bench where we build and test our circuit On our test bench We have Test equipment Such equipment consists of Stimulus instruments Switches Function generators Sophisticated data or pattern generators Measurement equipment Voltmeters DVM or DMM Oscilloscopes Logic analyzers Network analyzers Our circuit Our circuit consists of Wires Electronic parts Modules Made up of Wires Electronic parts We connect our test equipment to our circuit With wires We now have a picture that looks like Our circuit is what we call a unit under test - UUT Also known as a device under test - DUT A Verilog source program Follows this model Looks very much like a real electronic bench
test bench stimulus UUT measure wires

Equipment is connected to the UUT using wires On occasion in a Verilog program Stimulus and measurement equipment May be in the same software module Model comprises 3 major elements A test bench A collection of stimulus and measurement modules A circuit or system that we are studying That circuit or system Made up of a number of logical components A logical component may be an atomic device Like a logic gate A number of components or modules Each may in turn be made up of logical devices The stimulus module provides signals into the UUT The measurement module acquires / measures The corresponding outputs of the UUT Introducing the Models Verilog language supports the development of models At three different primary levels of abstraction Gate level model Gives most detailed expression We will use this model Dataflow level model Intermediate level of detail Begins focusing on components Behavioral level Gives most abstract Gate level Modules are implemented by interconnecting the various logic gates Similar to working with SSI and MSI components Also known as a structural model In this class we will work primarily with gate level models

Dataflow level Module is implemented by specifying the movement of the data Amongst the comprising hardware registers Model is analogous to the RTL (Register Transfer Level) level Used in specifying a microprocessor / computer architecture Behavioral level Modeling is based upon an algorithmic description of the problem Without regard for the underlying hardware. If we require a physical definition / implementation of our circuit We must ensure that the logic is correct Producing a mask for a production chip Finalizing the design of a programmable logic device We often will do so by scrutinizing critical elements Of the gate-level model However if we simply want to prototype an idea for a circuit Just to see how it works Do not want to spend time verifying interconnections We use the behavioral model Language does support modeling at the transistor level Work at that level will not be discussed here
Model Development

Will work at the gate level Will illustrate using combinational and sequential design To illustrate how a model is developed at each of the different levels Combinational circuits Will use an AND and an OR gate Extended to implement a NAND and a NOR circuit Sequential circuits Will progress from Basic latch Gated latch Flip-flop Two bit binary counter

Structural / Gate Level Development At the gate level Working with the basic logic gates and flip-flops Typically found in any detailed digital logic diagram Devices model the behavior of the parts We can buy from any electronics store Might design into an ASIC or use in FPGA Verilog supports logic gate primitives identified in adjacent figure As predefined intrinsic modules Prototypes for each of the gates given in the following figure They appear as for C or C++ function or procedure We build simple modules from several different types of gates
buf <name> (OUT1, IN1); not <name> (OUT1, IN1); and <name> (OUT, IN1, IN2); or <name> (OUT, IN1, IN2); nand <name> (OUT, IN1, IN2); nor <name> (OUT, IN1, IN2); xor <name> (OUT, IN1, IN2); xnor <name> (OUT, IN1, IN2); bufif1<name> (out, in, cntrl) bufif0<name> (out, in, cntrl) notif1<name> (out, in, cntrl) notif0<name> (out, in, cntrl) // Sets output equal to input // Sets output to opposite of input // Sets output to AND of inputs // Sets output to OR of inputs // Sets to NAND of inputs // Sets output to NOR of inputs // Sets output to XOR of inputs // Sets to XNOR of inputs // Sets output to input if ctrl is 1 tristate otherwise // Sets output to not input if ctrl is 1 tristate otherwise // Sets output to input if ctrl is 0 tristate otherwise // Sets output to not input if ctrl is 0 tristate otherwise buf and or xor bufif1 notif1 not nand nor xnor bufif0 notif0

Lets look at one of prototypes


buf <name> (OUT1, IN1); not <name> (OUT1, IN1); // Sets output equal to input // Sets output to opposite of input

The <name> for a gate instance Must begin with a letter Thereafter can be any combination of letters, numbers underscore _ $. Gates with more than two inputs Created by simply including additional inputs in the declaration Output list appears first followed by the input list

Example

A five-input and gate is declared as


and <name> (OUT, IN1, IN2, IN3, IN4, IN5); // 5-input AND

Creating Combinational Logic Modules The module is basic building block of Verilog Like C++ or Java class or procedure Expresses distinct local scope All variables declared and defined therein Visible only in that scope A module is similar to a function or procedure in C/C++/Java It performs a computation On the inputs to generate an output At the gate level Verilog module really is a collection of logic gates Each time we declare and define a module We are creating that set of gates Structural or gate level model of a combinational circuit Reflects the physical gates used to implement the design To illustrate the basic process of Creating a Verilog program Modeling combinational logic at the gate level Will begin with the following simple circuit. Example of a simple module begins with following Logic diagram Code fragment Module requires a name Call it AndOr
// Compute the logical AND and OR of inputs A and B. module AndOr(AandB, AorB, A, B); output AandB, AorB; input A, B; and myAnd (AandB, A, B); or myOr (AorB, A, B); endmodule

Can analyze the module line by line


// Compute the logical AND and OR of inputs A and B

First line is a comment designated by the // Everything on a line after a // is ignored Comments can appear On separate lines or at the end of lines of code Top of module begins with keyword module
module AndOr(AandB, AorB, A, B); output AandB, AorB; input A, B;

Indicates Start of module Name of the module AndOr List of signals connected to that module Subsequent lines Declare First two binary values generated by module are outputs Next two (A, B) are inputs to the module The next lines
and myAnd (AandB, A, B); or myOr (AorB, A, B);

Create instances of two gates AND gate called myAnd with output AandB and inputs A and B OR gate called myOr with output orOut and inputs A and B We declare such intrinsic components Same as we did in C, C++ or Java with int, float, or char The final line declares the end of the module
endmodule

All modules must end with an endmodule statement

Observe endmodule statement Is the only one that is not terminated by a semicolon Using Combinational Modules We build up a complex traditional software program by Having procedures call sub procedures Composing or aggregating classes into larger and more powerful structures Verilog builds up complex circuits and systems from modules Using a design approach similar to composition or aggregation To illustrate the process, Will use the previous AndOr module to build NandNor circuit Begin with the logic diagram and Verilog module in following figure

AND Gate AandB myAnd

XnandY

myOr OR Gate AndOr

AorB

XnorY

NandNor

// Compute the logical AND and OR of inputs A and B. module AndOr(AandB, AorB, A, B); output AandB, AorB; input A, B; and myAnd (AandB, A, B); or myOr (AorB, A, B); endmodule // Compute the logical NAND and NOR of inputs X and Y. module NandNor (XnandY, XnorY, X, Y); output XnandY, XnorY; input X, Y; wire XandY, XorY; AndOr myAndOr (XandY, XorY, X, Y); not n1 (XnandY, XandY); not n2 (XnorY, XorY); endmodule

The NandNor module declares instance of the AndOr module As it would any of the intrinsic types One can declare multiple instances of a submodule Another instance of the AndOr module Could be added to the NandNor module

Each instance of the submodule Creates a new set of gates Three instance of AndOr would create a total of 23 = 6 gates The wire Statement
wire XandY, XorY;

Used to connect the outputs of the AndOr module To the two not gates These wires comprise a net that carries the signals From the output of the AndOr module To the inverters The Real-World Affects Part 1 Lets take a first look at incorporating real-world affects Into HDL models Why are we doing this Why is it necessary in our models
Timing and Delays A First Look

In perfect world Parts are ideal Signals flow through wires and parts with no delay In real world Parts are not perfect Signals are delayed by varying amounts Verilog can model signal propagation delay through basic gates Using the # operator
Device Delays

Basic syntax is given as


Syntax #delay device;

We modify the AndOr module To incorporate delays into the design To model and test the affects of real world behavior
// Compute the logical AND and OR of inputs A and B. module AndOr(AandB, AorB, A, B); output AandB, AorB; input A, B; and #5 myAnd (AandB, A, B); or #10 myOr (AorB, A, B); endmodule

The line
and #5 myAnd (AandB, A, B);

states the AND gate takes 5 time units to propagate a change on the input to the output The delay through the OR gate is twice as long Taking 10 time units
or #10 myOr (AorB, A, B);

Units of time can be whatever we want As long as we use consistent values


Net Delays

The delay operator Can also be applied to a net When delay specified on a net Any state change on input to net Delayed accordingly Syntax follows that of device delay
Syntax #delay wire;

Using Symbolic Constants

One can use what are called magic numbers More robust design Will use named or symbolic constants Variables whose value is Set in one place Used throughout a piece of code Learned symbolic constant in Verilog Called a parameter Parameter defined and initialized Using the following syntax.
Syntax parameter = aValue

The following code fragment illustrates symbolic constant for Inclusion of a delay of 2 time units in a part model
parameter propagationDelay = 2; not #propagationDelay myNot (sigOut, sigIn);

Lets modify the previous example to Reflect more professional approach Also incorporate the signal rise and fall times
// Compute the logical AND and OR of inputs A and B. module AndOr(AandB, AorB, A, B); output AandB, AorB; input A, B; parameter delay0 = 5; parameter delay1 = 10; parameter riseTime = 3; parameter fallTime = 4; and #(riseTime, fallTime, delay0) myAnd (AandB, A, B); or #(riseTime, fallTime, delay1) myOr (AorB, A, B); endmodule

Modified code sets Gate delays delay0 and delay1

Rise and fall times To the values specified by remaining two parameters To speed up either gate One could simply change the value in the parameter lines
Sequential Logic

Lets now look at some simple sequential circuits With such circuits Time is integral part of behaviour We build such circuits out of storage elements We will study several different kids D, JK, RS In most cases we will build all of our sequential elements out of D flip-flops Verilog has no built in modules for sequential elements Consequently must build ourselves Thus sequential logic modeled at the gate level First developing the appropriate flip-flop module Then implementing the design As a composition of Instances of that module Necessary gates Interconnecting the components with wires SR Latch Begin with the basic SR latch SR Latch with Enable Basic design can be extended to include

// Gate Level Model S R Latch module srLatch(q, qnot, s, r); input s, r; output q, qnot; parameter delay0 = 2; // implement the latch nor #delay0 n0(q, r, qnot); nor #delay0 n1(qnot, s, q); endmodule

Enable as an additional level of control

// Gate Level Model // Gated SR Latch with clear module gsrLatch(q, qnot, sg, rg, clr, enab); input sg, rg, clr, enab; output q, qnot; parameter delay0 = 2; // Build the gating logic not n0(nclr, clr); and and0(rL, rg, clr, enab); and and1(sL, sg, clr, enab); // Build the basic RS latch nor #delay0 n0(q, rL, nclr, qnot); nor #delay0 n1(qnot, sL, q); endmodule

Master Slave Configuration

The master slave implementation using the gated latch follows naturally

// Use two SR Latches // in a master slave configuration to build a flip-flop module srmsff(q, qnot, s, r, clr, clk); input s, r, clk, clr; output q, qnot; not n0(nclk, clk); gsrLatch master(qm, qnotm, s, r, clr, clk); gsrLatch slave(q, qnot, qm, qnotm, clr, nclk); endmodule

Binary Counter

Can use the SR flip-flop to build Simple two-bit synchronous binary up counter

// Build a two bit binary up counter // using master slave SR flip-flops module TwoBitCntr(qA, qB, clr, clk); input clr, clk; output qA, qB; and a1(sA, qAnot, qB); and a2(rA, qA, qB); srmsff FFB(qB, qBnot, qBnot, qB, clr, clk ); srmsff FFA(qA, qAnot, sA, rA, clr, clk); endmodule

Lets take a look at a simple model for a D flip flop


module D_FF (q, d, clk); output q; input d, clk; reg q; always @(posedge clk) q = d; endmodule

// Indicate that q is stateholding // Hold value except at edge

Most of this should be familiar


Testing and Verifying the Circuit

Once the circuit is designed and modeled in Verilog We move into the next phase First Need to verify that the model functions properly

Next step is to use it for its intended purpose To that end we perform any necessary Functional, parametric, and stress tests on the design Confirm the design before committing to hardware At this point We introduce the general structure for Test bench Tester We will illustrate the verification phase Using the NandNor circuit developed earlier To do this we first create a test bench The Test Bench Test bench models the electronics workbench Electronics workbench Comprises the measurement and stimulus instruments Circuit to be tested The UUT Unit Under Test Verilog test bench Comprises modules used for stimulus and measurement These go in a test module System modeled in Verilog The UUT Diagram gives schematic representation High level pseudocode model for the test bench Has the following general structure
module MyTestBench; parameter declarations wires circuit module declarations test module declaration endmodule

We see that test bench plays the same role as does main() function

In C or C++ Top level class In Java Acts as the outermost container in the program Lets look at the pieces The Unit Under Test Why are we testing During different phases of development life cycle Testing for different reasons Formulating and executing Different kinds of tests At any stage Must have complete and accurate specification Early stages confirming High level functionality Overall behaviour of design Middle stages testing Data and control flow through system Timing Mainly high level but will examine Critical low-level timing aspects

Later stages verifying It performs according to specification Normal operation Boundary operation Inside, at, and outside boundaries Each path through the logic circuit is functional Timing All high and low-level timing constraints met The unit under test or UUT Is system, subsystem, module That we are testing This is our design

We will use the gate level NandNor circuit as the UUT To be tested and verified

Tester - Test Module Lets now move on to the tester or test module This is most critical element in test process This is where most thought must go
Structure or Architecture

Test module will have Initialization sequence To place UUT into known state If start test from unknown state Cannot make any statement about its behaviour A set of inputs and a set of outputs Inputs to the test module Will be the outputs of the UUT Will model the measurement equipment Outputs from the test module Will be the inputs of the UUT These will model the stimulus equipment Set of test vectors These will be outputs of test module Will be Individual vectors Sets of vectors Provide known signals or patterns into UUT

Set of known responses Will be outputs of UUT Known responses to applied stimuli

System Tasks, Functions, and Behavioural Modeling Tools

As we bring the tester together we find Verilog language provides standard system tasks and functions To aid in performing routine operations We will also examine several behavioural level constructs Useful in designing testers Before we launch into tester design Lets look at some of these
always and initial Statements

Each initial and/or always block Express a separate flow of control Each will finish execution independent of any other block Module may define multiple initial and/or always blocks Such blocks cannot be nested Statements contained in an initial block Delimited by begin and end Evaluated one time at the start of a simulation As name suggests We use initial blocks to specify Initial state of variables used in testing Statements contained in an always block Delimited by begin and end Evaluated continuously from the start of a simulation The always and initial statements Two keywords that allow one to set stimuli to a module

The syntax for the initial statement is given as


Syntax initial begin Initial statements end

The syntax for the always statement is given as


Syntax always begin Statements to be always executed end

Flow of Control

The behavioral Verilog model supports Familiar flow of control constructs Branches, switches, and loops Language provides support for event based control Branches Like the C and C++ languages Verilog utilizes the if and if else constructs Select alternate paths of execution Based upon the value of a condition variable Permitted combinations follow the C and C++ syntax
Syntax if (condition) statement; If (condition) statement1; else statement2; If (condition1) statement1; else If (condition2) statement2; else statement 3; If statement comprises a block of statements, the block must be delimited by the begin-end pair.

Case Statement The switch or case statement in Verilog Uses the Pascal rather than the C language syntax Unlike the C switch Once a statement or block of statements is evaluated Flow of control leaves the case Rather than continuing through the remaining alternatives
Syntax case (expression) label0: statement0; label1: statement1; . . labeln-1: statementn-1; default: defaultStatement; endcase If statement comprises a block of statements, the block must be delimited by the begin-end pair

Verilog supports two variants on basic case or switch statement


Syntax casez treats all z values in case labels or expressions as dont cares casex treats all x and z values in case labels or expressions as dont cares

Loops Verilog language supports the four common loop constructs. while repeat for forever First three should be familiar From the C or C++ languages Forever is unique to Verilog Syntax for each is given as

Syntax while(test) begin loop body end repeat(repeatcount) begin loop body end for(init; test; action) begin loop body end init and action are usually assignments. forever begin loop body end

Events Verilog supports four different types of event based control Given as Regular event Named event OR event Level Each is identified by the event control symbol @ Verilog interprets an event as Change in the value of either a net or a register Such a change can be used to invoke Evaluation of either a single statement of a block of statements Syntax for each is given as follows
Syntax Regular Event @(signal) action variable = @( signal) action signal may be clock, posedge clock, negedge clock for example Named Event event anEvent // event is a keyword always @(anEvent) action OR Event always @( signal1 or signal2 or signal3 or) action Level always wait( signal) action // wait is a keyword

Time

Verilog simulations executed with respect to simulation time Value stored in special register data type Time variable declared using keyword time data type Value of time variable can be retrieved Using system function $time Returns the current time Syntax is given as
Syntax $time

// declare variable to hold current time time simTime; initial begin simTime = $time; end

Displaying Information

Given purpose of developing Verilog program Model a design To confirm that it conforms to specification During test of module under design and when test complete Want to be able to Annotate results Observe values of Input and output signals Intermediate and final values of internal variables $display and $monitor statements The $display and $monitor are standard system tasks Enable one to see the states of certain signals in text form Output is typically directed to the screen (or window) Difference between the two statements is $display Only evaluated when the directive is encountered during execution $monitor Evaluated every time any of the signals being monitored Changes state Syntax for the two directives is given as
Syntax $display (["formatrString"], variableList); $monitor (["formatString"], variableList);

The formatString Optional for both statements Both follow the C printf Is a text string containing format variables that are to be instantiated From the values specified in variableList

More commonly used format variables given in following table.


Format Variable %b %d %o %h %c Display Binary Decimal Octal Hexadecimal Character

By convention Logic high is denoted as a 1 Logic low is denoted as a 0 Unknown state is denoted as an x Can include $time in a $display or $monitor statement as
Syntax $display ($time, ["formatString"], variableList); $monitor ($time, ["formatString"], variableList);

$display and $monitor output statements Must be placed within an initial or always block
Stopping and Finishing

There are several system tasks Can be used to terminate or temporarily suspend a simulation These are the $stop and $finish statements As names suggest Used to either stop or finish a simulation $stop directs the simulation to the interactive mode Used when the designer wishes to suspend the simulation prior to exit To examine the state of signal values. $finish terminates the simulation. The syntax for the two directives is given as
Syntax $stop; $finish;

Simulation Time Keeping and Time Units

Since the analysis of circuit timing is such an important issue In the design of digital circuits Verilog has its own time-keeping units It is not in any particular time unit Unit time in Verilog can be equated to Say, 10 nanoseconds (10 ns) in real time The idea is to run conceptual simulations on a circuit So we are not constrained by the ordinary time unit convention If we have a clock running in our source code We can set one half-period of that clock To one time unit in Verilog As long as it is the smallest resolution of simulation time needed. Using the time-keeping units provided in Verilog We can assign propagation delays to the gates and modules That are declared in a Verilog source code The # symbol functions as a delay assignment operator Simulated Time Important to note Simulated time is simulation of Actual time required for design to run when implemented Although value in simulation Has direct relation to physical (in fabricated system) Is not measured in seconds Implemented as unitless integer Common to map or interpret units as nanoseconds When modeling design Must think in terms of simulation time Implication Several Verilog statements may be executed Without $time advancing Sequence Important to distinguish

Sequence and $time Consider following code fragment


module SimTime0; integer a,b; initial begin a = 1; $display("a is %d", a, $time); end initial begin b = 2; $display("b is %d", b, $time); end endmodule

Assignments to both variables Will occur at simulation time 0

Time Control - # We used # symbol when modeling prop delay through part Can also utilize to control when statements executed Modifying above example Code fragment will evaluate b prior to a by one $time unit We have forced the unambiguous evaluation order
module SimTime1; integer a,b; initial begin #4 a = 1; $display("a is %d at $time = %d", a, $time); end initial begin #3 b = 2; $display("b is %d at $time = %d ", b, $time); end endmodule

Event Control - @ We can utilize event specified by @ symbol

To control when statements executed Examine two cases Blocking Non-blocking Modifying above code fragment To utilize blocking assignment Will generate following output a is 1 at $time = 5 b is 3 at $time = 15 c is 6 at $time = 25 d is 9 at $time = 35 If the assignment type in code fragment modified To utilize non-blocking assignment For current implementation Initial block containing all assignments Execute one time All assignments to a..d respectively Evaluated at $time == 0 Will obtain following output a is x at $time = 0 b is x at $time = 0 c is x at $time = 0 d is x at $time = 0

module SimTime2; integer a,b, c, d; integer i; reg sysClk; parameter delay = 5; initial begin sysClk = 0; i = 0; end always begin #delay sysClk = ~sysClk; i = i + 1; end // blocking assignment initial begin a = @(posedge sysClk) i+1; $display("a is %d at $time = %d", a, $time); b = @(posedge sysClk) i+2; $display("b is %d at $time = %d", b, $time); c = @(posedge sysClk) i+3; $display("c is %d at $time = %d", c, $time); d = @(posedge sysClk) i+4; $display("d is %d at $time = %d", d, $time); #(40*sysClk) $stop; $finish; end endmodule

Testing Combinational Logic A First Look

The tester module for the NandNor combinational logic Given in following code fragment Opening lines of the test module Identify the sets of inputs and outputs These signals will Come from the UUT Send stimulus vector to the UUT Following declaration of inputs and outputs Find definition of reg type There are two signal types in test bench Used to drive and monitor signals

During the test of the UUT


module Tester (X, Y, XnandYin, XnorYin); input XnandYin, XnorYin; output X, Y; reg parameter X, Y; stimDelay = 10;

initial // set initial conditions begin x = 0; y = 0; end initial begin // Stimulus

X = 1; Y = 1; #stimDelay X = 0; #stimDelay Y = 0; #stimDelay X = 1; end initial begin // Response display("\t Time, \t \tX, \t Y, \t XnandYin, \t XnorYin"); monitor($time, "\t \t %b, \t %b, \t %b, \t \t%b", X, Y, XnandYin, XnorYin); end endmodule

These two types of signals are reg and wire types The reg data type holds a value Until a new value is driven onto it In an initial or always block. The reg type Can only be assigned a value in an always or initial block Is used to apply stimulus to the inputs of UUT The wire data type is a passive data type Holds value driven on it by Port, assign statement or reg type Wires can not be assigned values Inside always and initial blocks Wires not used in this design Following reg declaration Parameter stimDelay specifies Delay between the applications of successive test vectors Initial block declared next

Initial blocks start executing sequentially at simulation time 0 Starting with the first line between begin end pair Each line executes from top to bottom Until a delay is reached When / if a delay is reached Execution of this block waits Until the delay time has passed and then picks up execution again. Each initial and always block executes concurrently So if a block is stalled Other blocks in the design would execute If always block included An always block does not continuously execute Instead only executes on change in items in the sensitivity list For example posedge clock or negedge reset Recall events discussed earlier Means when there is a low to high on the clock signal or high to low on reset always block will execute. Next test vectors Defined and appear as successive statements Four different combinations of X and Y Applied to the circuit input Delay is specified between each stimulus application Design of the NandNor circuit assumes ideal parts Had the logic gates included a delay The stimDelay between the applications of successive vectors Would have provided time for the signal to propagate Through the logic block.

Initialization and test vectors Written as statements within initial blocks Thus the test suite is applied one time during the simulation The circuit output in response to the set of test vectors Presented using the $display and $monitor system tasks $display is used to print to a line and enter a carriage return at the end Variables can also be added to the display Format for the variables can be Binary using %b Hex using %h Decimal using %d Another common element used in $display is $time which prints the current simulation time To monitor specific variables or signals in a simulation Every time one of the signals changes value A $monitor can be used Only one $monitor can be active at a time in a simulation But it can prove to be a valuable debugging tool Writing the Test Bench Now bring everything together with test bench In the test bench we instantiate One copy of the UUT Here will be NandNor gate, One copy of the Tester These are the stimulus and monitoring instruments Finally, we connect them together using wires As illustrated in the code fragment in following figure
module MyTest bench; wire XnandY, XnorY, X, Y; NandNor aNandNor (XnandY, XnorY, X, Y); Tester aTester (X, Y, XnandY, XnorY); endmodule

Performing the Simulation If the simulation is now run Test vectors are successively applied to the input of the UUT

As the simulation executes $monitor system task will display State of the input and output signals System time at which the samples were taken These appear in previous figure
Time, 0 10 20 30 X, 1, 0, 0, 1, Y, 1, 1, 0, 0, XnandYin, 0, 1, 1, 1, XnorYin 0 0 1 0

If the behavioural results are satisfactory Can move on to real work of confirming the design We do this by utilizing dataflow or structural models Incorporate real world affects and issues

Testing Sequential Logic A First Look

Tester for the behavioral sequential two-bit binary counter module Follows the same pattern with several additions Presented in the code module in following figure Tester designed to Reset system Apply 16 clock pulses to UUT
// Test module for two bit binary up counter module tester(clr, clk, qA, qB); input qA, qB; output clr, clk; reg clk, clr; parameter stimDelay = 15; parameter clkDelay = 5; initial begin clk = 0; clr = 0; #stimDelay clr = ~clr; repeat(16) begin #clkDelay clk = ~clk; end end initial begin $display("\tTime, \t\tqA, \tqB, \tclr, \tclk"); $monitor($time,"\t\t%b, \t%b, \t%b, \t%b", qA, qB, clr, clk); end endmodule

Clocks and Resets

Synchronous sequential circuit will need Strobe, enable, or clock in order to operate As was seen in previous code fragment Specific number of clock pulses supplied to UUT Generally test does not have such restrictions
reg clk, clr;

Good designs also include a reset or clear signal To establish the initial state of the circuit Typically these signals are supplied By the tester with a block of code such as Code fragment in accompanying figure

parameter stimDelay = 15; parameter clkDelay = 5; initial begin clk = 0; clr = 0; #stimDelay clr = ~clr; always #halfPeriod clk = ~clk; end