Verilog Class
Verilog Class
Basic Concept
Verilog Module
In Verilog, the basic unit of hardware is called a
module.
Modules cannot contain definitions of other
modules, i.e. it is illegal to nest module.
A module can, however, be instantiated within
another module.
Allows the higher modules to use its functionality
through its ports.
So, anytime internal implementation can be
changed, without affecting the top module.
verilog SM 2
Syntax of Module
module module_name (list_of_ports);
input/output declarations;
local net/parameter declarations;
Instances of subblock;
Behavioral statements;
Dataflow statements;
endmodule
verilog SM 4
Comments
Single Line Comment:// - begins with a // and
ends with a newline.
Multiple Line Comment:/* <write comment
here> */
Identifiers
Identifiers provide user-defined names for Verilog
objects.
verilog SM 5
An identifier is any sequence of letters, digits, and the
underscore (_) symbol except that:
the first character must not be a digit, and the identifier
must be 1024 characters or less.
Verilog is case sensitive.
Examples: bus8, Bus8, b$c01...
Illegal: 8bus, out_a%b...
Escaped identifiers
allow for any printable ASCII character to be included in
the name.
Escaped identifiers begin with white space.
verilog SM 6
The backslash (“\”) character leads off the
identifier, which is then terminated with white
space. The leading backslash character is not
considered part of the identifier.
Examples of escaped identifiers include: \flip-
flop, \a+b
Escaped identifiers are used for translators
from other CAD systems.
Escaped identifiers should not be used under
normal circumstances.
verilog SM 7
White Space
White space is defined as any of the following
characters: blanks, tabs, newlines, and formfeeds.
These are ignored except for when they are found in
strings.
Number represtation
There are two types of number specification in Verilog:
Sized and Unsized.
verilog SM 8
Sized Numbers:
Syntax: <bit_size>’<base><value>
Examples: 3’b101, 32’b1, 11’d97, 16’h1ff...
Unsized Numbers:
Syntax:’<base><value>
Examples: ’b101, ’d1
Note: Here the size is simulator and machine
specific(must be atleast 32)
verilog SM 9
Logic System
Verilog Logic System
0 : zero, low, false, logic low, ground...
1 : one, high, true, logic high, power...
X : unknown...
Z : high impedance, unconnected, tri-state...
verilog SM 10
Net:
wire, wor, wand, tri, triand, tri0, tri1
etc.
Register:
reg, integer, time and real.
verilog SM 11
Nets are physical connections between different devices.
Declaring a net
wire [<range>] <net_var> [<, net_var>*]
Wire:
must be driven by something, and cannot store a value
without being driven.
cannot be used as the left-hand side of an = or <= sign
in an always@ block.
verilog SM 12
are the only legal type on the left-hand
side of an assign statement.
can only be used to model combinational
logic.
are used to connect input and output ports
of a module instantiation.
verilog SM 13
Reg:
Contain implicit storage - unless a variable of this
type is explicitly assigned/modified, it holds its
previously assigned value.
Default value of an un-initialized reg is 'x' or
undefined.
Declaring a register:
verilog SM 14
can be connected to the input port of a module
instantiation.
can be used as outputs within an actual module
declaration.
is the only legal type on the LHS of an always@ block =
or <= sign.
is the only legal type on the LHS of an initial block = sign
(used in Test Benches).
cannot be used on the LHS of an assign statement.
Can be used to create both combinational and sequential
logic.
verilog SM 15
Integers
General purpose register used for manipulating
quantities.
The default width is host-machine word size but is
atleast 32 bits.
Integers have the following representation:
Eg: integer counter;
initial
counter = -1;
verilog SM 16
Real
Real number constant and real register data types are
declared as real.
They can be specified in decimal notation, i.e. 3.14 or
scientific notation, i.e. 3e6.
They cannot have range.
Their default value is 0.
Eg: real delta;
initial
delta = 4e10;
verilog SM 17
Time:
The data type time can hold a special simulator value called
simulation time which is extracted from the system function
$time.
Time is unsigned integer, 64 bits.
The time information can be used to help you debug
simulations.
Eg: time simulationTime;
initial
begin
simulationTime = $time;
end
verilog SM 18
Arrays are used to hold several objects of the
same type(reg, integer, time, real, realtime and
vector register data types).
Syntax:
<datatype> <array_var><start_addr>:<end_addr>];
Eg:
integer count[1:5]; // an array of 5 integers
reg [7:0] mem[0:8]; // Array of 9 mem, each mem
is 8 bit wide
verilog SM 19
Accessing array elements:
Entire element: mem[6] = 8’b 10101010;
verilog SM 20
Vectors are used to represent multi-bit busses
Syntax: <datatype> [<MSB>:<LSB>] <vector_var>;
Eg:
reg [7:0] MultiBitWord1; // 8-bit reg vector with MSB=7
LSB=0
wire [0:7] MultiBitWord2; // 8-bit wire vector with
MSB=0 LSB=7
reg [3:0] bitslice;
reg a; // single bit vector often referred to as
a scalar
verilog SM 21
Referencing vectors
a = MultiBitWord1[3]; //applies the 3rd bit of
MultiBitWord1 to a
bitslice =MultiBitWord1[5:3]
verilog SM 22
Memories are arrays of vectors which are accessed
similar to hardware memories.
Syntax:
reg [<MSB>:<LSB>] <memory_var>
[<start_addr>:<end_addr>];
Memories are arrays of vector reg.
Eg:
reg [7:0] ram[0:4095]; // 4096 memory cells that are 8
bits wide
verilog SM 23
verilog SM 24
By Ordered List
Signals are Connected to the Corresponding
Ports in the Same Order of Appearance in
Module port list.
By Port Name
Signals are Explicitly Specified to which
port they are connected
Order is not important
verilog SM 25
module Mux4x1 (o, inp, ctrl);
output o; input [3:0] inp; input [1:0] ctrl;
wire [1:0] mid;
Mux2x1 m0 (mid[0], inp[0], inp[1], ctrl[0]);
Mux2x1 m1 (mid[1], inp[2], inp[3], ctrl[0]);
Mux2x1 m2 (o, mid[0], mid[1], ctrl[1]);
endmodule
verilog SM 26
module Mux4x1 (o, inp, ctrl);
output o; input [3:0] inp; input [1:0] ctrl;
wire [1:0] mid;
Mux2x1 (.o(mid[0]), .i1(inp[0]), .i2(inp[1]),
.ctrl(ctrl[0]));
Mux2x1 (.ctrl(ctrl[0]), .i1(inp[2]), .i2(inp[3]),
.o(mid[1]));
Mux2x1 (o, mid[0], mid[1], ctrl[1]);
endmodule
verilog SM 27
Primitive logic gates (instantiations):
and G (out, in1, in2);
nand G (out, in1, in2);
or G (out, in1, in2);
nor G (out, in1, in2);
xor G (out, in1, in2);
xnor G (out, in1, in2);
not G (out1, in);
buf G (out1, in);
verilog SM 28
bufif1 G (out, in, ctrl);
bufif0 G (out, in, ctrl);
notif1 G (out, in, ctrl);
notif0 G (out, in, ctrl);
verilog SM 29
For all primitive gates:
The output port must be connected to a net
(a wire).
The input ports may be connected to nets or
verilog SM 30
Example: Gate Implementation
`timescale 1 ns / 1ns //timescale t_unit/t_precision
module exclusive_or (f, a, b);
input a, b;
output f;
wire t1, t2, t3;
nand #(5) m1 (t1, a, b);
and #(5) m2 (t2, a, t1);
and #(5) m3 (t3, t1, b);
or #(5) m4 (f, t2, t3);
endmodule
verilog SM 31
Representation: $<identifier>.
$time - returns the current simulation time.
$display - used for formatted printing like
printf in C.
$stop - stops simulation(used for debugging).
$finish – ends/terminates simulation.
verilog SM 32
System Tasks
Always
Alwayswritten
writteninside
insideprocedures
procedures
verilog SM 34
Compiler Directives
A compiler directive is immediately preceded by a
grave accent (‘).
‘define - defines a compile-time constant or macro.
Eg: ‘define WORD 32
‘ifdef - ‘else - ‘endif - provide support for conditional
compilation.
Eg: ‘ifdef WORD
Word_cal( ) ;
‘endif
‘include - simple text inclusion(include entire content of a
verilog source during compilation).
verilog SM 35
Arithmetic: + , - , * , / , % ,**
Binary bit-wise: ~ , & , | , ^ , ~^
Unary reduction: & , ~& , | , ~| , ^ , ~^
Logical: ! , && , ||
Equality: == , === , != , !==
Relational: < , < , >= , <=
Logical shift: >> , <<
Conditional: cond_expr? true_expr : false_expr;
Concatenation: {}
Replication: {{}}
verilog SM 36
Operators in Verilog
Arithmetic: + , - , * , / , % ,**
Note: ** - Exponential (ex: t**y is t to the power of y)
%- Modulus (Reminder from division of two
numbers)
Binary bit-wise: ~ , & , | , ^ , ~^
ex: X = 4’b1010, Y = 4’b1101 and Z = 4’b10x1
then:
~X = 4’b0101
X & Y = 4’b1000
X|Y = 4’b1111
X&Z = 4’b10x0
verilog SM 37
Operators in Verilog
Unary reduction: & , ~& , | , ~| , ^ , ~^
ex: X = 4’b1010
then
&X = 1’b0
|X = 1’b1
^X = 1’b0
Logical: ! , && , ||
Logical operators always evaluate to one bit value: 0(false), 1(true) and x
(ambigous)
ex:A = 3 and B =0,
A&&B// evaulates to 0
A||B = 1// evaulates to 1
(A==3) && (B == 0) //evaluates to 1
verilog SM 38
Operators in Verilog
Equality: == , === , != , !==
A == B Possible value 0,1, x
A != B Possible value 0,1, x
A === B Possible value 0,1(includes x and z)
A !== B Possible value 0,1
Relational: < , > , >= , <=
Logical shift: >> , <<
>> : Right Shift
<<: Left Shift
ex: X = 4’b1100, then X>> = 4’b0110 and X<< = 4’b1000
verilog SM 39
Operators in Verilog
Conditional: cond_expr? true_expr : false_expr;
ex:
assign 0ut = ctrl?in1:in0;
Concatenation: {}
A = 1’b1, B = 2’b00 and C = 2’b10
then {A,B}= 3’b100,
{C,B, 2’b10}= 6’b100010
{A, B[0], C[1]} = 3’b101
Replication: {{}}
{4{A}}= 4’b1111
{3{A},2{B}}= 7’b1110000
verilog SM 40
Operator Precedence
Use parentheses to
enforce your
priority
verilog SM 41
Description Styles in Verilog
Two different styles of description:
Data flow
Continuous assignment
Behavioral
Procedural assignment
Blocking
Non-blocking
verilog SM 42
Data-flow Style
Continuous Assignment
Identified by the keyword “assign”.
assign a = b & c;
assign f[2] = c[0];
Forms a static binding between
The ‘net’ being assigned on the LHS,
The expression on the RHS.
The assignment is continuously active.
Almost exclusively used to model combinational logic.
verilog SM 43
Data-flow Style
A Verilog module can contain any number
of continuous assignment statements.
For an “assign” statement,
The expression on RHS may contain both
“register” or “net” type variables.
The LHS must be of “net” type, typically a
“wire”.
verilog SM 44
Some Valid Statements
assign a = b >> 1;
assign a = b << 3;
assign f = {a, b};
assign f = {a, 3’b101, b};
assign f = {x[2], y[0], a};
assign f = { 4{a} }; // replicate four times
assign f = {2’b10, 3{2’b01}, x};
verilog SM 45
Dataflow Modelling
// An 8-bit adder description
module parallel_adder (sum, cout, in1, in2, cin);
input [7:0] in1, in2;
input cin;
output [7:0] sum;
output cout;
assign #20 {cout, sum} = in1 + in2 + cin;
endmodule
verilog SM 46
Dataflow Modelling
module generate_mux (data, select, out);
input [0:7] data;
input [0:2] select;
output out;
assign out = data [select];
endmodule
Note: Non-constant index in expression on RHS
generates a MUX
verilog SM 47
Dataflow Modelling
module generate_set_of_MUX (a, b, f, sel);
input [0:3] a, b;
input sel;
output [0:3] f;
assign f = sel ? a : b;
Endmodule
verilog SM 49
Behavioral Style: Always Block
A module can contain any number of “always”
blocks, all of which execute concurrently.
Basic syntax of “always” block:
always @ (event_expression)
begin
statement;
statement;
end
The @(event_expression) is required for both
combinational and sequential logic descriptions.
Only “reg” type variables can be assigned within an
“always” block.
verilog SM 50
Example: Always Block
// A combinational logic example
module mux21 (in1, in0, s, f);
input in1, in0, s;
output f;
reg f;
always @ (in1 or in0 or s)
if (s)
f = in1;
else
f = in0;
endmodule
verilog SM 51
Example: Always Block
module simple_counter (clk, rst, count);
input clk, rst;
output count;
reg [31:0] count;
always @(posedge clk)
begin
if (rst)
count = 32’b0;
else
count = count + 1;
end
endmodule
verilog SM 52
Behavioral Style: Initial Block
Initial blocks execute only once, at the start of
simulation.
Blocks can be a single statement or a
compound statement.
A compound statement is one or more single
statements enclosed within a begin...end
construct.
verilog SM 53
Example: Initial
module shifter_toplevel;
reg clk, clear, shift;
wire [7:0] data;
//Instance of shift_register
shift_register S1 (clk, clear, shift, data);
initial
begin
clk = 0; clear = 0; shift = 0;
end
always
#10 clk = !clk;
endmodule
verilog SM 54
Delays
Used to delay the subsequent statement by a
specified amount of time.
Eg:
#10 clk = 1;
#10 clk = 0;
verilog SM 55
Behavioral Style: Triggering Control
Triggering control: @ (trigger_event)
Delays execution until trigger_event changes or
transitions.
The trigger_event can be a signal/expression or
multiple expressions linked using the keyword or.
It is also possible to detect for particular transitions
by using the keywords posedge or negedge. Eg:
always @(posedge CLK) q = d;
always @(i0 or i1) o = i0 & i1;
verilog SM 56
Events
execution
executiontriggers
triggersevery
every
•@ time
timeany
anysignal
signalchanges
changes
always @(signal1 or signal2 or ..)
begin
..
end
execution
executiontriggers
triggersevery
every
time
timeclk
clkchanges
changes
from
from00toto11
always @(posedge clk) begin
..
execution
executiontriggers
triggersevery
every
end
time
timeclk
clkchanges
changes
from
from11to to00
always @(negedge clk) begin
verilog SM 57
..
“Initial” Blocks
Will
Willbe bedisplayed
displayed
initial begin
atatsim
simtime
time50
50
#50;
$display(“Really?”);
end
endmodule verilog SM 58
Parameter
A parameter is a constant with a name.
No size is allowed to be specified for a parameter.
parameter HI = 25, LO = 5;
parameter up = 2b’00, down = 2b’01, steady = 2b’10;
verilog SM 59
Example: Parameter
// Parameterized design:: an N-bit counter
module counter (clear, clock, count);
parameter N = 7;
input clear, clock;
output [0:N] count; reg [0:N] count;
always @ (negedge clock)
if (clear)
count <= 0;
else
count <= count + 1;
endmodule
verilog SM 60
Parameters
module top(out, in, clk);
output [1:0] out;
B.
B.Implelementation
Implelementation input [3:0] in;
with input clk;
withparameters
parameters
wire [1:0] out;
wire [3:0] in;
module dff(Q, D, clk); wire clk;
parameter WIDTH = 4; wire [3:0] p_in;
output [WIDTH-1:0] Q; wire wu, wd;
input [WIDTH-1:0] D;
input clk; assign wu = p_in[3] & p_in[2];
assign wd = p_in[1] & p_in[0];
reg [WIDTH-1:0] Q;
wire [WIDTH-1:0] D; dff instA(p_in, in, clk);
wire clk; // WIDTH = 4, from declaration
dff instB(out, {wu, wd}, clk);
always @(posedge clk) defparam instB.WIDTH = 2;
Q = D; // We changed WIDTH for instB only
endmodule endmodule
verilog SM 61
Blocking & Non-blocking
Assignments
verilog SM 62
Blocking Assignment (using ‘=’)
verilog SM 64
Non-Blocking Assignment (using ‘<=’)
Normally occurs at the end of the sequential
block.
Statements subsequent to the instruction under
consideration are not blocked by the
assignment.
Recommended style for modeling sequential
logic.
Can be used to assign several ‘reg’ type
variables synchronously, under the control of a
common clock.
verilog SM 65
Difference
// Section 1: Blocking Section 2: Non-Blocking
statements execute statements execute
sequentially concurrently
#5 a <= b; // waits 5 time units,
#5 a = b; // waits 5 time
evaluates, schedules apply
units, evaluates and for end of current time
applies value to a
c <= d; // evaluate, schedules
c = d; // evaluates and apply for end of current
applies value to c time
// At end of current time
both a and c receive their
values
verilog SM 66
always@ (posedge clk) always@ (posedge clk)
begin
begin a <= b;
a = b; end
always@ (posedge clk)
end
begin
always@ (posedge clk) b <= a;
Begin end
//(2)a becomes 1 and b becomes 0.
b=a;
end
//(1)both a and b becomes
1.
verilog SM 67
Loops
Verilog supports four types of loops:
– ‘while’ loop
– ‘for’ loop
– ‘forever’ loop
– ‘repeat’ loop
verilog SM 68
Condotional Statements
Verilog supports following conditional
statements:
If-else
Case
verilog SM 69
Procedural Statements: if
E.g. 4-to-1 mux:
module mux4_1(out, in, sel);
output out;
if (expr1) input [3:0] in;
true_stmt1; input [1:0] sel;
reg out;
else if (expr2) wire [3:0] in;
wire [1:0] sel;
true_stmt2;
.. always @(in or sel)
if (sel == 0)
else out = in[0];
def_stmt; else if (sel == 1)
out = in[1];
else if (sel == 2)
out = in[2];
else
out = in[3];
endmodule
verilog SM 70
Procedural Statements: case
E.g. 4-to-1 mux:
module mux4_1(out, in, sel);
case (expr) output out;
input [3:0] in;
input [1:0] sel;
item_1, .., item_n: stmt1;
reg out;
item_n+1, .., item_m: stmt2; wire [3:0] in;
.. wire [1:0] sel;
verilog SM 71
Procedural Statements: while
E.g.
module count(Y, start);
output [3:0] Y;
input start;
reg [3:0] Y;
wire start;
integer i;
while (expr) stmt;
initial
Y = 0;
reg [3:0] Y;
wire start;
integer i;
initial
Y = 0;
verilog SM 73
Procedural Statements: repeat
E.g.
module count(Y, start);
output [3:0] Y;
input start;
initial
Can
Canbebeeither
eitheran
an Y = 0;
integer
integeror
oraavariable
variable
always @(posedge start)
repeat (4) #10 Y = Y + 1;
endmodule
verilog SM 74
Some Rules to be Followed
A variable cannot appear as the target of
both a blocking and a nonblocking
assignment.
Following is not permissible:
value = value + 1;
value <= init;
About “Loop” Statements
Loop bound must evaluate to a constant.
Implemented by unrolling the ‘for’ loop, and
replicating the statements.
verilog SM 75
Task and Function
A function shall A task can be
execute at zero executed anytime
simulation time unit. during simulation.
A function cannot A task can contain
contain time- time-controlling,
controlling delay statements.
statements. A task can enable
A function cannot other tasks or
enable a task. functions.
verilog SM 76
Task and Function
A function shall have A task can have zero
at least one input or more arguments
type argument and of any type.
shall not have an A task shall not
output or inout type
return a value.
argument.
A function shall
return a single value.
verilog SM 77
Task
The definition of a task is the following:
task <task name>; // Notice: no list inside ()s
<argument ports>
<declarations>
<statements>
endtask
An invocation of a task is of the following
form:
<name of task> (<port list>);
verilog SM 78
Example: Task
task convert;
input [7:0] temp_in;
output [7:0] temp_out;
begin
temp_out = (9/5) *( temp_in + 32)
end
endtask
verilog SM 79
Example: Calling a Task
module temp_cal (temp_a, temp_b,temp_c, temp_d);
input [7:0] temp_a, temp_c;
output [7:0] temp_b, temp_d;
reg [7:0] temp_b, temp_d;
`include "mytask.v“
always @ (temp_a)
convert (temp_a, temp_b);
always @ (temp_c)
convert (temp_c, temp_d);
endmodule
verilog SM 80
Function
The definition of a function is the following:
function <range or type> <function name>; // Notice: no list
inside ()s
<argument ports>
<declarations>
<statements>
endfunction
where <range or type> is the type of the results
passed back to the expression where the function
was called
verilog SM 81
Example: Function
function myfunction;
input a, b, c, d;
begin
myfunction = ((a+b) + (c-d));
end
endfunction
verilog SM 82
Example: Calling a Function
module func_test(a, b, c, d, e, f);
input a, b, c, d, e ;
output f;
wire f;
`include "myfunction.v"
assign f = (myfunction (a,b,c,d)) ? e :0;
endmodule
verilog SM 83
Verilog Test Bench
What is test bench?
A Verilog procedural block which executes
only once.
Used for simulation.
verilog SM 84
How to Write Testbench?
Create a dummy template
Declare inputs to the module-under-test (MUT) as
“reg”, and the outputs as “wire”
Instantiate the MUT.
Initialization
Assign some known values to the MUT inputs.
Clock generation logic
May include several simulator directives like
$display, $monitor, $dumpfile, $dumpvars, $finish.
verilog SM 85
Example: Testbench
module shifter_toplevel;
reg clk, clear, shift;
wire [7:0] data;
shift_register S1 (clk, clear, shift, data);
initial
begin
clk = 0; clear = 0; shift = 0;
end
verilog SM 86
Example: Testbench(Contd….)
always
#10 clk = !clk;
initial
begin
$display (“\ttime, \tclk, \tclr, \tsft, \tdata);
$monitor (“%d, %d, %d, %d, %d”, $time,clk, reset, clear,
shift, data);
end
initial
#400 $finish;
***** REMAINING CODE HERE ******
endmodule
verilog SM 87
Thank You