Verilog New

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 72

Verilog

What is Verilog
Verilog is a hardware description language (HDL) that describes the
functionality of hardware design
❖Digital and Analog design language
❖Latest Verilog standard: IEEE Standard 1364-2005
❖Verilog is also used in Analog & Mixed Signal Language
Application area of Verilog
Modelling Styles
❖ Data flow model
❖ Structural model
❖ Behavioral model
Continued…
• Dataflow level – The module implementation depends on data flow
specification i.e. how data flows and processes in the design circuit.
• Continuous assignment
a
• Data Flow model f
b AND
module and_gate (a, b, f);
input a, b;
output f;
assign f = a & b;

endmodule
Continued…
• Structural model -Pure predefined gates
• Pure predefined gates
a
• Structural model f
b AND
module and_gate (a, b, f);
input a, b;
output f;
and a1 (f, a, b);

endmodule
Continued..
• Behavioral model- A behavioral description describes a systems
behavior (or) function in an algorithmic fashion
• Procedural assignment (always, initial) • Behavioral model
• Blocking ( = ) module and_gate (a, b, f);
input a, b;
• Non-blocking ( <= ) output reg f;
always @ (a, b) begin
if (a == 1’b1 && b == 1’b1)
a f = 1’b1;
f else
b AND
f = 1’b0;
end

endmodule
Design Styles
• A system can be designed by either bottom up or top down approach

• Bottom up approach :
• Design happens at the lowest of modules and by adding lower modules,
complex modules are made.
• Not preferred for huge systems.
• Top down approach
• It is the preferred method for designing a huge design.
Verilog Module Declaration :
module<module_name>(<port_list>);
In Verilog, the basic unit of hardware is called ...
a module. <implementation>
...
• A module cannot contain definition of endmodule
other modules.
• A module can, however, be instantiated
within another module. // This is illegal to write
module dut_1;
• Instantiation allows the creation of a ...
hierarchy in Verilog description. module dut_2;
...
endmodule
endmodule
input MODULE output
Verilog Module
Example1 :
module and (f, x, y); a
input x, y; f
AND
b
output f;
assign f = x & y;
endmodule
Example2:
Module half_adder(input a,b, output sum,carry);
assign sum =a^b;
assign carry=a&b;
endmodule
Verilog Syntax
• Keywords in lowercase.
• Identifiers
 Case sensitive
 Alphanumeric, underscore and $ characters can be used
• Comments
 Single line – Represented with //
 Multiple line – Represented with /* */
my_identifier
my_identifier2
3my_identifier
$my_identifier
my_identifier$
DUT & TB Connections
• Test bench must know hardware but don’t need to be hardware

A test bench is a
completely closed
system i.e. no
inputs go in or
outputs go out
hence TB has no
ports
D q1 q2 out

Module instantiations clk D_FF1 clk D_FF2 clk D_FF3

• Position based • Name based


module d_flipflop(output q, input d, clock); module d_flipflop(output q, input d, clock);
always @ (posedge clock) always @ (posedge clock)
begin begin
q <= d; q <= d;
end end
endmodule endmodule

module shift_register (input d, clk, output out ); module shift_register (input d, clk, output out );
reg q1, q2; reg q1, q2;
d_flipflop D_FF1(q1, d, clk); d_flipflop D_FF1 (.q(q1), .d(d), .clock(clk));
d_flipflop D_FF2(q2, q1, clk); d_flipflop D_FF2 (.d(q1), .q(q2), .clock(clk));
d_flipflop D_FF3(out, q2, clk); d_flipflop D_FF3 (.clock(clk), .q(out), .d(q2));;
endmodule endmodule
Test bench for Half_adder
module half_adder_tb;
reg a, b;
wire s, c_out;
half_adder ha(a, b, s, c_out);
initial begin
$monitor("At time %0t: a=%b b=%b, sum=%b,carry=%b",$time, a,b,s,c_out);
a = 0; b = 0;
#1;
a = 0; b = 1;
#1;
a = 1; b = 0;
#1;
a = 1; b = 1;
end
endmodule
Data Types
A storage format having a specific range or type is called data type.
 They can be divided into two groups.
1.Net type group: The net-type group represents physical connections
between digital circuits. Ex. wire, wand, wor, etc.
2.Variable type group: The variable type group represents the storage of
values in digital circuits. They are used as variables. Ex. reg, integer
Data types and Default values
Data values:evel
Represents
• 0 - Logic 0 state
• 1 - Logic 1 state
• x - Unknown logic state
• z - High impedance state
Continued…
• Wire- wire is continuously driven by combinational logic.

module two_level (a, b, c, d, f); a


t1
b
input a, b, c, d;
f
output f; c
wire t1, t2; // Intermediate lines d t2
assign t1 = a & b;
and a1 (t1, a, b);
assign t2 = ~(c | d);
assign f = ~(t1 & t2);
endmodule
Continued…
• Reg - Reg is a variable which retains value till it is updated. Flip flops
are modelled using reg data type
module d_flip_flop (d,clk,rst,q);

input d; // data input


input clk; // clock input
input rst; // synchronous reset
output reg q; // output q

always @(posedge clk) // negedge


begin
if(rst == 1'b1)
RESET
q <= 1'b0;
else
q <= d;
end

endmodule
Continued…
module test (input i1,i2, output out);
• integer : Used for loop counting
integer i;
(typical use)
real b = 6.4;
• real : Used to store floating-point time c;
numbers initial
• time : Keeps track of simulation begin
time (not used in synthesis) for(i = 0; i < 54; i++)
• $time - returns integer value begin
(6) out = i; // out = i[0];
• $realtime – returns floating c = $time;
value(6.4) $display(“output=%b, time=%0t”, out, c);
end
end
%b – binary
%d – decimal endmodule
%h – hexadecimal 0 0 1 . . . 0 1 0
%s – string MSB LSB
%t – time 31st 1st 0th
%f - floating bit bit bit
Continued…
String-An ordered collection of characters is called a string. Each
character in a string is stored as 8 bit ASCII values. They are stored
as reg type variable.
module str_mod (input a, ouput b);
reg [8*20:1] string_var;
// reg [160:1] string_var;
// reg [160 - 1:0] string_var;
initial
begin
string_var = “hello world!”;
$display(“string value = %0s”, string_var);
end
endmodule
Arrays
• Two types of arrays – one dimensional & two dimensional
• One dimensional array Syntax: a[3] a[2] a[1] a[0]
• wire/reg [3:0] a = 4’b1111; // register width = 4 1 1 1 1
• wire/reg a [3:0]; // register depth = 4
• a[3] = 1’b1;
1 a[3]
• a[2] = 1’b1;
• a[1] = 1’b1; 1 a[2]
Type of value representation Value assigned
• a[0] = 1’b1; 1 a[1] of value 15
Binary 4 bit 4’b1111
1 a[0]
Decimal 4 bit 15

• [3:0] a -> packed array Hexadecimal 4bit 4’hF

• a [3:0] -> unpacked array


Continued..
• Two dimensional array syntax
• reg [7:0] ram [0:255];

• ram[0] = 8’hff; ram[7] ram[6] ram[5] ram[4] ram[3] ram[2] ram[1] ram[0]

• ram[1][5] = 1’b0; ram[0] ram[0] ram[0][6] ram[0][5] ram[0][4] ram[0][3] ram[0][2] ram[0][1] ram[0][0]
[7]
ram[1] ram[1] ram[1][6] ram[1][5] ram[1][4] ram[1][3] ram[1][2] ram[1][1] ram[1][0]
[7]
. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

ram[255] ram[25 ram[255] ram[255] ram[255] ram[255] ram[255] ram[255] ram[255]


5][7] [6] [5] [4] [3] [2] [1] [0]
Parameters
• Parameters are not variables , they are constants. Their values can’t be
changed during run time.
Module Parameters:
module ram (clk,rst,d_in,radd,wadd,d_out ); Parametrized module :
parameter dt_width =8; module buffer #(parameter WIDTH=8)(input
//Defines dt_width as a constant value 8 [WIDTH-1:0]var1,output[WIDTH-1:0]var2);
parameter ad_depth=256;
//Defines ad_depth as a constant value 256 assign var2=var1;
-------------
------------- endmodule
reg[(dt_width-1):0]mem[(ad_depth-1):0];
//Declaring a 256X8 memory using parameter
endmodule
• Parameters can be changed inside the module in 2 ways.
1. During module instantiation
Parameters can be overridden with new values during module instantiation.
the new parameters are passed in with in #( )
Example:
module ram (clk, rst, in, addr, out);
parameter WIDTH = 8; // 16
parameter DEPTH = 128; // 256
reg [(WIDTH-1):0] mem [(DEPTH-1):0]; // declaring the 128X8 memory using parameters.
….
endmodule

module test_bench (….);


input rst, clk;
output out;
…….
// overriding using position
ram #(16,256) mem1 (.clk(clk), .rst(rst),…..);

// overriding using names


ram #( .DEPTH(256), .WIDTH(16)) mem2 (.clk(clk), .rst(rst),…..);
…….
endmodule
2. Defparams
Using defparam this method is used to quickly update the design parameters without having to reinstatiate
the module.

Example:
module design_ip #(parameter WIDTH = 8,parameter DEPTH = 128) ( input [BUS_WIDTH-1 : 0 ]
addr,…);
reg [(WIDTH-1):0] mem [(DEPTH-1):0]; // declaring the 128X8 memory using parameters.
………………….
……………….
endmodule

module tb ();
…..
design_ip DUT (…);
defparam DUT.WIDTH = 64;
…..
endmodule
Operators
• Logical operators
• Bitwise operators
• Reduction operators
• Arithmetic operators
• Relational operators
• Shift operators
• Equality operators
• Concatenation operator
• Conditional operator
• Replication operator
• Arithmetic Operators: • Logical Operators:
• + unary (sign) plus • ! logical negation
• – unary (sign) minus • && logical AND
• + binary plus (add) • || logical OR
• – binary minus (subtract)
• * multiply
• / divide
• % modulus
• ** exponentiation • The value 0 is treated as logical FALSE while any non-
zero value is treated as TRUE.
• Logical operators return either 0 (FALSE) or 1 (TRUE).
• Relational Operators: • Bitwise Operators:
• != not equal Examples: • ~ bitwise NOT Examples:
• (a != b) • wire a, b, c, d, f1, f2, f3, f4;
• == equal • & bitwise AND • assign f1 = ~a | b;
• ((a + b) == (c – d))
• >= greater or equal • ((a > b) && (c < d))
• | bitwise OR • assign f2 = (a & b) | (b & c) | (c & a)
• <= less or equal • (count <= 0) • ^ bitwise exclusive-OR • assign f3 = a ^ b ^ c;
• assign f4 = (a & ~b) | (b & c & ~d);
• > greater • ~^ bitwise exclusive-NOR
• < less
• Relational operators operate on numbers, and • Bitwise operators operate on bits, and return a value that
return a Boolean value (true or false). is also a bit.

• Reduction Operators: Examples: Example:


• & bitwise AND • wire [3:0] a, b, c; wire f1, f2, f3; assign f1 = &a;
• | bitwise OR • assign a = 4’b0111;
• ~& bitwise NAND
• assign b = 4’b1100; 1 0 1 0
• assign c = 4’b0100;
• ~| bitwise NOR • assign f1 = ^a; // gives a 1
• ^ bitwise exclusive-OR • assign f2 = &(a ^ b); // gives a 0 after bitwise of a, b
• assign f3 = ^a & ~^b; // gives a 1
• ~^ bitwise exclusive-NOR
• Reduction operators accepts a single word operand and produce a single bit as output.
• Operates on all the bits within the word. f1 = 0
msb lsb
Examples:
• wire [3:0] data, target; 1 0 1 1 Original date
• Shift Operators: Will append 0 • assign target = data >> 1;
• >> shift right as new value • assign target = data << 1;
- Will append • assign target = data >>> 1;
• << shift left MSB 0 1 0 1 Right shift
Data >> 1
• >>> arithmetic shift right • wire a, b, c;
• wire [7:0] x, y, z;
• Conditional Operator: • assign a = (b > c) ? b : c;
• cond_expr ? true_expr : false_expr; • assign z = (x == y) ? x+2 : x-2; 1 0 1 0 Left shift
Data << 1
• Concatenation Operator: • a = 2’b01; b = 2’b10;
• {…, …, …} • assign f = {a, b}; // f = 4’b0110 Arithmetic
• assign f = {a, 3’b101, b}; // f = 7’b0110110 1 1 0 1 Right shift
• Replication Operator: • assign f = {a[1], b[0], a}; // f = 4’b0001 Data >>> 1
• {n{m}}
• assign f = {2’b10, 3{2’b01}, b};
// f = 8’b1001010110
Msb – most significant bit
Lsb – least significant bit

Arithmetic right shift


1010 -> 1101
0101 -> 0010
• Equality operator
• Equality operators compare operands bit by bit.

Reg [3:0]a,b;
Reg y1,y2,y3,y4,y5,y6,y7;

Initial begin
a = 4'b0010;
b = 4'b0011;
y1 = (a == b); //logical equality will return 0
y2 = (a != b); // logical inequality will return 1
#10; a = 4'b101x;
b = 4'b1010;
y3 = (a === b); // case equality will return 0
y4 = (a !== b); // case inequality will return 1
y5 = (a == b); // logical equality will return x
y6 = (a != b); //logical inequality will return x
#10;
a = 4'b101x;
b = 4'b101x;
y7 = (a === b); //case equality will return 1
end
Operator precedence
• Operators on same line have the same precedence.
• All operators associate left to right in an + – ! ~ (unary)
expression, except ?:
**
• Parentheses can be used to change the precedence */%
• The presence of a ‘z’ or ‘x’ in a reg or wire being << >> >>>
used in an arithmetic expression results in the < <= > >=
whole expression being unknown (‘x’).
== != === !==
• The logical operators (!, &&, | |) all evaluate to a 1- & ~&
bit result (0, 1 or x).
^ ~^
• The relational operators (>, <, <=, >=, ~=, ==) also | ~|
evaluate to a 1-bit result (0 or 1).
&&
• Boolean false is equivalent to 1’b0. Boolean true is ||
equivalent to 1’b1.
?:
Verilog Processes
Processes

Continuous Procedural

Concurrent Procedural Blocking Non-Blocking


• Continuous assignment • Procedural assignment
• The “net” being assigned on the left-hand side • The “register” being assigned on the left-hand
(LHS). side (LHS).
• The expression on the right-hand side (RHS), • The expression on the right-hand side (RHS),
which may consist of both “net” and “register” which may consist of both “net” and “register”
type variables. type variables.
• Almost exclusively used to model combinational • Two kinds of procedural blocks are supported
circuits in Verilog:
• syntax- assign assignment_statement • The “initial” block
• Example: assign a = b + c; // continuous • Executed once at the beginning of simulation.
concurrent assignment • Used only in test benches; cannot be used in
synthesis.
Procedural assignment example: • The “always” block
• A continuous loop that never terminates
initial always @(posedge • Application: used to generate infinite
begin clk) signal(clock)
reset =1’b1; begin • The procedural block defines:
#100 reset=1’b0; if (reset) • A region of code containing sequential statements.
#10 din=1’b1; q<=1’b0; • The statements execute in the order they are
#10 din=1’b0; else written.
end q<=d;
end
Procedural assignments
Typical Procedural Block
Type of block is specified here: initial, always

The symbol signifies an event control (only for always block )

Specifies the event which flags off the execution of the block
(only for always block
Type of block @(sensitivity list)
The block can be assigned a name which can be
begin: name_of_block
referred(optional )
local variable declarations;
procedural assignment statements; All variables ect., local to the block are declared at the
end beginning of the block

The procedural statements form the body of the


All the activities within the block are enclosed block
within the begin end construct
• Non-blocking
• the value of D at time t will be assigned to the final output
Blocking Vs non- q3 at the time t+3 cycles
• Here the RHS expressions will be evaluated & assigned to

blocking assignments the LHS at the same time


• Always @ (posedge clk)
begin
• Blocking q1 <= D + 3 ; // st1 – d = 2 + 3 = 5 / q1 = 5
• the value of D at time t will be assigned to the final q2 <= q1; // st2 – ‘x’ / q2 = x
output q3 at the same time t q3 <= q2; // st3 – ‘x’ / q3 = x
• Always @ (posedge clk) end
begin initial begin
q1 = D + 3; // st1 – d = 5 -> 5 + 3 = 8 $monitor
q2 = q1; // st2 #1 d;
q3 = q2; // st3 $100 $finish;
end end
• y=data; -> at the start of the time • y<=data; -> assigned at the 3rd time
region – active region region – NBA region
• Circuit realisation will be 1 flip flop • Circuit realisation will be 3 flip flops (3 bit shift register)
D q3 D q1 q2 q3

clk D_FF clk D_FF clk D_FF clk D_FF


Blocking assignments
• Blocking assignments are executed in the order sequentially . Since they block the
execution of the next statement , till the current statement is executed
• Any delay attached is also got added to delay in execution of next statements
• Blocking assignment are represented with sign “=“.
Example :
module blocking;
reg [3:0] data =4’h5;
reg[3:0] y =4’h3;
initial
Begin
y = data;
$display(“1st block: data=%0h and y=%0h”,data,y);
end

initial begin
data=y;
Output:
$display(“2nd block: data=%0h and y=%0h”,data,y);
1st block: data=5 and y=5
end
2nd block: data =5 and y=5
endmodule
Non-blocking assignments
• Nonblocking assignments are executed in parallel. Since the execution of next statement is not
blocked due to execution of current statement. Represented with the sign “<=“.
• Nonblocking assignments in a block, the right hand sides are evaluated first. Subsequently the
specified assignments are scheduled.
• Nonblocking assignments are illegal to use in a continuous assignment statement or in a net
declaration
Example :
module blocking;
reg [3:0] data =4’h5;
reg[3:0] y =4’h3;
initial
begin
y<=data;
$display(“1st block: data=%0h and y=%0h”,data,y);
end

initial begin
data<=y; Output:
$display(“2nd block: data=%0h and y=%0h”,data,y); 1st block: data=3 and y=5
end 2nd block: data =3 and y=5
endmodule
Stratified event queue/event scheduler/time
regions
• Every change in value of a net or variable in the circuit being simulated is considered an event. Used in
the procedural blocks (always, initial).
• Events/regions can occur at different times. They are as follows
• Active
• Statements from the previous time slot
• Evaluation of
• Blocking assignments
• RHS of non blocking assignments
• Continuous assignment
• $display & $write
• Inactive
• #0 delay statements
• Non blocking/NBA
• Non-blocking statement LHS update
• Postponed
• $strobe & $monitor
• Statements to next time slot
• Example
always @ (enable, a, b)
begin
a = 0;
a <= 1;
$display(“display a = %d”, a); // output: display a = 0
end
a= 0
Active a <= 1 (rhs of non blocking)
$display
Inactive
always @ (enable, a, b) NBA a <= 1 (lhs update of the non blocking)

begin Postponed $monitor

a = 0;
a <= 1;
$monitor(“monitor a = %d”, a); // output: monitor a = 1
end
Delays in procedural assignments
Delays(inter, intra)
• Inter delay – the statement itself is executed after the delay expires
• Syntax:
out1 = a + b;
#10 out2 = c+ d;

• Intra delay – the RHS is captured first and assigned to LHS after the delay
expires
• Syntax:
out1 = a + b;
out2 = #10 c + d;
Delays in continuous concurrent assignments
• Inertial delay
in this modelling, the input pulses less than the delay are filtered, remaining
pulses are passed with mentioned delay
Example:
assign #10 out = in; // input pulse widths less than 10ns will be ignored
• Transport delay
it is like a wire delay, it propagates all input pulses with the delay specified.
Example:
always@(*) begin
out <= #10 in;
end
Testbench:

Example module test;


reg in;
wire out;

Verilog model: DUT dut_1(.in(in),.out(out));

module DUT (input in, initial begin


output reg out); in = 1'b1;
$monitor("time = %d in = %d out = %d ",$time,in,out);
forever begin
assign #10 out = in; //inertial delay
#1 in = 0;
#15 in = 1;
#1 in = 0;
always@(*) begin //transport delay #1 in = 0;
out <= #10 in; end
end end

endmodule initial begin


$dumpfile("test.vcd");
$dumpvars(0,test);
always@( * ) blocks are used to describe Combinational Logic,
#100 or$finish;
Logic Gates. Only = (blocking) assignments
should be used in an always@( * ) block. Never use <= (non-blocking)
end assignments in always@( * ) blocks.
Only use always@( * ) block when you want to infer an element(s) that changes its value as soon as one or
more of its inputs change. endmodule
Timing Control statements
• Wait
• Wait is level sensitive and blocks the below statement until the condition is true.
• Example
module waiting_ex (input [4:0] a, b, c, output out);
initial begin
a = 10;
b = 10;
wait(c == 5)
out = (a == b);
end
initial begin
c = 0;
#5 c = 3;
#20;
c = 5;
end
endmodule

• Output:
• The out = (a == b) will wait till c = 5, and it will be executed at time = 25 units;
• Event based timings
• Event based timing control statement(TCS) is based on the transitions in the
sensitivity list

• Example
module event_based_tcs (input clk, rst, d, output out);
initial begin
@(posedge clk);
rst = 1;
@(negedge clk);
rst = 0;
out = d;
end
endmodule
Types of coding in Procedural blocks(sequential,
parallel)

• Sequential
• Statements are executed one after the other
• Example
module ex (…);

Initial begin
#1 $display(“time = %0t”, $time);//st 1
#1 $display(“time = %0t”, $time);//st 2
#1 $display(“time = %0t”, $time);//st 3
end
….
endmodule
• Parallel
• All statements are executed at the same time – t = 0ns
• Example
module ex (…);

initial
fork
#1 $display(“time = %0t”, $time);//st 1
#1 $display(“time = %0t”, $time);//st 2
#1 $display(“time = %0t”, $time);//st 3
join
….
endmodule
Branching Construct
If else Statement:
• The if construct checks a specific condition and decides execution
based on the result.
Assignment 1
always @(. . . . );
begin
assignment 1;
if (condition) Yes No
begin //Alternative 1 condition
assignment 2;
end
else Assignment 2 Assignment 3
begin // Alternative 2
assignment 3;
end
assignment 4;
Assignment 4
end
If condition module test; //assignment
module test; module test;
reg [3:0] a, b, c, out;

reg a, b, c, out;
initial reg [3:0] a, b, c, out;
begin
initial if (c == 0) begin
begin a = b + 5;
out = a;
If (c == 0) assign a = 1;
end
out = a; else begin
else b = a +10;
assign b = 10;
out = b; Out = b;
end
end
end initial
initial
begin
begin
initial a = 0; b = 1; c = 1; // out -> b -> 11
a = 0; b = 1; c = 1; // out -> b -> 1
begin #1 a = 0; b = 1; c = 0; // out -> a ->
#1 a = 0; b = 1; c = 0; // out -> a ->
a = 0; b = 1; c = 1; // out -> b -> 11 5
0
#1 a = 0; b = 1; c = 0; // out -> a -> 5
end
end
end
endmodule
endmodule endmodule
Case Statement:
• Multiway decision statement that tests whether an expression matches
one of a number of other expressions and branches accordingly.

Syntax :
reg [3:0] w, x, y, z; case (expression)
integer i; case_item_1 : statement_1;
always @( w or x or y or case_item_2 : statement_2;
i) case_item_3 : statement_3;
case(i) --------------
0: z=w; default : default_statement;
1:z=x; endcase
default :z=y;
endcase
Case Statement with don’t cares:
always @(a) always @(a) a=3’b10x matches the second
case(a) casex(a) case item for casex
3’b000 : z=3’b000; 3’b000 : z=3’b000;
3’b101 : z=3’b010; 3’b101 : z=3’b010;
default : z=3’b111; default : z=3’b111;
endcase endcase

a= 3’b10x does not match any


case items so the default
assignment is made
a=3’b001 matches the first case item for
casez
always @(a)
casez(a)
3’b00z : z=3’b000;
3’b101 : z=3’b010;
default : z=3’b111;
endcase
Full case :
• A “full case” statement has all possible case expression binary patterns
can be matched to a case item or to a case default.
module full_case (input [2:0] a_in, output reg [7:0] d_out);

always @*
begin
case(a_in)
3’b000 : d_out=8’b00000001;
3’b001 : d_out=8’b00000010;
3’b010 : d_out=8’b00000100;
3’b011 : d_out=8’b00001000;
default : d_out=8’b00000000;
endcase
end
endmodule
Parallel case :
• A “parallel case” statement is a case statement in which it is only
possible to match a case expression to one and only one case item.

module parallel_case (input [2:0] a_in, output reg [7:0] d_out);


always @*
begin
case(a_in)
3’b000 : d_out=8’b00000001;
3’b001 : d_out=8’b00000010;
endcase
end
endmodule
Overlapping case :
• If it is possible to fined a case expression that would match more than
one case item, the matching case item are called “overlapping” case
items and the case statement is not “parallel”

module parallel_case (input [2:0] a_in, output reg [7:0]


d_out);
always @*
begin
case(a_in)
3’b1?? : d_out =0;
3’b?1? : d_out =1;
3’b??1 : d_out=2;
endcase
end
endmodule
Looping constructs
for loop:
• Its execution is a three step process as follows:
reg [2:0]mem[7:0];
 Initialize a variable that controls the integer i;
number of loops executed. reg read_mem;
 Evaluates an expression if the result is
initial begin
zero, the loop exits, and if it is not zero, for(i=0; i<10; i=i+1)
the for loop executes its associated $display(“Data at
statement(s) and then perform step c. location”, i , “is”,
 Executes an assignment, normally mem[i]);
end
modifies the value of the loop control
variable, then repeats step b.
For loop example:
module test; module test;

int a, b, c, out; int a, b, c, out;

initial
initial
begin
begin
for (c = 0; c < 10; c++) begin
for (c = 0; c < 10; c++) a = b + c;
//out = a + b+ c; #1 out = a * 3;
#1 out = a + b+ c; end
end end

initial initial
begin begin
$monitor(“a = %0d, b = %0d, c = %0d, out = %0d”, $monitor(“a = %0d, b = %0d, c = %0d, out = %0d”, a, b,
a, b, c, out); c, out);
a = 0; b = 1; c = 1;
a = 0; b = 1; c = 1;
end
end
endmodule
endmodule
While loop:

• Executes a statement until an expression


becomes false.
• If the expression starts out false, the
statement does not executes at all.
Example counts the number of logic 1 value in rega
begin
reg [7:0] tempreg;
count = 0; While tempreg is not all 0
temreg = rega;
while (tempreg) begin
If 0th bit is 1, count is incremented
if(tempreg[0])
count = count+1;
tempreg =tempreg >>1; Tempreg is shifted right by one place
end
end
repeat loop forever loop

• Executes a statement, fixed number • Continuously executed a statement


of times • Syntax : forever statement
• If the expression evaluates to
unknown or high impedance, it is
treated as zero, and no statement is
executed.
• Syntax: repeat (expression) reg clock;
initial begin
statement
clock =1’b0;
Clock toggles every 5 time units forever #5clock = ~clock;
end
Repeats 5 +ve edges of clock
initial begin
repeat(5)
Note: @(posedge clock);
 For loop is a synthesizable construct. y= a|b;
 While, forever, repeat are non synthesizable end
construct
Task and Function
• Task • Function
• Tasks are used in all programming languages, • A Verilog HDL function is the same as a task, with
generally known as procedures or very little differences, like function cannot drive
subroutines. The lines of code are enclosed in more than one output. The lines of code are
task....endtask enclosed in function….endfunction
• tasks can include timing delays, like posedge, • functions cannot include timing delays, like
posedge, negedge, # delay, which means that
negedge, # delay and wait. functions should be executed in "zero" time delay.
• tasks can have any number of inputs and • functions can have any number of inputs but only
outputs. return one output.
• tasks can be used for modeling both • functions can be used for modeling combinational
combinational and sequential logic(clock logic.
dependency). • functions can call other functions, but can not call
• tasks can call another task or function. tasks.
• A task must be specifically called with a • Function can be used within an expression
statement, it cannot be used within an • Out = c + add_fun(in1, in2);
expression as a function can.
• add_task(out, in1, in2);
• Example
module adder (input [3:0] a, b, output
reg [4:0] task_out1, task_out2, function adder_fun (input [3:0] in1, in2);
fun_out); reg [4:0] temp_out;
temp_out = in1 + in2;
initial begin return temp_out;
a = 10; b = 12; endfunction
adder_task(task_out1, task_out2, a, b); endmodule
fun_out = adder_fun(a, b);
end

task adder_task (output [4:0] temp_out,


temp_out2, input [3:0] in1, in2);
temp_out = in1 + in2;
#10 temp_out2 = in1 – in2;
endtask
Compiler directives
• `define (macro) • `include
• It refers to substitution of a line/lines of a test • It will copy-past the content of the file
code that is being included.

Example: Example:

`define WIDTH 8 module testbench ();


`define DEPTH 128 `include “tb_variables.sv”
module ram (clk, rst, in, addr, out); ……
reg [(`WIDTH-1):0] mem [(`DEPTH-1):0]; endmodule tb_variables.sv
….
endmodule
• `ifdef • `ifndef
Example: Example:
`define present
module and_op(a, b, c); module and_op(a, b, c);
output a; output a;
input b, c; input b, c;
`ifdef present `ifndef present
a = b + c; a = b + c;
`else `else
a = b – c; // this will execute a = b – c;// this will execute
`endif `endif
endmodule endmodule
• `timescale unit/precision
#10 –> 10 * unit -> 10 * 1ns
Delay will be 10ns
`timescale 1ns/1ps
module dut (….); #1.58673 –> precision = 1ps = 0.001ns
Delay will round off to one decimal value
…..
Delay will be = 1.587 * 1ns = 1.587ns
#10 assign a = b;
#1.58673 assign b = c; `define delay 10
….. Module

endmodule #(`delay/3)

endmodule
System tasks
• $time – returns the current simulation time in integer value
• $realtime – returns the current simulation time in floating value
• $strobe - displays the last updated value in the current time-slot in which it is called
• $display - displays the value at that instant of time
• $monitor - continuously monitors the changes in the arguments/variables present inside the monitor
• Example
Module sys_fun;
reg [1:0]s;
initial begin
$strobe (“Strobe - Value of s=%d at time =%t", s, $time); //Strobe - Value of s = 2 at time =0
$display (“Display - Value of s=%d at time =%t", s, $time);//Display - Value of s = x at time =0
$write(“Write - Value of s=%d at time = %t \n", s, $time); //Same as $display but needs a ‘\n’ at the end
$monitor (“monitor - Value of s =%d at time =%t", s, $time);//monitor - Value of s = 2 at time =0
s = 3;
s=2;
#10;
S = 0; //monitor - value of s = 0 at time = 10
end
endmodule
• $finish – it will terminate the simulation and come out of the tool.
• $stop – it will suspend the simulation, but it will not come out of the tool. Tool will run in background.
• $random – returns the 32 bit signed random value
• $urandom – returns the 32 bit unsigned random value
• Example
module
reg [3:0] y;
initial begin
#2100 $finish;
end
initial begin
#15 y = $random; // prints random value from [-7:+7]
#15 y = $urandom; // prints random value from [0:15] – 4’b0000 – 4’b1111
#15 y = {$random}; // prints random value from [0:15]
#15 y = {$random}%10; // print random value from [0:9]
#15 y = $random % 10; // print random value from [-9:9]
end
endmodule
• File Read
File operations(write, read) data.txt
10001000
11111111
xxzzxx111
01010101
• File Write @3
10101010
10111111
module (......) x1x10000
.....
integer FILE_WRITE;
initial begin module (......)
a = 10; b = 5; .....
#1 a = 10; b = 5;
reg [7:0]ram[7:0];
#1 a = 10; b = 5;
end
initial begin
initial begin $readmemb("data.txt",ram);
FILE_WRITE = $fopen("file.txt"); end
$fmonitor(FILE_WRITE," a = %d, b = %d",a,b);
$fclose(FILE_WRITE); endmodule
end • The date in the data.txt is pushed to 8x8 RAM/array
endmodule
Command line arguments
• These will check switch in the run command and execute the logic for the respective one.
Mainly used to simplify the testbench execution for multiple runs.
• $test$plusargs
• It will check if that switch is present or not
• Example Run command:
module test (…) Run … +switch_name
…..
if ($test$plusargs(“switch_name”)) Output:
$display(“switch is present”);
Switch is present
….
endmodule

• $value$plusargs
• It will take the value assigned to the switch
• Example Run command:
module test (…)
Run … +switch_name=10
…..
reg [3:0] value;
if ($value$plusargs(“switch_name=%d”, value)) Output:
$display(“switch value is = %0d”, value); Switch value is = 10
….
endmodule
Stratified event queue/event scheduler/time regions
• Every change in value of a net or variable in the circuit being simulated is considered an event. Used in the
procedural blocks (always, initial).
• Events/regions can occur at different times. They are as follows
• Active
• Statements from the previous time slot
• Evaluation of
• Blocking assignments (s = 10;)
• RHS of non blocking assignments
(s <= a + b;)
• Continuous assignment (assign s = 10;)
• $display & $write
• Inactive
• #0 delay statements Inactive region ex:
• #0 a = 1;
Fork
• Non blocking/NBA
A = 0; // output – X
• Non-blocking statement LHS update
• (s <= a + b;)
// #0 A = 0;// output - 0
• Postponed A = 1;
• $strobe & $monitor Join
• Statements to next time slot
• Example
always @ (enable, a, b)
begin
a = 0;
a <= 1;
$display(“display a = %d”, a); // output: display a = 0
end

always @ (enable, a, b)
begin
a = 0; // active region
a <= 1; // lhs update in NBA region
$monitor(“monitor a = %d”, a); // output: monitor a = 1
end
• `timescale 1ns/1ns

Ways to generate 10ns clock module tb;


reg clk;
always
begin
#5 clk = 0;
• `timescale 1ns/1ns • `timescale 1ns/1ns
#5 clk = 1;
module tb; module tb;
end
reg clk; reg clk;
endmodule
initial initial
begin begin
clk = 1; clk = 1;
#100 $finish; #100 $finish; • `timescale 1ns/1ns
end end module tb;
parameter cycle = 10;
always
reg clk = 1;
begin forever
always
#5 clk = ~clk; begin
begin
end #5 clk = ~clk;
#(cycle/2) clk = 0;
end #(cycle/2) clk = 1;
endmodule endmodule end
endmodule
References

• For reference - https://www.chipverify.com/verilog/verilog-tutorial


• For interview - https://www.vlsi4freshers.com/search/label/Verilog
Thank you

You might also like