0% found this document useful (0 votes)
63 views165 pages

Verilog Full

Uploaded by

Rafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views165 pages

Verilog Full

Uploaded by

Rafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

Course Content

1. Introduction to Verilog ---------------------------------------------------------------------------------------------------------


Verilog HDL Brief Description, Level of Abstraction

2. Verilog Lexical Tokens ---------------------------------------------------------------------------------------------------------


White Space, Comments, Numbers, Identifiers, Operators, Verilog Keywords

3. Verilog Data Types ----------------------------------------------------------------------------------------------------------------


Value Set, Wire, Reg, Input, Output, Inout, Integer, Supply0, Supply1, Time, Parameter

4. Operators ---------------------------------------------------------------------------------------------------------------------------
Arithmetic Operators, Relational Operators, Bit-wise Operators, Logical Operators, Reduction Operators,
Shift Operators, Concatenation Operator, Conditional Operator, Operator Precedence

5. Operands ----------------------------------------------------------------------------------------------------------------------------
Literals, Wires, Regs, and Parameters, Bit-Selects “x[3]” and Part-Selects “x[5:3]”, Function Calls

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Course Content
6. Modules--------------------------------------------------------------------------------------------------------------------------------
Module Declaration, Module Instantiations, Parameterized Modules, Continuous Assignment

7. Behavioral Modeling ----------------------------------------------------------------------------------------------------------------


Procedural Assignments, Delay in Assignment, Blocking and Nonblocking Assignments, begin ... end,
for Loops, while Loops, forever Loops, repeat, disable, if ... else if ... else case, casex, casez

8. Timing Controls-----------------------------------------------------------------------------------------------------------------------
Delay Control, Event Control, @, Wait Statement, Intra-Assignment Delay

9. Procedures: Always and Initial Blocks ------------------------------------------------------------------------------------------


Always Block, Initial Block

10. Functions ------------------------------------------------------------------------------------------------------------------------------


Function Declaration, Function Return Value, Function Call, Function Rules, Example

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Course Content
11. Tasks------------------------------------------------------------------------------------------------------------------------------------

12. Component Inference -------------------------------------------------------------------------------------------------------------


Registers, Latches, Flip-flops, Counters, Multiplexers, Adders/Subtracters, Tri-State Buffers Other
Component Inferences

13. Finite State Machines -------------------------------------------------------------------------------------------------------------


Counters, Shift Registers

14. Memories ----------------------------------------------------------------------------------------------------------------------------


Two-dimensional arrays, Initializing memory from a file

15. Compiler Directives---------------------------------------------------------------------------------------------------------------


Time Scale, Macro Definitions, Include Directive

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Course Content
16. System Tasks and Functions -----------------------------------------------------------------------------------------------------
$display, $strobe, $monitor; $time, $stime, $realtime; $reset, $stop, $finish; $deposit; $scope, $showscope;
$list; $random; $dumpfile, $dumpvar, $dumpon, $dumpoff, $dumpall; $shm_probe, $shm_open, $fopen,
$fdisplay, $fstrobe, $fmonitor.

17. Test Benches ------------------------------------------------------------------------------------------------------------------------


Test Benches, Synchronous Test Benches

18. Verilog HDL Interview Questions – Asked in Top Semiconductor MNCs----------------------------------------------

19. Frequently Asked Interview Questions List----------------------------------------------------------------------------------

20. Verilog HDL Practice Question Bank -----------------------------------------------------------------------------------------

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Course Content
Crash Course Duration : 200 Minutes

(Average 10 Minutes Per Module * 20 = 200 Minutes)

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #01 : Introduction to Verilog HDL
• Verilog HDL is one of the two most common Hardware Description Languages (HDL) used by
integrated circuit (IC) designers. The other one is VHDL.
• Designs described in HDL are technology-independent, easy to design and debug, and are usually
more readable than schematics, particularly for large circuits.
• Verilog is used as an input for synthesis programs which will generate a gate-level description (a
netlist) for the circuit.
• The way the code is written will greatly effect the size and speed of the synthesized circuit
• Some Verilog constructs are not synthesizable. (eg. delay)
• Non-synthesizable constructs should be used only for test benches.
Note: “Verilog is NOT a Programming Language. It is a Hardware Description Language !!!”

Programming Language : Let the hardware perform a particular function


HDL : Design that Hardware !!

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #01 : Introduction to Verilog HDL

• There are two types of code in most HDLs:

1) Structural, which is a verbal wiring diagram without storage.


Example 1.1:
assign a=b & c | d;
assign d = e & (~c);
2) Procedural, which is used for circuits with storage, or as a convenient way to write conditional
logic.
Example 1.2:
always @(posedge clk) // Execute the next statement on every rising clock edge.
count <= count+1;

• if and case statements are only allowed in procedural code. As a result, the synthesizers have been
constructed which can recognize certain styles of procedural code as actually combinational.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #01 : Introduction to Verilog HDL
Verilog can be used to describe designs at four levels of abstraction:

(i) Switch level (the switches are MOS transistors inside gates).
(ii) Gate level (interconnected AND, NOR etc.).
(iii) Register transfer level/Data Flow Level (RTL uses registers connected by Boolean equations).
(iv) Algorithmic level/Behavioral Level (much like c code with if, case and loop statements).

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #01 : Introduction to Verilog HDL
(i) Switch level (the switches are MOS transistors inside gates).

Example 1.3:
module inverter (IN, OUT);
input IN;
output OUT;
supply0 VSS;
supply1 VDD;

pmos p(OUT, VDD, IN);


nmos n (OUT, VSS, IN);
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #01 : Introduction to Verilog HDL
(ii) Gate level (interconnected AND, NOR etc.).

Example 1.4: A
Y1
module myDesign(A, B, Y); B
input A;
input B; A
output Y; Y2
and A1(Y1, A,B); B
nand NA1(Y2, A, B);
or O1(Y3, A,B); A
endmodule Y3
B

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #01 : Introduction to Verilog HDL
(iii) Register transfer level/Data Flow Level

A 0
Example 1.5:
module myDesign(A, B, SEL, mux_out); mux_out
input A, B, SEL;
output mux_out;
assign mux_out = (SEL` & A) + (SEL & B); B 1
endmodule

SEL

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #01 : Introduction to Verilog HDL
(iv) Algorithmic Level/Behavioral Level

Design Behavior
Example 1.6:
module myDesign(A, B, SEL, mux_out); Verilog Modeling
input A, B, SEL;
output mux_out;
reg mux_out;
always @(A, B, SEL)
if (SEL = 1) mux_out = B;
begin
else mux_out = A;
if(SEL)
mux_out = B;
else
mux_out = A;
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #02 : Lexical Tokens
Verilog source text files consists of the following lexical tokens –

2.1. White Space :


- Used to separate words
- Can contain spaces, tabs, new-lines and form feeds
- Thus a statement can be extended over multiple lines without any special continuation characters

Example 2.1 :
module sample (a, b, c, d);
input a; // space in the start is ignored
reg [8*6 :1] string = “Earth ” ; // would not be ignored
wire temp;
assign = (a & b &c) | (a & b &c) | (a & b &c) | (a & b &c) | (a & b &c) | (a
& b &c) ; //Multiple line statement

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #02 : Lexical Tokens
2.2. Comments :
Specified in two ways –
- Begin the comment with double slashes (//) : All texts between these characters (//) and
the end of the lines will be ignored by the Verilog Simulators

- Enclose comments between the characters /* and */ : This method allows you to continue
comments on more than one line

Example 2.2:
assign c = a & b; //This is a simple comment

/* this commnet continues on more than one lines !!!


assign x = temp_reg;
assign y = temp1_reg;
*/

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #02 : Lexical Tokens

2.3. Numbers:
- Number values can be specified in binary, octal, decimal or hexadecimal
- Number storage is defined as a number of bits

Example 2.3:

3’b001, A 3-bit number


5’d30, (= 5’b11110)
16’h5ED4, (= 16’d24276)

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #02 : Lexical Tokens

2.4. Identifiers :
- User defined words for variables, function names, module names, block names and instance names
- Begins with a letter or underscore
- Never begins with a number and $
- Identifiers are case-sensitive in Verilog

Example 2.4:

Allowed Identifiers: abcd, my_module, my_design_5, myDesign5, mydesign$

Not Allowed Identifiers : 5myDesign, $myDesign

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #02 : Lexical Tokens

2.5. Operators:
- Operators are one, two or sometimes three characters
- Used to performs operations on variables

Example 2.5:

>, +, -, ~, &, !=, ===

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #02 : Lexical Tokens

2.6. Verilog Keywords:


- Verilog Language Specific words
- They can not be used as Verilog identifiers

Example 2.6:

assign, always, case, while, wire, reg, and, or, module, begin, input, output, inout, posedge, negedge

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #02 : Lexical Tokens
module myDesign(a_i, b_i, ctrl_i, clk_i, result_o);
input a_i;
Verilog Keyword
input b_i; identifier
input clk_i;
input [1:0] ctrl_i; Single line comment
output result_o;
whitespace reg result_o; // Registered Output
/* A small ALU operations, based on the ctrl_i signal
values */
always @(posedge clk_i) Multi line comment
begin
case(ctrl_i) operator
2’b00 : result_o <= a_i & b_i;
2’b01 : result_o <= a_i + 1’b1;
2’b10 : result_o <= a_i | b_i;
2’b11 : result_o <= a_i * b_i; Number
default : result_o <= a_i;
endcase
end
26-11-2022 endmodule VLSI Excellence - Gyan Chand Dhaka 7
Module #03 : Data Types

3.1. Value Set:


- Verilog HDL consists only four basic values
- Almost all Verilog data types store all these values
- Values are –
A) 0 (Logic Zero or False Condition)
B) 1 (Logic One or True Condition)
C) X (Unknown Logic Value)
D) Z (High Impedance State)

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #03 : Data Types

3.2. Wire:
- Represents a physical wire in a circuit and is used to connect gates or modules.
- A value of a wire can be read but not assigned to, in a procedural block or in a function
- A wire does not store its value
- Must be driven by a continuous assignment statement

Example 3.1:
Syntax:
wire a; //simple 1 wire
wire b;
wire wire_variable_scaler;
wire c;
wire [MSB : LSB] wire_variable_vector;
wire [7:0] data; // A cable of 8 wires
assign c = a & b;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #03 : Data Types

3.3. Reg:
- Declare type reg for all data objects on the left hand side of expressions in procedural
blocks (initial and always) and functions.
- Reg data type must be used for latches, flip-flops and memories

Syntax: Example 3.2:

reg reg_variable_1_bit; reg a; // simple 1 bit reg variable


reg [MSB : LSB] reg_variable_vector; reg b;
reg [7:0] data;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #03 : Data Types

3.4. Input, Output, Inout:


- These keywords declare input, output and bidirectional ports of a module or task.
- Input and inout ports are of type wire
- An output port can be configured to be of type wire or reg. The default type is wire

Syntax: Example 3.3:

input simple_port; module sample(a, b, c, d);


input [MSB : LSB] input_port_list; input a; // input defaults to wire
output [MSB : LSB] output_port_list; input b;
inout [MSB : LSB] inout_port_list; output c;
output [2:0] d; /*two bit output, declare its output as reg */
reg [2:0] d;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #03 : Data Types

3.5. Integer:
- Integers are general purpose variables.
- They are mainly used for loop indices, parameters, and constants
- Implicitly they are type of reg but they store data as signed numbers however
explicitly declared reg types store data as unsigned
- Default size is 32 bits
- If they hold constants, during synthesis, synthesizer adjusts them to the minimum
width needed at compilation

Syntax: Example 3.4:

integer integer_variable; integer a; //single 32 bit integer


assign b= 63; // 63 defaults to a 7 bit variable

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #03 : Data Types

3.6. Supply0, Supply1:


- Supply0 and Supply1 define wires tied to Logic 0 (Ground) and Logic 1 (Power),
respectively.

Syntax: Example 3.5:

supply0 logic_0_wire; supply0 gnd_wire;


Supply1 logic_1_wire; supply1 pwr_wire;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #03 : Data Types

3.7. Time:
- A 64-bits quantity that can be used in conjunction with the $time system task to hold
simulation time
- Time is not used for synthesis (Not Synthesizable) and hence only used for simulation

Syntax: Example 3.6:

time time_variable; time current_simulation_time;


current_simulation_time = $time;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #03 : Data Types

3.8. Parameter:
- Parameters allows constants like word length to be defined symbolically in one place.
This makes it easy to change the word length later, by changing only the parameter

Syntax: Example 3.7:

parameter par1 = value1; parameter NUM_OF_BITS = 8;


parameter par2 = value2, parameter ADD = 2’b00, SUB = 2’b01;
par3 = value3, . . . ; Parameter [2:0] Last_State = 3’b111;
parameter [range] param4 = value4;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #04 : Verilog HDL Operators

4.1: Arithmetic Operator:


- These perform arithmetic operations.
- The + and - can be used as either unary (-z) or binary (x-y) operators

Operators:
+ (addition) Example 4.1:
- (subtraction)
* (multiplication) c = a + b;
/ (division) d = a – b;
% (modulus) count = (count + 1) % 16 ;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #04 : Verilog HDL Operators

4.2: Relational Operator:


- Relational operators compare two operands and return a single bit 1or 0.
- These operators synthesize into comparators.
- Wire and reg variables are positive. Thus (-3’b001) = = 3’b111 and (-3d001)>3’b110.
- However for integers -1< 6
Example 4.2:
Operators:
if (x = = y)
< (less than) e = 1;
<= (less than or equal to) else
> (greater than) e = 0;
>= (greater than or equal to)
== (equal to) Equivalent Statement -
!= (not equal to) e = (x == y);

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #04 : Verilog HDL Operators

4.3: Bit-wise Operator:


- Bit-wise operators do a bit-by-bit comparison between two operands.

Operators: Example 4.3:

~ (bitwise NOT) module and2(a, b, c);


& (bitwise AND) input a;
| (bitwise OR) input b;
^ (bitwise XOR) output c;
~^ or ^~(bitwise XNOR) assign c = a & b;
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #04 : Verilog HDL Operators

4.4: Logical Operator:


- Logical operators return a single bit 1 or 0. They are the same as bit-wise operators only for
single bit operands.
- They can work on expressions, integers or groups of bits, and treat all values that are nonzero as “1”.
- Logical operators are typically used in conditional (if ... else) statements since they work with expressions.

Operators: Example 4.4:

! (logical NOT) wire[7:0] x, y, z; // x, y and z are multibit variables.


&& (logical AND) reg a;
|| (logical OR) if ((x == y) && (z))
a = 1; // a = 1 if x equals y, and z is nonzero.
else a = !x; // a =0 if x is anything but nonzero

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #04 : Verilog HDL Operators

4.5: Reduction Operator:


- Reduction operators operate on all the bits of an operand vector and return a single-bit value. These are the
unary (one argument) form of the bit-wise operators.

Operators: Example 4.5:

& (reduction AND) module chk_zero (a, z);


| (reduction OR) input [2:0] a;
~& (reduction NAND) output z;
~| (reduction NOR) assign z = ~| a; // Reduction NOR
^ (reduction XOR) endmodule
~^ or ^~ (reduction XNOR)

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #04 : Verilog HDL Operators

4.6: Shift Operator:


- Shift operators shift the first operand by the number of bits specified by the second operand. Vacated
positions are filled with zeros for both left and right shifts (There is no sign extension).

Operators: Example 4.6:

<< (shift left) assign c = a << 2; /* c = a shifted left 2 bits; vacant positions are
>> (shift right) filled with 0’s */

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #04 : Verilog HDL Operators

4.7: Concatenation Operator:


- The concatenation operator combines two or more operands to form a larger vector.

Operators: Example 4.7:

{ }(concatenation) wire [1:0] a, b;


wire [2:0] x;
wire [3;0] y, Z;
Wire [2:0]count;
assign x = {1’b0, a}; // x[2]=0, x[1]=a[1], x[0]=a[0]
assign y = {a, b}; /* y[3]=a[1], y[2]=a[0], y[1]=b[1], y[0]=b[0] */

assign {count, y} = x + Z; // Concatenation of a result

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #04 : Verilog HDL Operators

4.8: Replication Operator:


- The replication operator makes multiple copies of an item

Operators: Example 4.8:

{n{item}} (n fold replication of an item) wire [1:0] a, b; wire [5:0] x, y, z;


assign x = {4{1’b0}, a}; // Equivalent to x = {0,0,0,0,a }
assign y = {2{a}, {b}}; //Equivalent to y = {a, a, b}
assign z = {6{1’b1}};

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #04 : Verilog HDL Operators

4.9: Conditional Operator: “?”


- Conditional operator is like those in C/C++. They evaluate one of the two expressions based on a
condition.
- It will synthesize to a multiplexer (MUX).
- Operated on 3 operands (Ternary Operator)

Operators: Example 4.9:

(condition) ? (result if condition true): assign a = (g) ? x : y;


(result if condition false) assign a = (inc = = 2) ? a+1 : a-1;
/* if (inc), a = a+1, else a = a-1 */

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


Module #04 : Verilog HDL Operators

4.10: Operator Precedence:


- Table Below shows the precedence of operators from highest to lowest.
- Operators on the same level evaluate from left to right.
- It is strongly recommended to use parentheses to define order of precedence and improve the readability
of your code.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 10


Module #05 : Verilog HDL Operands

5.1: Literals:
- Literals are constant-valued operands that can be used in Verilog expressions.
- The two common Verilog literals are:
1) String: A string literal is a one-dimensional array of characters enclosed in double quotes (“ “)
2) Numeric: constant numbers specified in binary, octal, decimal or hexadecimal.

Syntax: Example 5.1:


n’Fddd ..., where “time is”// string literal
n - integer representing number of bits 267 // 32-bit decimal number
F - one of four possible base formats: 2’b01 // 2-bit binary
b (binary), o (octal), d (decimal), 20’hB36F// 20-bit hexadecimal number
h (hexadecimal). Default is d. ‘o62 // 32-bit octal number
dddd - legal digits for the base format
Module #05 : Verilog HDL Operands

5.2: Wires, Regs, and Parameters:


- Wires, regs and parameters can also be used as operands in Verilog expressions.

Syntax:
Example 5.2:
reg variable_name;
reg a;
reg [MSB : LSB] vector_variable_name;
reg b;
wire wire_variable_name;
wire c;
parameter par1 = value;
parameter N = 4;
assign c = a + b;
assign c = a + N;
Module #05 : Verilog HDL Operands

5.3: Bit-Selects “x[3]” and Part-Selects “x[5:3]”:


- Bit-selects and part-selects are a selection of a single bit and a group of bits, respectively, from a
wire, reg or parameter vector using square brackets “[ ]”.
- Bit-selects and part-selects can be used as operands in expressions in much the same way that
their parent data objects are used.

Syntax: Example 5.3:

variable_name[index] reg [7:0] a, b;


variable_name[MSB:LSB] reg [3:0] ls;
reg c;
c = a[7] & b[7]; // bit-selects
ls = a[7:4] + b[3:0]; // part-selects
Module #05 : Verilog HDL Operands

5.4: Function Calls:


- The return value of a function can be used directly in an expression without first assigning it to a
register or wire variable.

Syntax: Example 5.4:

function_name (argument_list) assign a = b & c & chk_bc(c, b);// chk_bc is a function


/* Definition of the function */
function chk_bc;// function definition
input c, b;
chk_bc = b^c;
endfunction
Module #06 : Verilog HDL Modules

6.1: Module Declaration:


- A module is the principal design entity in Verilog. The first line of a module declaration specifies
the name and port list (arguments).

Syntax: Example 6.1:


module module_name (port_list); module add_sub(add, in1, in2, out); in1
input [msb:lsb] input_port_list; input add; // defaults to wire out
output [msb:lsb] output_port_list; input [7:0] in1, in2; wire in1, in2; ADD_SUB
inout [msb:lsb] inout_port_list; output [7:0] out; reg out;
... statements ... in2
... statements ...
endmodule endmodule
add

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #06 : Verilog HDL Modules
6.2: Module Instantiations:
- Module declarations are designs from which one creates actual objects (instantiations).
- Modules are instantiated inside other modules, and each instantiation creates a unique object
from the actual design. The exception is the top-level module which is its own instantiation
- The instantiated module’s ports must be matched to those defined in the actual module design.
- Modules may not be instantiated inside procedural blocks.(always & initial block)
- This is specified as –

1) by name, using a dot(.) “ .design_port_name (name_of_wire_connected_to_port)”.


Example 6.2:
// Passing arguments by using port names a, b, c
module byname (a, b, c);
...
// Module instantiation in a top level module
byname bynameinstance(c.z, a.x, b.y)
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2
Module #06 : Verilog HDL Modules

2) by position, placing the ports in exactly the same positions in the port lists of both the design and
the instance

Example 6.3:
// Passing arguments(signals) by position.
module byposition (a, b, c);
...
// Module instantiation in a top level module
byposition bypositioninstance(x, y ,z);

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #06 : Verilog HDL Modules
6.3: Parameterized Modules:
- You can build modules that are parameterized and specify the value of the parameter at each
instantiation of the modules
Example 6.4:
//Module Definition
Syntax: module shift_n (it, ot); // used in module test_shift.
module_name #(1st_parameter_values, input [7:0] it; output [7:0] ot;
2nd_parm_value, ...) parameter n = 2;‘ // default value of n is 2
instance_name(port_connection_list); assign ot = (it << n); // it shifted left n times
endmodule
// Module instantiation in a top level module
wire [7:0] in1, ot1, ot2, ot3;
shift_n shft2(in1, ot1), // shift by 2; default
shift_n #(3) shft3(in1, ot2); // shift by 3; override parameter 2.
shift_n #(5) shft5(in1, ot3); // shift by 5; override parameter 2.
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4
Module #06 : Verilog HDL Modules

- Macros do string substitutions and do many of the jobs parameters do. They are good for global
parameters because they do not have to be passed through modules

Syntax: Example 6.5:


define macro_name value; // USING MACROS LIKE PARAMETERS
`define M 8 // Word width
module top
wire [`M -1:0] x, y, z; // equivalent to wire [8-1:0] x,y,z;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #06 : Verilog HDL Modules
6.4: Continuous Assignment:
- The continuous assignment is used to assign a value onto a wire in a module. It is the normal
assignment outside of always or initial blocks (Module #07 ).
- Continuous assignment is done with an explicit assign statement or by assigning a value to a wire
during its declaration.
- Note that continuous assignment statements are concurrent and are continuously executed during
simulation.
- The order of assign statements does not matter. Any change in any of the right-hand-side inputs will
immediately change a left-hand-side output.

Syntax: Example 6.6:


wire wire_variable = value; wire [1:0] a = 2’b01; // assigned on declaration
assign wire_variable = expression; assign b = c & d; // using assign statement
assign d = x | y;
/* The order of the assign statements
does not matter. */
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6
Module #07 : Verilog HDL Behavioral Modeling Part#2
7.7: for Loops:
- Similar to for loops in C/C++, they are used to repeatedly execute a statement or block of
statements.
- If the loop contains only one statement, the begin ... end statements may be omitted.

Syntax:
for (count = value1; count </<=/>/>= value2; count = count +/- step)
begin
Example 7 .7:
... statements ...
for (j = 0; j <= 7; j = j + 1)
end
begin
c[j] = a[j] & b[j];
d[j] = a[j] | b[j];
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #07 : Verilog HDL Behavioral Modeling Part#2
7.8: while Loops:
- The while loop repeatedly executes a statement or block of statements until the expression in the
while statement evaluates to false.
- To avoid combinational feedback, a while loop must be broken with an
@(posedge/negedge clock) statement.
- For simulation a delay inside the loop will suffice.
- If the loop contains only one statement, the begin ... end statements may be omitted.
Note: While loops are not recommended for synthesizable RTL Code because when we synthesize the RTL
code and turn into gates or registers and the synthesizer need to know exactly how many times the loop
will execute.
Syntax: Example 7 .8:
while (expression) while (!overflow) begin
begin @(posedge clk);
... statements ... a = a + 1;
end end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #07 : Verilog HDL Behavioral Modeling Part#2
7.9: forever Loops:
- The forever statement executes an infinite loop of a statement or block of statements.
- To avoid combinational feedback, a forever loop must be broken with an
@(posedge/negedge clock) statement.
- For simulation a delay inside the loop will suffice.
- If the loop contains only one statement, the begin ... end statements may be omitted.

Syntax: Example 7 .9:


forever forever begin
begin @(posedge clk); // or use a= #9 a+1;
... statements ... a = a + 1;
end end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #07 : Verilog HDL Behavioral Modeling Part#2

7.10: repeat (Not synthesizable):


- The repeat statement executes a statement or block of statements a fixed number of times.

Syntax: Example 7 .10:


repeat (number_of_times) repeat (2) begin // after 50, a = 00,
begin #50 a = 2’b00; // after 100, a = 01,
... statements ... #50 a = 2’b01; // after 150, a = 00,
end end // after 200, a = 01

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #07 : Verilog HDL Behavioral Modeling Part#2

7.11: disable:
- Execution of a disable statement terminates a block and passes control to the next statement after the
block.
- It is like the C break statement except it can terminate any loop, not just the one in which it appears.
- Disable statements can only be used with named blocks.

Syntax: Example 7 .11:


disable block_name; begin: accumulate
forever
begin
@(posedge clk);
a = a + 1;
if (a == 2’b0111) disable accumulate;
end
26-11-2022
end
VLSI Excellence - Gyan Chand Dhaka 5
Module #07 : Verilog HDL Behavioral Modeling Part#2

7.12: . if ... else if ... else:


- The if ... else if ... else statements execute a statement or block of statements depending on the result of
the expression following the if.
- If the conditional expressions in all the if’s evaluate to false, then the statements in the else block, if
present, are executed.
- There can be as many else if statements as required, but only one if block and one else block.
- If there is one statement in a block, then the begin .. end statements may be omitted.
- Both the else if and else statements are optional. However if all possibilities are not specifically covered,
synthesis will generated extra latches.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #07 : Verilog HDL Behavioral Modeling Part#2
Syntax: Example 7 .12:
if (expression) if (alu_func == 2’b00)
begin aluout = a + b;
... statements ... else if (alu_func == 2’b01)
end aluout = a - b;
else if (expression) else if (alu_func == 2’b10)
begin aluout = a & b;
... statements ... else // alu_func == 2’b11
end aluout = a | b;
... more else if blocks ... if (a == b) /* This if with no else will generate
else begin a latch for x and ot. This is so they
begin x = 1; will hold there old value if (a != b).*/
... statements ... ot = 4’b1111;
end end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #07 : Verilog HDL Behavioral Modeling Part#2

7.13: case:
- The case statement allows a multipath branch based on comparing the expression with a list of case
choices.
- Statements in the default block executes when none of the case choice comparisons are true.
- With no default, if no comparisons are true, synthesizers will generate unwanted latches.
- Good practice says to make a habit of putting in a default whether you need it or not.
- If the defaults are don’t cares, define them as ‘x’ and the logic minimizer will treat them as don’t cares
and save area.
- Case choices may be a simple constant, expression, or a comma-separated list of same.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #07 : Verilog HDL Behavioral Modeling Part#2
Syntax: Example 7 .12:
case (expression)
case (alu_ctr)
case_choice1:
begin
2’b00: aluout = a + b;
... statements ... 2’b01: aluout = a - b;
end 2’b10: aluout = a & b;
case_choice2: default: aluout = 1’bx; /*Treated as don’t cares for
begin endcase minimum logic generation.*/
... statements ...
end Example 7 .13:
... more case choices blocks ... case ({w, y})
default: 2’b00: aluout = a + b; //case if x, y is 2’b00.
begin 2’b01: aluout = a - b;
... statements ... 2’b10: aluout = a & b;
end 2’b11; aluout = a|b;
endcase default: $display(“Invalid w,y = %b %b ”, w, y);
endcase //Display an error if w,y contain ‘x’s.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


Module #07 : Verilog HDL Behavioral Modeling Part#2

7.13: casex:
- In casex(a), when the case_choice constants contains z, x or ?, they match any value in “a”.
- With case(a), a = x (unknown) matches only a case_choice of x, not 1, 0 or z.
- Also a=z (3-state) matches only z. In short, case uses x to detect a signal value of a=‘x’(unknown).
- Casex uses x as a wild card which can match anything.

Syntax: Example 7 .14:


same as for case statement casex (a)
2’b1x: msb = 1; // msb = 1 if a = 10 or a = 11
// If this were case(a) then only a=1x would match.
2’bz1 : msb = 0; // msb = 0 if a = 01 or a = 11
default: msb = 0;
endcase

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 10


Module #07 : Verilog HDL Behavioral Modeling Part#2

7.13: casez:
- Casez is the same as casex except only ? and z (not x) are used in the case choice constants as don’t
cares.
- Casez is favored over casex since in simulation, an inadvertent x signal, will not be matched by a 0 or 1
in the case choice.

Syntax: Example 7 .15:


same as for case statement casez (d)
3’b1??: b = 2’b11; // b = 11 if d = 100 or greater
3’b01?: b = 2’b10; // b = 10 if d = 010 or 011
default: b = 2’b00;
endcase

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 11


Module #07 : Verilog HDL Behavioral Modeling Part#1

7.1: Behavioral Modeling:


- Verilog procedural statements are used to model a design at a higher level of abstraction
- Behavioral Modeling provides powerful ways of doing complex designs.
- Procedural statements can only be used in procedures (always and initial blocks)

7.2: Procedural Assignments:


- Procedural assignments are assignment statements used within Verilog procedures (always and initial
blocks).
- Only reg variables and integers (and their bit/part-selects and concatenations) can be placed left of the
“=” or “<=” in procedures.
- The right hand side of the assignment is an expression which may use any of the operator types
described in Module #04.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #07 : Verilog HDL Behavioral Modeling
7.3: Delay in Assignment (not for synthesis):
- In a delayed assignment (Inter-Assignment Delay) ∆t time units pass before the statement is
executed and the left-hand assignment is made.
- With intra-assignment delay, the right side is evaluated immediately but there is a delay of ∆t
before the result is place in the left hand assignment. If another procedure changes a right-hand
side signal during ∆t, it does not effect the output.
- Delays are not supported by synthesis tools.

Syntax: Example7.1:
for Procedural Assignment reg sum, a, b, c;
variable = expression sum = b ^ c; // execute now.
Delayed assignment sum = #15 b ^ c; /* b ^ c; evaluated now; sum changed
#∆t variable = expression; after 15 time units. */
Intra-assignment delay
#10 sum = b ^ c; ; /* 10 units after sum changes, b ^ c; is
variable = #∆t expression;
evaluated and sum changes. */

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #07 : Verilog HDL Behavioral Modeling

7.4: Blocking Assignments (‘=’):


- Procedural (blocking) assignments (=) are done sequentially in the order the statements are
written.
- A second assignment is not started until the preceding one is complete.
- “=” best corresponds to what c/c++ code would do; use it for combinational procedures

Syntax:
variable = expression;
variable = #∆t expression; //grab inputs now, deliver ans. later, don’t delay next statement
#∆t variable = expression; //grab inputs later, deliver ans. later; delay next statement by #∆t

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #07 : Verilog HDL Behavioral Modeling
Example 7.2: For simulation
initial
begin
a=1; b=2; c=3;
#5 a = b + c; // wait for 5 units, and execute a= b + c =5.
d = #2a; // Time continues from last line, execute at t = 5 and assign at t= 5 + 2 = 7 units

Example 7.3: For synthesis


always @( *)
begin
Z=Y;
Y=X;
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #07 : Verilog HDL Behavioral Modeling

7.5: Non-Blocking Assignments (‘<=’):


- RTL (nonblocking) assignments (<=), start in parallel.
- The right hand side of nonblocking assignments is evaluated starting from the completion of the
last blocking assignment or if none, the start of the procedure.
- The transfer to the left hand side is made according to the delays. An intra-assignment delay in a
non-blocking statement will not delay the start of any subsequent statement blocking or non-
blocking. However normal delays are cumulative and will delay the output.
- One must not mix “<=” or “=” in the same procedure.
- “<=” best mimics what physical flip-flops do; use it for “always @ (posedge clk ..)” type procedures.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #07 : Verilog HDL Behavioral Modeling

Syntax:
variable <= expression;
variable <= #∆t expression; //grab inputs now, deliver ans. later, don’t delay next statement
#∆t variable <= expression; //grab inputs later, deliver ans. later, don’t delay next statement.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #07 : Verilog HDL Behavioral Modeling

Example 7 .4: For simulation


initial
begin
#3 b <= a; // grab a at t=0 Deliver b at t=3.
#6 x <= b + c; // grab b + c at t=0, wait and assign x at t=6. x is unaffected by b’s change.
end

Example 7 .5: For synthesis


always @( posedge clk)
begin
Z <= Y;
Y <= X;
y <= x;
z <= y;
end
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7
Module #07 : Verilog HDL Behavioral Modeling

7.6: begin ... end:


- begin ... end block statements are used to group several statements for use where one statement is
syntactically allowed.
- Such places include functions, always and initial blocks, if, case and for statements.
- Blocks can optionally be named

Syntax: Example 7 .6:


begin : block name function trivial_one; // The block name is “trivial_one.”
reg reg_variable_list; input a;
integer integer_list; begin: adder_blk; // block named adder, with
parameter parameter_list; integer i; // local integer i
... statements ... ... statements ...
end end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #08 : Verilog HDL Timing Controls

8.1: Delay Control (Not synthesizable):


- Also known as Inter Assignment Delay
- This specifies the delay time units before a statement is executed during simulation.
- A delay time of zero can also be specified to force the statement to the end of the list of statements to
be evaluated at the current simulation time.

Syntax: Example 8 .1:


#delay statement; #5 a = b + c; // evaluated and assigned after 5 time units
#0 a = b + c; // very last statement to be evaluated

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #08 : Verilog HDL Timing Controls

8.2: Intra-Assignment Delay (Not synthesizable):


- This delay #∆ is placed after the equal sign.
- The left-hand assignment is delayed by the specified time units, but the right-hand side of the assignment
is evaluated before the delay instead of after the delay.
- This is important when a variable may be changed in a concurrent procedure.

Syntax: Example 8.2:


variable = #∆t expression; assign a=1; assign b=0;
always @(posedge clk)
b = #5 a; // a = b after 5 time units.
always @(posedge clk)
c = #5 b; /* b was grabbed in this parallel procedure before
the first procedure changed it. */

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #08 : Verilog HDL Timing Controls

8.3: Wait Statement (Not synthesizable):


- Delay executing the statement(s) following the wait until the specified condition evaluates to true

Syntax: Example 8.3:


wait (condition_expression) statement; wait (!c) a = b; // wait until c=0, then assign b to a

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #08 : Verilog HDL Timing Controls
8.4: Event Control, @:
- This causes a statement or begin-end block to be executed only after specified events occur.
- An event is a change in a variable and the change may be: a positive edge, a negative edge, or either (a
level change), and is specified by the keyword posedge, negedge, or no keyword respectively.
Note:
- For synthesis one cannot combine level and edge changes in the same list.
- For flip-flop and register synthesis the standard list contains only a clock and an optional reset.
- For synthesis to give combinational logic, the list must specify only level changes and must contain all
the variables appearing in the right-hand-side of statements in the block.
Syntax: Example 8.4:
@ (posedge variable or always @(posedge clk or negedge rst)
negedge variable) if (rst) Q=0; else Q=D; // Definition for a D flip-flop.
statement; @(a or b or e); // re-evaluate if a or b or e changes.
@ (variable or variable . . .) sum = a + b + e; // Will synthesize to a combinational adder
statement;
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4
Module #09 : Verilog HDL Procedures
9.1: Always Block:
- All always blocks in a module execute simultaneously unlike conventional programming languages,
in which all statements execute sequentially.
- The always block can be used to imply latches, flip-flops or combinational logic.
- All the statements enclosed within begin ... end, executes sequentially.
- The always block is triggered to execute by the level, positive edge or negative edge of one or more
signals (separate signals by the keyword or).
- Procedures can be named. In simulation one can disable named blocks. For synthesis it is mainly used
as a comment.
Syntax 1: Syntax 2:
always @(event_1 or event_2 or ...) always @(event_1 or event_2 or ...)
begin begin: name_for_block
... statements ... ... statements ...
end end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #09 : Verilog HDL Procedures

Example 9.1:
always @(a or b) // level-triggered; if a or b changes levels
always @(posedge clk); // edge-triggered: on +ve edge of clk

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #09 : Verilog HDL Procedures
9.2: Initial Block (Not Synthesizable):
- The initial block is like the always block except that it is executed only once at the beginning of the
simulation.
- It is typically used to initialize variables and specify signal waveforms during simulation.
- Initial blocks are not supported for synthesis.
Example 9.2:
initial
Syntax: begin
initial clr = 0; // variables initialized at
begin clk = 1; // beginning of the simulation
... statements ... end
end inital // specify simulation waveforms
begin
a = 2’b00; // at time = 0, a = 00
#50 a = 2’b01; // at time = 50, a = 01
#50 a = 2’b10; // at time = 100, a = 10
end
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3
Module #10 : Verilog HDL Functions

10.1: Verilog HDL Function :

- Functions are declared within a module, and can be called from continuous assignments, always
blocks, or other functions.
- In a continuous assignment, they are evaluated when any of its declared inputs change.
- In a procedure, they are evaluated when invoked.
- Functions describe combinational logic, and do not generate latches.
- Functions are a good way to reuse procedural code, since modules cannot be invoked from within a
procedure.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #10 : Verilog HDL Functions
10.2: Function Declaration :
- A function declaration specifies the name of the function, the width of the function return value, the
function input arguments, the variables (reg) used within the function, and the function local parameters
and integers

Syntax: Example 10.1:


function [msb:lsb] function_name; function [7:0] my_func; // function return 8-bit
input [msb:lsb] input_arguments; value
reg [msb:lsb] reg_variable_list; input [7:0] i;
parameter [msb:lsb] parameter_list; reg [4:0] temp;
integer [msb:lsb] integer_list; integer n;
... statements ... temp= i[7:4] | ( i[3:0]);
endfunction my_func = {temp, i[[2:0]};
endfunction

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #10 : Verilog HDL Functions
10.3: Function Return Value:
- When we declare a function, a variable is also implicitly declared with the same name as the function
name, and with the width specified for the function name (The default width is 1-bit).
- At least one statement in the function must assign the function return value to this variable.

10.4. Function Call:


- A function call is an operand in an expression. A function call must specify in its terminal list all the
input parameters.

Example 10.2:
wire [7:0] x;
wire [7:0] y;
assign y = my_func[x];

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #10 : Verilog HDL Functions
10.5: Function Return Value:
- Functions must contain at least one input argument.
- Functions cannot contain an inout or output declaration.
- Functions cannot contain time controlled statements (#, @, wait).
- Functions can invoke other functions, but not themselves (not recursive).
- Functions cannot invoke tasks.
- Functions must contain a statement that assigns the return value to the implicit function name register.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #10 : Verilog HDL Functions
10.6: Function Example:
- A Function has only one output. If more than one return value is required, the outputs should be
concatenated into one vector before assigning it to the function name.
- The calling module program can then extract (unbundle) the individual outputs from the concatenated
form.

Example 10.3:
module simple_processor (instruction, outp);
input [31:0] instruction;
output [7:0] outp;
reg [7:0] outp;; // so it can be assigned in always block
reg func;
reg [7:0] opr1, opr2;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #10 : Verilog HDL Functions
Continued . . .
function [16:0] decode_add (instr) end
// returns 1 1-bit plus 2 8-bits 8’b10001010: begin // increment operand
input [31:0] instr; add_func = 1;
reg add_func; opr2 = 8’b00000001;
reg [7:0] opcode, opr1, opr2; end
begin default: begin; // decrement operand
opcode = instr[31:24]; add_func = 0;
opr1 = instr[7:0]; opr2 = 8’b00000001;
case (opcode) end
8’b10001000: begin // add two operands endcase
add_func = 1; decode_add = {add_func, opr2, opr1}; // concatenated
opr2 = instr[15:8]; into 17-bits
end end
8’b10001001: begin // subtract two operands endfunction
add_func = 0;
opr2 = instr[15:8];
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6
Module #10 : Verilog HDL Functions
Continued . . .

always @(instruction) begin


{func, op2, op1} = decode_add (instruction); //
outputs unbundled
if (func == 1)
outp = op1 + op2;
else
outp = op1 - op2;
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #11 : Verilog HDL Tasks
11.1: Verilog HDL Tasks (Not Synthesizable):
A task is similar to a function, but:
- A function runs in “0” time, a task can have time control statements , @, #, wait.
- A task does not return values in-line like a function, but it can have output as well as input ports. Thus it
can send back multiple values. These ports are declared using input and output.
- A function cannot invoke a task, but a task can invoke functions or other tasks.
- A function must have at least one input argument. A task can have zero.
Syntax:
task task_name;
input [msb:lsb] input_port_list;
output [msb:lsb] output_port_list;
reg [msb:lsb] reg_variable_list;
parameter [msb:lsb] parameter_list;
integer [msb:lsb] integer_list;
... statements ...
endtask
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1
Module #11 : Verilog HDL Tasks
Example 11.1:
module alu (func, a, b, c);
input [1:0] func;
always @(func or a or b) begin
input [3:0] a, b;
case (func)
output [3:0] c;
2’b00: my_and (a, b, c);
reg [3:0] c; // so it can be assigned in always
2’b01: c = a | b;
block
2’b10: c = a - b;
task my_and;
default: c = a + b;
input[3:0] a, b;
endcase
output [3:0] andout;
end
integer i;
endmodule
begin
for (i = 3; i >= 0; i = i - 1)
andout[i] = a[i] & b[i];
end
endtask
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2
Module #11 : Verilog HDL Tasks
Example 11.2:
module alu (func, a, b, c);
input [1:0] func;
always @(func or a or b) begin
input [3:0] a, b;
case (func)
output [3:0] c;
2’b00: my_and (a, b, c);
reg [3:0] c; // so it can be assigned in always
2’b01: c = a | b;
block
2’b10: c = a - b;
task my_and;
default: c = a + b;
input[3:0] a, b;
endcase
output [3:0] andout;
end
integer i;
endmodule
begin
for (i = 3; i >= 0; i = i - 1)
#10;
andout[i] = a[i] & b[i];
end
endtask
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3
Module #12 : Verilog HDL Component Inference
12.1: Latches:
- A latch is inferred (put into the synthesized circuit) if a variable, or one of its bits, is not assigned in all
branch of an if statement.
- A latch is also inferred in a case statement if a variable is assigned to in only some of the branches.
- To improve code readability, use the if statement to synthesize a latch because it is difficult to explicitly
specify the latch enable signal using a case statement

Example 12 .1:
d D Q q
always @(clk,d)
begin
if (clk)
q <=d; clk EN
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #12 : Verilog HDL Component Inference

Example 12 .2:
always @(clk or rst or d) d D Q q
begin
if (rst)
q <= 0;
clk EN
else if (clk) R
q <= d;
end rst

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #12 : Verilog HDL Component Inference
12.2: Edge-Triggered Registers, Flip-flops, Counters:
- A register (flip-flop) is inferred by using posedge or negedge clause for the clock in the event list of an
always block. To add an asynchronous reset, include a second posedge/negedge for the reset and use the if
(reset) ... else statement.
- Note that when you use the negedge for the reset (active low reset), the if condition is (!reset).

b
Example 12 .3: D Q a
c
always @(posedge clk)
begin; d
a <= b & c; clk CLK
R
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #12 : Verilog HDL Component Inference

Example 12 .4:
always @(posedge clk or negedge rst); b a
D Q
begin; c
if (! rst)
d
a < = 0; clk CLK
else R
a <= b & c;
end rst

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #12 : Verilog HDL Component Inference

Example 12 .5:
reg [7:0] count;
wire enable;
always @(posedge clk or posedge rst) // Do not include enable.
begin;
if (rst)
count <= 0;
else if (enable)
count <= count+1;
end; // 8 flip-flops will be generated

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #12 : Verilog HDL Component Inference
12.3: Multiplexers:
- A multiplexer is inferred by assigning a variable to different variables/values in each branch of an if or case
statement.
- You can avoid specifying each and every possible branch by using the else and default branches.
- To improve readability of your code, use the case statement to model large multiplexers
Note that a latch will be inferred if a variable is not assigned to for all the possible branch conditions.

Example 12 .6: a 1
if (sel == 1)
y = a; y
else
y = b; b 0

sel

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #12 : Verilog HDL Component Inference

a
Example 12 .7:
b
case (sel) y
2’b00: y = a; c
2’b01: y = b;
d
2’b10: y = c;
default: y = d;
endcase sel[1 : 0]

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #12 : Verilog HDL Component Inference
12.4: Adders/Subtracters:
- The +/- operators infer an adder/subtracter whose width depend on the width of the larger operand

a
+
Example 12 .8:
b 1
if (sel == 1)
y = a + b; y
else c
y = c + d; 0
+
d
sel

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #12 : Verilog HDL Component Inference

Example 12 .9:
if (sel == 1)
y = a + b; a
else
y = c + d; c
sel + y

d
sel

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


Module #12 : Verilog HDL Component Inference
12.5: Tri-State Buffers:
- A tristate buffer is inferred if a variable is conditionally assigned a value of z using an if, case or conditional
operator.

Example 12 .10: en
if (en == 1)
y = a;
else a y
y = 1’bz;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 10


Module #13 : Verilog HDL 1001 Sequence Detector
13.1: Moore FSM:
- In Moore FSM, output depends only on the present state
- Output is less prone to glitch because of registered present state
- More number of states are required
- They react slower to inputs (One clock cycle later)
Moore Machine

Inputs
Present
Next State Output
State

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #13 : Verilog HDL 1001 Sequence Detector
13.2: Mealy FSM:
- In Mealy FSM, output depends on the present state as well as present input
- Output is more prone to glitch because of asynchronous dependency on present input
- Less number of states are required
- They react faster to inputs

Melay Machine

Inputs
Present
Next State Output
State

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #13 : Verilog HDL 1001 Sequence Detector
13.3: Verilog FSM Design Techniques :

1) Using a Single Process (Procedural Block) to Code Present State, Next State and Output Logic
2) Using Two Process, One to code Present State and Next State logic and another to code Output Logic,
3) Using Three Process each to code Present State, Next State and Output Logic

Note: When modeling finite state machines, it is recommended to separate the sequential current-state logic
from the combinational next-state and output logic.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #13 : Verilog HDL 1001 Sequence Detector
13.4: 1001 Sequence Detector Moore (Non-Overlapping) FSM Diagram :

reset 0

S0/0 S0 – On Reset
S1 – 1 is detected
0 1 S2 – 10 is detected
1 S3 – 100 is detected
0 S4 – 1001 is detected
S1/0

1 1
S4/1 S2/0
0

1 0
S3/0

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #13 : Verilog HDL 1001 Sequence Detector
13.5: 1001 Sequence Detector Moore (Non Overlapping) Verilog Code :
Example 13.1:
module moore_1001_nonovr (clk, rst, data_i, data_o); S1: begin default: nxt_st = S0;
input clk, rst, data_i; if(data_i) nxt_st = S1; endcase
output data_o; // data_o is declared reg so that it can else nxt_st = S2 end
reg data_o; // be assigned in an always block. end // default is optional since
parameter S0=0, S1=1, S2=2, S3=3, S4 = 4; S2: begin //all 4 cases are covered
reg [2:0] state, nxt_st; if (data_i) nxt_st = S1; //specifically. Good practice
always @ (state or data_i) else nxt_st = S3; // says uses it
begin : next_state_logic //Name of always procedure. end
case (state) S3: begin
S0: begin if (data_i) nxt_st = S3;
if (data_i) nxt_st = S1; else nxt_st = S0;
else nxt_st = S0; end
end S4: begin
if (data_i) nxt_st = S1;
else nxt_st = S0;
26-11-2022
end
VLSI Excellence - Gyan Chand Dhaka 5
Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: 1001 Sequence Detector Moore (Non Overlapping) Verilog Code :

always @(posedge clk or posedge rst) always @(state) begin : output_logic


begin : register_generation case (state)
if (rst) state = S0; S0: data_o = 1’b0;
else state = nxt_st; S1: data_o = 1’b0;
end S2: data_o= 1’b0;
S3: data_o = 1’b0;
S4: data_o = 1’b1;
default: data_o = 1’b0;; // default avoids latches
endcase
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #13 : Verilog HDL 1001 Sequence Detector
13.4: 1001 Sequence Detector Moore (Overlapping) FSM Diagram :
reset 0

S0/0 S0 – On Reset
S1 – 1 is detected
1 S2 – 10 is detected
1 S3 – 100 is detected
0 S4 – 1001 is detected
S1/0
1 1
0
S4/1 S2/0
0

1 0
S3/0

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #13 : Verilog HDL 1001 Sequence Detector
13.5: 1001 Sequence Detector Moore (Overlapping) Verilog Code :
Example 13.2:
module moore_1001_ovr (clk, rst, data_i, data_o); S1: begin default: nxt_st = S0;
input clk, rst, data_i; if(data_i) nxt_st = S1; endcase
output data_o; // data_o is declared reg so that it can else nxt_st = S2 end
reg data_o; // be assigned in an always block. end // default is optional since
parameter S0=0, S1=1, S2=2, S3=3, S4 = 4; S2: begin //all 4 cases are covered
reg [2:0] state, nxt_st; if (data_i) nxt_st = S1; //specifically. Good practice
always @ (state or data_i) else nxt_st = S3; // says uses it
begin : next_state_logic //Name of always procedure. end
case (state) S3: begin
S0: begin if (data_i) nxt_st = S3;
if (data_i) nxt_st = S1; else nxt_st = S0;
else nxt_st = S0; end
end S4: begin
if (data_i) nxt_st = S1;
else nxt_st = S2;
26-11-2022
end
VLSI Excellence - Gyan Chand Dhaka 8
Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: 1001 Sequence Detector Moore (Overlapping) Verilog Code :

always @(posedge clk or posedge rst) always @(state) begin : output_logic


begin : register_generation case (state)
if (rst) state = S0; S0: data_o = 1’b0;
else state = nxt_st; S1: data_o = 1’b0;
end S2: data_o= 1’b0;
S3: data_o = 1’b0;
S4: data_o = 1’b1;
default: data_o = 1’b0;; // default avoids latches
endcase
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


Module #13 : Verilog HDL 1001 Sequence Detector
13.4: 1001 Sequence Detector Mealy (Non-Overlapping) FSM Diagram :
reset 0/0

S0 S0 – On Reset
S1 – 1 is detected
1/0 S2 – 10 is detected
1/0 S3 – 100 is detected
S1 0/0

1/0
1/1 0/0 S2

0/0
S3

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 10


Module #13 : Verilog HDL 1001 Sequence Detector
13.5: 1001 Sequence Detector Mealy (Non Overlapping) Verilog Code :
Example 13.3:
module mealy_1001_nonovr (clk, rst, data_i, data_o); S1: begin default: nxt_st = S0;
input clk, rst, data_i; if(data_i) nxt_st = S1; endcase
output data_o; // data_o is declared reg so that it can else nxt_st = S2 end
reg data_o; // be assigned in an always block. end // default is optional since
parameter S0=0, S1=1, S2=2, S3=3, S4 = 4; S2: begin //all 4 cases are covered
reg [2:0] state, nxt_st; if (data_i) nxt_st = S1; //specifically. Good practice
always @ (state or data_i) else nxt_st = S3; // says uses it
begin : next_state_logic //Name of always procedure. end
case (state) S3: begin
S0: begin if (data_i) nxt_st = S0;
if (data_i) nxt_st = S1; else nxt_st = S0;
else nxt_st = S0; end
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 11


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: 1001 Sequence Detector Mealy (Non Overlapping) Verilog Code :

always @(posedge clk or posedge rst) always @(state or data_i) begin : output_logic
begin : register_generation case (state)
if (rst) state = S0; S0: data_o = 1’b0;
else state = nxt_st; S1: data_o = 1’b0;
end S2: data_o= 1’b0;
S3: begin
if(data_i) data_o = 1’b1;
else data_o = 1’b0;
end
default: data_o = 1’b0;; // default avoids latches
endcase
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 12


Module #13 : Verilog HDL 1001 Sequence Detector
13.4: 1001 Sequence Detector Mealy (Overlapping) FSM Diagram :
reset 0/0

S0 S0 – On Reset
S1 – 1 is detected
1/0 S2 – 10 is detected
1/0 S3 – 100 is detected
S1 0/0
0/0
1/0
1/1 S2

0/0
S3

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 13


Module #13 : Verilog HDL 1001 Sequence Detector
13.5: 1001 Sequence Detector Mealy (Overlapping) Verilog Code :
Example 13.4:
module mealy_1001_ovr (clk, rst, data_i, data_o); S1: begin default: nxt_st = S0;
input clk, rst, data_i; if(data_i) nxt_st = S1; endcase
output data_o; // data_o is declared reg so that it can else nxt_st = S2 end
reg data_o; // be assigned in an always block. end // default is optional since
parameter S0=0, S1=1, S2=2, S3=3, S4 = 4; S2: begin //all 4 cases are covered
reg [2:0] state, nxt_st; if (data_i) nxt_st = S1; //specifically. Good practice
always @ (state or data_i) else nxt_st = S3; // says uses it
begin : next_state_logic //Name of always procedure. end
case (state) S3: begin
S0: begin if (data_i) nxt_st = S1;
if (data_i) nxt_st = S1; else nxt_st = S0;
else nxt_st = S0; end
end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 14


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: 1001 Sequence Detector Mealy (Non Overlapping) Verilog Code :

always @(posedge clk or posedge rst) always @(state or data_i) begin : output_logic
begin : register_generation case (state)
if (rst) state = S0; S0: data_o = 1’b0;
else state = nxt_st; S1: data_o = 1’b0;
end S2: data_o= 1’b0;
S3: begin
if(data_i) data_o = 1’b1;
else data_o = 1’b0;
end
default: data_o = 1’b0;; // default avoids latches
endcase
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 15


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.1: Finite State Machines (FSMs):
- In Digital VLSI design, Finite State Machines play a very important role in implementing the correct
behaviour of the system during different operating modes.
- The FSM enables the system to go through different operating modes as per the user requirements or
during the self booting process

Examples :
1) Implementing different Low Power Modes in a SoC using State Machines
2) Transmitter and Receiver Logic Implementation ( UART, SPI etc )

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.2: Moore and Mealy FSMs:
- In Moore FSM, output depends only on the present state
- Output is less prone to glitch because of registered present state
- More number of states are required
- They react slower to inputs (One clock cycle later)
Moore Machine

Inputs
Present
Next State Output
State

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.3: Moore and Mealy FSMs:
- In Mealy FSM, output depends on the present state as well as present input
- Output is more prone to glitch because of asynchronous dependency on present input
- Less number of states are required
- They react faster to inputs

Melay Machine

Inputs
Present
Next State Output
State

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.4: FSM Design Techniques :

1) Using a Single Process (Procedural Block) to Code Present State, Next State and Output Logic
2) Using Two Process, One to code Present State and Next State logic and another to code Output Logic,
3) Using Three Process each to code Present State, Next State and Output Logic

Note: When modeling finite state machines, it is recommended to separate the sequential current-state logic
from the combinational next-state and output logic.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: Defining State Definition :

1) Using Parameters:
parameter state0 = 0, state1 = 1, state2 = 2, state3 = 3;
2) Using Macros:
`define state0 2'd0
`define state1 2'd1
`define state2 2’d2
`define state3 2'd3;
When using macro definitions one must put a back quote in front. For example:
case (state)
`state0: Z = 3’b000;
`state1: Z = 3’b101;
`state2: Z = 3’b111;
`state3: Z = 3’b001;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: FSM Design Example : start = 0
reset = 1
state0: Z = 3’b000;
state1: Z = 3’b101;
state0
state2: Z = 3’b111;
state3: Z = 3’b001;
wait3 = 0 start = 1

state3 state1
skip3 = 1

wait3 = 1 skip3 = 0

state2

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: FSM Design Example :
state1: begin
Example 13.1: nxt_st = state2;
module my_fsm (clk, rst, start, skip3, wait3, Z); end
input clk, rst, start, skip3, wait3; state2: begin
output [2:0] Z; // Z is declared reg so that it can if (skip3) nxt_st = state0;
reg [2:0] Z; // be assigned in an always block. else nxt_st = state3;
parameter state0=0, state1=1, state2=2, state3=3; end
reg [1:0] state, nxt_st; state3: begin
always @ (state or start or skip3 or wait3) if (wait3) nxt_st = state3;
begin : next_state_logic //Name of always procedure. else nxt_st = state0;
case (state) end
state0: begin default: nxt_st = state0;
if (start) nxt_st = state1; endcase // default is optional since all 4 cases are
else nxt_st = state0; end // covered specifically. Good practice
end // says uses it

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #13 : Verilog HDL Finite State Machines (FSMs)
13.5: FSM Design Example :

always @(posedge clk or posedge rst)


begin : register_generation
if (rst) state = state0;
else state = nxt_st;
end
always @(state) begin : output_logic
case (state)
state0: Z = 3’b000;
state1: Z = 3’b101;
state2: Z = 3’b111;
state3: Z = 3’b001;
default: Z = 3’b000; // default avoids latches
endcase
end
endmodule

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #14 : Verilog HDL Array & Memories

14.1: Verilog Array and Memories:


- An array declaration in Verilog can be either scalar or vector.
- Arrays are allowed in Verilog for ‘reg’, ‘wire’, ‘integer’ and ‘real’ data types

Examples :

1) reg X [0 : 7]; // X is a scalar reg array of depth = 8 and each 1 - bit wide

2) reg [7 : 0] X1 [0 :3]; // X1 is an 8 bit reg vector array with a depth of 4

3) reg [7 :0] X2 [0 : 1] [0 : 3] ; X2 is a 2-Dimensional Array with Rows = 2 and Columns = 4 , each 8 bit wide

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #14 : Verilog HDL Array & Memories

14.2: Verilog Array Assignment:

X = 1’b0; // Illegal assignment as all elements of an array can’t be assigned in a single GO !!

X[1] = 1’b0 // Assign 1st element (Index = 1) of X a 0 (1 – Bit Value).

X1 [2] = 8’hAA; // Assign 8’hAA to Index = 2 of X1 Array

X2 [1] [2] = 8’hBB; Assign 8’hBB to Row = 1; Column = 2 of 2 – D Array X2

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #14 : Verilog HDL Array & Memories

14.3: Few Ky Points :


- Two dimensional arrays can be declared, but can only be accessed by word.
- To get at a bit(s) one must send the output to a register or wire and select the bits from this new variable
- To change one bit, one must read the whole word, change the bit, and write back the word.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #14 : Verilog HDL Array & Memories
14.4: Initializing Memory From a File :
- The command $readmemb will read a file of binary numbers into the array.
- The data file consists of addresses and data.
- An address written in hex as @hhh...and indicates the address of the first word in a block of data.
- It is followed by binary data words separated by blanks. Legal binary bits are “0 1 X Z _”.
- Data not included in the file will be given xxx... values.
- The data may be given in noncontiguous blocks if an address proceeds each block.
- If no initial address is given, @000 is assumed for the first data word.
- Comments are allowed in data files.
- If start_addr is given the memory array will be filled starting at that address and continue until finish_addr
(or the end of the array) is reached.
- The command $readmemh is similar except the data must contain hexadecimal numbers.

@00A // Start address


10101100 11110000 1x000x11 11110101 01011010 01001100 XxxxZzzz 00000000

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #14 : Verilog HDL Array & Memories

14.4: Initializing Memory From a File :

Syntax:
reg [wordsize:0] array [0:arraysize]
readmemb(“file_name”, array_name);
readmemb(“file_name”, array_name, start_addr);
readmemb(“file_name”, array_name, start_addr, finish_addrs);
readmemh(“file_name”, array_name);

// Note: start_addr and finish addr are optional

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #14 : Verilog HDL Array & Memories
14.4: Initializing Memory From a File :

Example 14.1: ------------------------------- file init.dat-------------------------------


reg [7:0] memry [0:31]; // 32 byte memory. // Since start_addr =8 memry[0:9] will all be stored as
wire [7:0] memwrd; xxxxxxxx.
wire x; @00A //
initial begin 10101100 11110000 1x000x11 11110101 01011010 01001100
// Initialize memory contents from file. XxxxZzzz 00000000
$readmemb(“init.dat”, memry, 8); @01E // 5'h1E = 5'd30. Underscore gives readability.
// Start reading at word 8. However the first word in the file 1100_1010 0011_0001
// is 10 (@00A), so words 8 and 9 will default to x.
end
---
// Extract last word in memory.
assign memwrd= memry[31];
// Extract most sig bit in word 31
assign x= memwrd[7];

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #15 : Verilog HDL Compiler Directives

15.1: Compiler Directives:


- Compiler directives are special commands, beginning with `, that affect the operation of the Verilog
simulator.
- A compiler directive is a statement that causes the compiler to take a specific action during compilation.
- Examples :
1) Time Scale
2) Macro Definitions
3) Include Directive

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #15 : Verilog HDL Compiler Directives

15.2: Time Scale:


- `timescale specifies the time unit and time precision. A time unit of 10 ns means a time expressed as say
#2.3 will have a delay of 23.0 ns.
- Time precision specifies how delay values are to be rounded off during simulation.
- Valid time units include s, ms, us (µs), ns, ps, fs.
- Only 1, 10 or 100 are valid integers for specifying time units or precision.
- It also determines the displayed time units in display commands like $display.

Syntax: Example 14 .1:


`timescale time_unit/time_precision; `timescale 1 ns/1 ps // unit =1ns, precision=1/1000ns
`timescale 1 ns /100 ps // time unit = 1ns; precision = 0.1ns;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #15 : Verilog HDL Compiler Directives

Example 15 .2:
`timescale 100ps/10ps shall have a #1 delay of 100ps while you can give #0.1 as the smallest
delay i.e. of 10ps.

`timescale 1ns/1ps shall have `#1` as 1ns and `#0.001ns` as 1ps as the smallest delay.

`timescale 10ps/1fs shall represent a #1 of 10ps delay and #0.001ps is the smallest measurable
delay.

`timescale 1ns/1ns ; #0.49 , which is less than half a time unit. However the time precision is
specified as 1ns and hence the simulator can not go smaller than 1ns which makes it to round
to 0ns
#0.51; will get rounded to 1ns

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #15 : Verilog HDL Compiler Directives

15.3: Macro Definitions:


- A macro is an identifier that represents a string of text. Macros are defined with the directive `define, and
are invoked with the quoted macro name as shown in the example.
- Verilog compilers will substitute the string for the macro name before starting compilation.
- The `define statement must appear in the file before the statement using the string. If they are in separate
files, the file containing the definition must be compiled first.

Syntax: Example 14 .3:


`define macro_name text_string; `define add_lsb a[7:0] + b[7:0]
. . . `macro_name . . `define N 8 // Word length
wire [`N -1:0] S;
assign S = `add_lsb; // assign S = a[7:0] + b[7:0];

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #15 : Verilog HDL Compiler Directives

15.4: Include Directive:


- Include is used to include the contents of a text file at the point in the current file where the include
directive is.
- The include directive is similar to the C/C++ include directive.

Syntax: Example 14 .4:


`include file_name; module x;
`include “dclr.v”; // contents of file “dclr,v” are put here

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #16 : Verilog HDL System Tasks and Functions

16.1: System Tasks and Functions:


- These are tasks and functions that are used to generate input and output during simulation.
- Their names begin with a dollar sign ($).
- Verilog contains the pre-defined system tasks and functions, including tasks for creating output from a
simulation.
- Operations such as displaying the screen, monitoring values of nets, stopping and finishing are done by
system tasks.

Examples : $display, $time, $finish etc

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #16 : Verilog HDL System Tasks and Functions

16.2: $display, $strobe, $monitor:


- Display Selected Variables
- These commands have the same syntax, and display text on the screen during simulation.
- $display and $strobe display once every time they are executed, whereas $monitor displays every time
one of its parameters changes.
- The difference between $display and $strobe is that $strobe displays the parameters at the very end of the
current simulation time.
- Format characters include %d (decimal), %h (hexadecimal), %b (binary), %c (character), %s (string) and
%t (time), %m (hierarchy level).

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #16 : Verilog HDL System Tasks and Functions

Syntax: Example 16 .1:


$display (“format_string”, par_1, par_2, ... ); initial begin // c below is in submodule submod1.
$strobe (“format_string”, par_1, par_2, ... ); $displayh (b, d, submod1.c); //No format, display in hex.
$monitor (“format_string”, par_1, par_2, ... ); $monitor (“time=%t, d=%h, c=%b”,$time, a, submod1.c);
$displayb ( as above but defaults to binary.. end
$strobeh (as above but defaults to hex..
$monitoro (as above but defaults to octal..
initial
#1 a=1; b=0;
$fstrobe(hand1, a, b);
b=1;
end
;will write 1 1 for a and b.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #16 : Verilog HDL System Tasks and Functions

16.3: $time, $stime, $realtime:


- These return the current simulation time as a 64-bit integer, a 32-bit unsigned integer, and a real number,
respectively.
- If the current simulation time is too large and the value does not fit in 32 bits, the $stime function only
returns the 32 low order bits of the value.

Example 15.2:
integer cur_time ;
cur_time = $time ;
integer cur_time ;
cur_time = $stime ;
real cur_time ;
cur_time = $realtime ;

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4


Module #16 : Verilog HDL System Tasks and Functions
16.4: $reset, $stop(n), $finish(n):
- $reset resets the simulation back to time 0.
- $stop halts the simulator and puts it in the interactive mode where the user can enter commands.
- $finish exits the simulator back to the operating system.
Note: Remember that $finish control system task makes the simulator exit, however $stop simply suspends
simulation.
- By default the argument is 1

Argument (n) Description


0 No Messages
1 Simulation Time and Location
2 Simulation Time, Location, Memory
Consumption and CPU time used in
Simulation

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #16 : Verilog HDL System Tasks and Functions

Example 16.3:
$stop ; Suspend simulation and print message (default argument = 1)

#150 $finish(2) ; Exits simulator after 150 time units from the last executed
statement and prints message (argument == 2).

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6


Module #16 : Verilog HDL System Tasks and Functions

16.5: $deposit:
- $deposit sets a net to a particular value, overwriting what was put there by the “circuit”. Good for test
benches.

Syntax: Example 15.4:


$deposit (net_name, value); $deposit (b, 1’b0);
$deposit (outp, 4’b001x);// outp is a 4-bit bus

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #16 : Verilog HDL System Tasks and Functions

16.6: $random :
- $random generates a random integer every time it is called. If the sequence is to be repeatable, the first
time one invokes random give it a numerical argument (a seed). Otherwise the seed is derived from the
computer clock.

Syntax: Example 15.4:


runny = $random; reg [3:0] xyz;
xyzzy = $random(integer); initial begin
integer seeds the generator xyz= $random (7); // Seed the generator so number
randy=$random%integer; // sequence will repeat if simulation is restarted.
integer sets the upper limit of the forever xyz = #20 $random;
range of the random integers. // The 4 lsb bits of the random integers will transfer into the
// xyz. Thus xyz will be a random integer 0 ≤ xyz ≤ 15.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8


Module #16 : Verilog HDL System Tasks and Functions

16.7: $dumpfile, $dumpvar, $dumpon, $dumpoff, $dumpall:


- These can dump variable changes to a simulation viewer.
- The dump files are capable of dumping all the variables in a simulation.
- This is convenient for debugging, but can be very slow.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


Module #16 : Verilog HDL System Tasks and Functions

Syntax: Example 16.5:


$dumpfile(“filename.dmp”) module testbench:
$dumpvar dumps all variables in the design. reg a, b; wire c;
$dumpvar(1, top) dumps all the variables in initial begin;
module top. $dumpfile(“cwave_data.dmp”);
$dumpvar(2, top) dumps all the variables in $dumpvar //Dump all the variables
module top and 1 level below. // Alternately instead of $dumpvar, one could use
$dumpvar(n, top) dumps all the variables in $dumpvar(1, top) //Dump variables in the top module.
module top and n-1 levels below. // Ready to turn on the dump.
$dumpvar(0, top) dumps all the variables in $dumpon
module top and all level below. a=1; b=0;
$dumpon initiates the dump. topmodule top(a, b, c);
$dumpoff stop dumping. end

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 10


Module #16 : Verilog HDL System Tasks and Functions

16.8: $fopen, $fdisplay, $fstrobe, $fmonitor and $fwrite:


These commands write more selectively to files.
- $fopen opens an output file and gives the open file a handle for use by the other commands.
- $fclose closes the file and lets other programs access it.
- $fdisplay and $fwrite write formatted data to a file whenever they are executed. They are the same except
$fdisplay inserts a new line after every execution and $write does not.
- $strobe also writes to a file when executed, but it waits until all other operations in the timestep are
complete before writing.
- Thus initial
#1 a=1; b=0;
$fstrobe(hand1, a, b);
b=1;
end
;will write write 1 1 for a and b.
- $monitor writes to a file whenever any one of its arguments changes
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 11
Module #16 : Verilog HDL System Tasks and Functions

Syntax:
handle1=$fopen(“filenam1.suffix”)
handle2=$fopen(“filenam2.suffix”)
$fstrobe(handle1, format, variable list) //strobe data into filenam1.suffix
$fdisplay((handle2, format, variable list) //write data into filenam2.suffix
$fwrite((handle2, format, variable list) //write data into filenam2.suffix all on
// one line. Put \n in the format string
// where a new line is desired.

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 12


Module #16 : Verilog HDL System Tasks and Functions
Example 16.5:
module testbench:
reg [15:0]a; reg clk; integer hand1; initial begin
initial begin; a=a+8;
#3000 $fclose (hand1); // Close the file
hand1=$fopen(“datastuff.txt”);
$finish;
forever @(posedge clk) begin end
$fstrobe (hand1, “time=%5t, a=%h, c=%b”, submod submod1(a, clk); // with internal variable c.
$time, a, submod1.c);. endmodule
end // Never put statements after a forever block. -------------------------------- Output ----------------------
end time= 5, a=2b, c=0
initial begin time= 10, a=2c, c=1
clk=0; a=8’h2b;
forever #5 clk=~clk;
end // Never put statements after a forever block

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 13


Module #17 : Verilog Test Bench Design

17.1: Verilog Test Bench Design:


- A Test bench supplies the signals and dumps the outputs to simulate a Verilog design (module(s)).
- It invokes the design under test, generates the simulation input vectors, and implements the system tasks to
view/format the results of the simulation.
- It is never synthesized so it can use all Verilog commands

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 1


Module #17 : Verilog HDL Finite State Machines (FSMs)
17.2: FSM Design Example : start = 0
reset = 1
state0: Z = 3’b000;
state1: Z = 3’b101;
state0
state2: Z = 3’b111;
state3: Z = 3’b001;
wait3 = 0 start = 1

state3 state1
skip3 = 1

wait3 = 1 skip3 = 0

state2

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 2


Module #17 : Verilog HDL Finite State Machines (FSMs)
17.3: FSM Design Example :
state1: begin
Example 17.1: nxt_st = state2;
module my_fsm (clk, rst, start, skip3, wait3, Z); end
input clk, rst, start, skip3, wait3; state2: begin
output [2:0] Z; // Z is declared reg so that it can if (skip3) nxt_st = state0;
reg [2:0] Z; // be assigned in an always block. else nxt_st = state3;
parameter state0=0, state1=1, state2=2, state3=3; end
reg [1:0] state, nxt_st; state3: begin
always @ (state or start or skip3 or wait3) if (wait3) nxt_st = state3;
begin : next_state_logic //Name of always procedure. else nxt_st = state0;
case (state) end
state0: begin default: nxt_st = state0;
if (start) nxt_st = state1; endcase // default is optional since all 4 cases are
else nxt_st = state0; end // covered specifically. Good practice
end // says uses it

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 3


Module #17 : Verilog HDL Finite State Machines (FSMs)
17.3: FSM Design Example :
always @(posedge clk or posedge rst)
begin : register_generation
if (rst) state = state0;
else state = nxt_st;
end

always @(state) begin : output_logic


case (state)
state0: Z = 3’b000;
state1: Z = 3’b101;
state2: Z = 3’b111;
state3: Z = 3’b001;
default: Z = 3’b000; // default avoids latches
endcase
end
endmodule
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 4
Module #17 : Verilog HDL Finite State Machines (FSMs)
17.4: Test Bench Design :
Example 17.2:
‘timescale 1 ns /100 ps // time unit = 1ns; precision = 1/10 ns;
module my_fsm_tb; // Test Bench of FSM Design of Example 17.1
/* ports of the design under test are variables in the test bench */
reg clk, rst, start, skip3, wait3;
wire Z;
/**** DESIGN TO SIMULATE (my_fsm) INSTANTIATION ****/
my_fsm dut1 (clk, rst, start, skip3, wait3, Z);
/**** RESET AND CLOCK SECTION ****/
initial begin
clk = 0; rst=0;
#1 rst = 1; // The delay gives rst a posedge for sure.
#200 rst = 0; // Deactivate reset after two clock cycles +1 ns*/
end
always #50 clk = ~clk; // 10 MHz clock (50*1 ns*2) with 50% duty-cycle

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 5


Module #17 : Verilog HDL Finite State Machines (FSMs)
17.4: Test Bench Design :
Continued . . .

/**** SPECIFY THE INPUT WAVEFORMS skip3 & wait3 ****/


initial begin
skip3 = 0; wait3 = 0; // at time 0, wait3=0, skip3=0
#1; // Delay to keep inputs from changing on clock edge.
#600 skip3 = 1; // at time 601, wait3=0, skip3=1
#400 wait3 = 1; // at time 1001, wait3=1, skip3=0
skip3= 0;
#400 skip3 = 1; // at time 1401, wait3=1, skip3=1
wait(Z) skip3 = 0; // Wait until Z=1, then make skip3 zero.
wait3 = $random; //Generate a random number, transfer lsb into wait3
$finish; // stop simulation. Without this it will not stop.
end
endmodule
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 6
Module #17 : Verilog HDL Finite State Machines (FSMs)
17.5: Synchronous Test Bench :
- In synchronous designs, one changes the data during certain clock cycles.
- In the previous test bench one had to keep counting delays to be sure the data came in the right cycle.
- With a synchronous test bench the input data is stored in a vector or array and one part injected in each
clock cycle.
- Synchronous test benches are essential for cycle based simulators, which do not use any delays smaller
than a clock cycle

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 7


Module #17 : Verilog HDL Finite State Machines (FSMs)
Example 17.3:
// Synchronous test bench
module SynchTstBch:
reg [8:1] data;
reg x, clk;
wire y;
integer I;
topmod top1(clk, x, y); //DUT Instantiation
initial begin
data[8:1]=8'b1010_1101; // Underscore spaces bits.
I=1;
x=0;
clk=0;
forever #5 clk= ~clk;
// Any statements placed after forever will never be reached!
end
26-11-2022 VLSI Excellence - Gyan Chand Dhaka 8
Module #17 : Verilog HDL Finite State Machines (FSMs)

Example 17.3:
/*** Send in a new value of x every 3rd clock cycle***/ // Wait for y to respond (change);
@(negedge clk)
always
// Check the result; print a warning if it is not as expected.
begin: data_in_proc if (x != y) $display (“x != y, x=%b, y=%b,” x , y);
@(posedge clk) I<=I+1;
if (I= =9) $finish; // End of simulation end
@(posedge clk) // Wait here for the 2nd clock edge. end // data_in_proc
@(posedge clk) // After the 3rd edge, execute begin ...
begin endmodule
#1; // Keeps data from changing on clock edge.
x <= data[I];

26-11-2022 VLSI Excellence - Gyan Chand Dhaka 9


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques


in Verilog HDL

Video Lecture Link1


Video Lecture Link2
Video Lecture Link3

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 1


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques

 What is FSM ?
 Moore and Mealy FSM Block Diagram
 FSM Design Techniques
 Verilog HDL Design
 Synthesizing the Design
 Test Bench Design
 Analysing Simulation Waveforms

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 2


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques

In Digital VLSI design, Finite State Machines play a very important role in implementing the correct
behaviour of the system during different operating modes.
The FSM enables the system to go through different operating modes as per the user requirements or
during the self booting process

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 3


Finite State Machine (FSM) Design Techniques
Moore and Mealy FSM

Moore Machine

Inputs
Next State Present State Outputs
Output Logic
Logic Logic

Figure #01: Moore Finite State Machine Block Diagram

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 4


Finite State Machine (FSM) Design Techniques

Moore and Mealy FSM

Melay Machine

Inputs
Next State Present State Outputs
Output Logic
Logic Logic

Figure #02: Melay Finite State Machine Block Diagram

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 5


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques

Different Techniques to Design Finite State Machines are as below –


1) Using a Single Process (Procedural Block) to Code Present State, Next State and Output Logic
2) Using Two Process, One to code Present State and Next State logic and another to code Output
Logic,
3) Using Three Process each to code Present State, Next State and Output Logic

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 6


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques

Verilog HDL Design and Test-Bench Simulation:

We will be using EDA Playground (https://www.edaplayground.com) to design Fixed Priority


Round Robin Arbiter in Verilog HDL.
Synthesis using Open Source Synthesis Tool : Yosys (Available in EDA Playgound)
Simulation using Open Source Simulation Tool : Riviera (Available in EDA Playground)

Verilog Project Link1

Verilog Project Link2


Verilog Project Link3

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 7


youtube.com/@vlsiexcellence

Finite State Machine (FSM) Design Techniques

If you find the content valuable, Please do not forget to hit the 👍 button

Also, please do subscribe my YouTube channel and enable the notification to get notified for next
such designs.
I would appreciate your suggestions, any queries and any digital design you would like to understand
starting from circuit to HDL design. Please write them down in the comment section !!!

Thank You !!!

11-01-2023 VLSI Excellence - Gyan Chand Dhaka 8


youtube.com/@vlsiexcellence

Digital Hardware Design


Verilog in 10 Minutes – Verilog Coding Styles

Video Lecture Link

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 1


youtube.com/@vlsiexcellence

Digital Hardware Design

Verilog Combinational Logic (CL)


Y
How would you describe the behavior of this function in words ? 0
Z
foo
Y
If X = 1, then foo = Y or Z, 1
else foo = Y and Z Z

X
How would you describe the behavior of this function in Verilog Code ?

always @ (X or Y or Z)
if(X) foo = Y | Z;
else foo = Y & Z; foo can change when any of X, Y or Z changes
So, code must be rerun whenever any of these changes

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 2


youtube.com/@vlsiexcellence

Digital Hardware Design

Alternative Coding Style for CL


Y
Verilog has a short hand way to capture Combinational Logic 0
Z
Called “Continuous Assignment” foo
Y
1
Z
assign foo = X ? Y | Z : Y & Z;
X
LHS Re-evaluated whenever anything in RSH changes

assign f = a ? b : c

Is same as
if(a) f = b;
else f = c;

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 3


youtube.com/@vlsiexcellence

Digital Hardware Design

Flip-Flop

D Q
Flip Flop Behavior -

For every positive edge of the clock Q changes to become equal to D Clock

Flip Flop Behavior as Verilog Code -

always @ (posedge clock)


Q <= D;
always @ ()
- Triggers execution of the following code block
- () is called ‘Sensitivity List’
-- Describe when execution triggered
15-01-2023 VLSI Excellence - Gyan Chand Dhaka 4
youtube.com/@vlsiexcellence

Digital Hardware Design


Verilog Module for Flip Flop
module flipflop (Clock, X, Y, Z, Q); Y
0 D
Z D Q Q
input Clock, X, Y, Z;
output Q; Y
1 Clock
reg Q; Z
wire D;
assign D = X ? Y | Z : Y & Z; X Clock

always @ (posedge Clock)


begin
Q <= D;
end
endmodule

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 5


youtube.com/@vlsiexcellence

Digital Hardware Design

Verilog Module for Flip Flop

module flipflop (Clock, X, Y, Z, Q);

input Clock, X, Y, Z; Module Name


output Q;
reg Q; Connected Ports
wire D; Port Declarations
assign D = X ? Y | Z : Y & Z;
Local Variables Declarations
always @ (posedge Clock) Code Segments
begin
Q <= D;
end
endmodule

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 6


youtube.com/@vlsiexcellence

Digital Hardware Design

RTL Coding Styles

Three Coding Styles -


• always @(???edge Clock) -> Flip Flops and Input Logic
• always @(*) -> Combinational Logic (CL) specified by its behavior
• assign a = . . . -> Combinational Logic (CL) specified as structure

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 7


youtube.com/@vlsiexcellence

Best Free VLSI Content

1. Verilog HDL Crash Course – Link


2. Static Timing Analysis (STA) – Theory Concepts – Link
3. Static Timing Analysis (STA) – Practice/Interview Questions – Link
4. Low Power VLSI Design – Theory Concepts – Link
5. Low Power VLSI Design (LPVLSI) – Practice/Interview Questions – Link
6. Digital ASIC Design Verilog Projects – Link

Please Like, Comment, Share & Subscribe My Channel in Order to Reach Out the Content to a Larger Audience.

Thanks !!

15-01-2023 VLSI Excellence - Gyan Chand Dhaka 8

You might also like