Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views77 pages

Introduction To Verilog

Uploaded by

Manish Mahato
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)
17 views77 pages

Introduction To Verilog

Uploaded by

Manish Mahato
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/ 77

Introduction to Verilog

Contents :
• Introduction to Verilog
• Basic Naming Convention
• Verilog operators.
• Data Types.
• Assignment statements.
• Control statements.
• Behavioral Modeling in Verilog HDL.
• Combinational logic design using Verilog.
Introduction to Verilog
• Verilog is Hardware description language(HDL).
• It describes digital system like MP, FF, Registers, Memory etc.
• HDL descriptions provide technology-independent documentation of
a design and its functionality.
• Design style :
 Bottom-up -- Each design is performed at gate level
 Top Down -- Desired style of all designers- early testing is done.
Abstraction level of Verilog

1. Behavioral Level.
2. Register-Transfer Level.
3. Gate Level.
Behavioral Level

 Describes systems by concurrent algorithms.


 Each algorithm itself is sequential.
 Function, Tasks and always block are the main elements.
Register-Transfer Level

 It specifies characteristics of a circuit by operations and


transfer of data between registers.
 An explicit clock is used.
 RTL designs contain exact timing possibility.
 Operations are scheduled to occur at certain times
 Modern definition of RTL code is :
“Any code that is synthesizable is called RTL code”
Gate Level
 A system is described by logical links and their timing
properties.
 All signals are discrete signals and have definite logical
values(‘0’, ’1’, ‘X’, ‘Z’).
 The usable operators are predefined logic primitives
(AND, OR, NOT etc. gates).
 Therefore Gate-Level is not used for logical designs.
 Gate level code is generated by Synthesis tool and this
netlist is used for gate level simulation and backend.
HDL Compiler and the Design Process
 HDL Compiler translates Verilog language hardware descriptions to the Synopsys
internal design format.
 Design Compiler can then optimize the design and map it to a specific ASIC
technology library.
Design Methodology
Design Flow

1. Write a design description in the Verilog language.

2. Provide Verilog-language test drivers for the Verilog HDL simulator.

3. Simulate the design by using a Verilog HDL simulator. Verify that the
description is correct.

4. HDL Compiler performs architectural optimizations and then


creates an internal representation of the design.

5. Synopsys Design Compiler to produce an optimized gate-level


description in the target ASIC library.
Design Flow
6. Use Synopsys Design Compiler to output a Verilog gate-level
description. This netlist-style description uses ASIC components as
the leaf-level cells of the design. The gate-level description has the
same port and module definitions as the original high-level Verilog
description.

7. Gate-level Verilog description from step 6 is pass through the Verilog


HDL simulator. use the original Verilog simulation test drivers from
step 2, because module and port definitions are preserved through the
translation and optimization processes.

8. Compare the output of the gate-level simulation (step 7) with the


output of the original Verilog description simulation (step 3) to verify
that the implementation is correct.
Why Verilog?
• Why use an HDL?
– Describe complex designs (millions of gates)
– Input to synthesis tools (synthesizable subset)
– Design exploration with simulation
• Why not use a general purpose language
– Support for structure and instantiation
– Support for describing bit-level behavior
– Support for timing
– Support for concurrency
• Verilog vs. VHDL
– Verilog is relatively simple and close to C
– VHDL is complex and close to Ada
– Verilog has 60% of the world digital design market (larger share in US)
Modern Project Methodology

Always
inst1 Synthesis
inst2
inst3

Place and
Route
clb 1
clb 2
Logic Values
• 0: zero, logic low, false, ground

• 1: one, logic high, power

• X: unknown

• Z: high impedance, unconnected, tri-state


VERILOG HDL

• Basic Unit – A module


• Module
– Describes the functionality of the design.
– States the input and output ports.

• Example: A Computer
– Functionality: Perform user defined computations.
– I/O Ports: Keyboard, Mouse, Monitor, Printer.
Modules
• The principal design entity

Module Name & Definitions


Port List Ports, Wire, Reg,
Parameter

Module Statements & Module


Constructs Instantiations
Module
• General definition  Example

module module_name ( port_list ); module HalfAdder (A, B, Sum Carry);


port declarations; input A, B;
… output Sum, Carry;
variable declaration; assign Sum = A ^ B;
… //^ denotes XOR
description of behavior assign Carry = A & B;
endmodule // & denotes AND
endmodule
Basic Naming Convention

Lexical Conventions in Verilog


Type of lexical tokens :
•Operators
•White space ( page 29).
•Comment.
•Identifier (page 30).
•Number .
•String.
•Keyword.
Basic Naming Convention

 Operators:

Arithmetic Operators +, -, *, /, %
Relational Operators <, <=, >, >=
Equality Operators ==, !=, ===, !==
Logical Operators !, &&, ||
Bit-Wise Operators ~, &, |, ^, ~^
Unary Reduction &, ~&, |, ~|, ^, ~^
Shift Operators >>, <<
Conditional Operators ?:
Concatenations {}
Operators
{} concatenation ~ bit-wise NOT
+ - * / arithmetic & bit-wise AND
% modulus | bit-wise OR
> >= < <= relational ^ bit-wise XOR
^~ ~^ bit-wise XNOR
! logical NOT
& reduction AND
&& logical AND
| reduction OR
|| logical OR ~& reduction NAND
== logical equality ~| reduction NOR
!= logical inequality ^ reduction XOR
?: conditional ~^ ^~ reduction XNOR
<< shift left
>> shift right
Operator Precedence
[ ] bit-select or part-select >, >=, <, <= relational
( ) parentheses ==, != logical equality
!, ~ logical and bit-wise & bit-wise AND
negation ^, ^~, ~^
&, |, ~&, ~|, ^, ~^, ^~ bit-wise XOR and XNOR
reduction operators | bit-wise OR
+, - unary arithmetic && logical AND
{ } concatenation || logical OR
*, /, % arithmetic ?: conditional
+, - arithmetic
<<, >> shift
Lexical Conventions
 Comments
// Single line comment
/* Another single line comment */
/* Begins multi-line (block) comment
All text within is ignored
Line below ends multi-line comment
*/
 Number
decimal, hex, octal, binary
unsized decimal form.
size base form.
include underlines, +,-
 String
" Enclose between quotes on a single line"
Lexical Conventions (cont.)
 Identifier
A ... Z
a ... z
0 ... 9
Underscore and dollar sign ‘$’

• limited to 1024 chars long.


• First char of identifier must not be a digit.
Verilog is case sensitive
Data Types
• Nets.
– Nets are physical connections between devices.
– Nets always reflect the logic value of the driving device.
– Many types of nets, but all we care about is wire.
• Registers & Parameters.
– Implicit storage – unless variable of this type is modified it
retains previously assigned value.
– Does not necessarily imply a hardware register.
– Register type is denoted by reg .
 A register holds its value until a new value is assigned to it.
 Registers are used extensively in behavior modeling and in applying
stimuli.
 Parameters are not variables, they are constants.
Variable Declaration
• Declaring a net
wire [<range>] <net_name> [<net_name>*];
Range is specified as [MSb:LSb]. Default is one bit wide

• Declaring a register
reg [<range>] <reg_name> [<reg_name>*];

• Declaring memory
reg [<range>] <memory_name> [<start_addr> : <end_addr>];

• Examples
reg r; // 1-bit reg variable
wire w1, w2; // 2 1-bit wire variable
reg [7:0] vreg; // 8-bit register
reg [7:0] memory [0:1023]; a 1 KB memory
Ports and Data Types
• Correct data types for ports

Module

Register/net net register/net net


input output

net

inout

net
Data types
• Net
– physical wire between devices
– the default data type.
– used in structural modeling and continuous assignment.
– types of nets
• wire, tri : default
Simpler than VHDL
• wor, trior : wire-ORed
• wand, triand : wire-ANDed Only Syntactical
Difference
• trireg : with capacitive storage
• tri1 : pull high
• tri0 ; pull low
• supply1 ; power
• supply0 ; ground
A Full-Adder
• module add (co, s, a, b, c)
input a, b ,c ;
output co, s ;
xor (n1, a, b) ;
xor (s, n1, c) ;
nand (n2, a, b) ; Simpler than VHDL
nand (n3,n1, c) ; Only Syntactical
nand (co, n3,n2) ; Difference

endmodule
Verilog Primitives
• Basic logic gates only
– and
– or
– not
– buf
– xor
– nand
– nor
– xnor
– bufif1, bufif0
– notif1, notif0
Primitive Pins Are Expandable
• One output and variable number of inputs

nand (y, in1, in2) ;

nand (y, in1, in2, in3) ;

nand (y, in1, in2, in3, in4) ;

• not and buf


– variable number of outputs but only one input
Continuous Assignment Statement
 It drives nets(wire data type).
 They represent structural connection.
 Used for modeling Tri-state buffer.
 Used for modeling combinational logic.
 They are outside the procedural blocks(always & initial)
 Continuous assign overrides any procedural assignment.
 left-hand side of assignment must be net data type.

Syntax :
assign(strength, strength) #(delay) net = expression;
Continuous Assignments
• Describe combinational logic
• Operands + operators
• Drive values to a net
– assign out = a&b ; // and gate
– assign eq = (a==b) ; // comparator
– wire #10 inv = ~in ; // inverter with delay
– wire [7:0] c = a+b ; // 8-bit adder
• Avoid logic loops
– assign a = b + a ;
– asynchronous design
Logical and Conditional Operators
• Logical, bit-wise and unary operators
a = 1011; b = 0010
logical bit-wise unary
a || b = 1 a | b = 1011 |a = 1
a && b = 1 a &b = 0010 &a = 0

• Conditional operator
assign z = ({s1,s0} == 2'b00) ? IA :
({s1,s0} == 2'b01) ? IB :
({s1,s0} == 2'b10) ? IC :
({s1,s0} == 2'b11) ? ID :
1'bx ;

assign s = (op == ADD) ? a+b : a-b ;


Assignments
Assignment : drive values into nets and registers.
Continuous Assignments – Any changes in the RHS
of continuous assignment are evaluated and the LHS is
update.
Example : (1) assign out = ~in;
(2) assign reg_out; = reg_in << shift
Control Statements/ Conditional statement
• Syntax: if Statement Example:
if (condition) if (Clk)
True procedural_statement; Q = 0;

• Syntax: if –else Statement Example:


if (condition) if (Clk)
True procedural_statement Q = 0;
else
else
Q = D;
False procedural_statement;
Control Statements/ Conditional statement
• Syntax: nested if –else Statement
if (condition)
Example:
True procedural_statement1 if (Clk)
else if (condition) Q = 0;
True procedural_statement2; else if
----------------------- Q = D;
else
…………………..
Q = 1;
else
False procedural statement;
Example : If and If-else
Case Statement
 Supports single or multiple statements
 Group multiple statements using begin and end keyword

• Syntax :
Case (<case_expression>)
<case1> : <Procedural statement 1>
<case2> : < Procedural statement 2>
………..
<casen> : < Procedural statement n>
Default : <Procedural statement>
endcase
Case Statement
• Case Statement
• Example 1:
case (X)
2’b00: Y = A +
B;
2’b01: Y = A –
B;
2’b10: Y = A / B;
endcase
casex and casez Statement
• Variants of case Statements:
– casez and casex

• casez – z is considered as a don’t care


• casex – both x and z are considered as don’t cares
• Example:
casez (X)
2’b1z: A = B + C;
2’b11: A = B / C;
endcase
Example: casez
Example: casex
Looping statements

There are four types of looping statements which


provide a means of controlling the execution of a
statement zero, one, or more times.
Looping statements

 forever
repeat
while
for

Forever Loop :
 Executes Continuously, loop never ends.
 Normally it is used in initial blocks.
 Careful in using forever loop, if no timing construct
is present then simulation could hang.
 syntax : forever <statement>
Looping statements
repeat statement :
 Executes statement fixed number of times
syntax : repeat (<number>) <statement>

While loop statement :


 Executes as long as an evaluates as true.
syntax : while (condition)

For loop statement:


 Same as used in other programming languages.
 syntax : (<initial assg>;<exp>;<step assg>) <statement>
Behavioral modeling in Verilog HDL.
The basic essence of a behavioral model is the process.
Implemented as a sequential state machine.
 As an asynchronous clearing of a register, or
 As a combinational circuit.

 Procedural Blocks (Construct) in Verilog : Two Types.


o An Initial block
 Executes exactly only once during simulation.
 Starts at simulation time 0.
o An always block
 Starts at simulation time 0.
 Executes continuously during simulation.

The basic Verilog statement for describing a process is the always


construct.
Example : always block
Example : initial block

Module initial_example();
Reg clk,reset,enable,data;
initial begin
clk = 0;
Reset= 0;
Enable = 0;
Data = 0;
end
endmodule
Procedural Assignment Statements.
 Procedural assignment statement assign values to reg, integer, real or
time variables.
 It can not assign values to nets(wire data types).
 registers(reg data type) can be assigned the value of net(wire),
constant, another register or specific value.
Syntax:
variable_lvalue = [timing_control] expression
variable_lvalue <= [timing_control] expression
[timing_control] variable_lvalue = expression
[timing_control] variable_lvalue <= expression

Two types The bit widths


 blocking (uses “=” )  Keeping the least significant bits
 nonblocking (uses “<=”)  Zero-extended in the most significant bits
Blocking Assignments
 Are executed in the order they are coded. Hence they are
sequential.
Since they block the execution of next statement , till the
current statement is executed , they are called blocking
assignments.
// blocking assignments
 uses “=” symbol /Operator initial begin
x = #5 1'b0; // at time 5
Example : y = #3 1'b1; // at time 8
z = #6 1'b0; // at time 14
end
Blocking procedural assignment.
Non Blocking Assignments
 They are executed in parallel.
 Since execution of next statement is not blocked due to the
execution of current statement .
 Therefore they are called as non-blocking assignment.
 Uses “<=” symbol/Operator
Example: reg x, y, z;
// nonblocking assignments
initial begin
x <= #5 1'b0; // at time 5
y <= #3 1'b1; // at time 3
z <= #6 1'b0; // at time 6
end
Example :Bad procedural Example :Good procedural
assignment assignment
Procedural Assignment Groups.

 If procedural block contains more than one statement, then


those statements are enclosed within….
 Sequential begin-end block
 Parallel fork-join block
 when using begin-end we can give name to that group
called as named blocks.
All statements are executed All statements are executed
sequentially. Parallel.
Sequential Statement Groups:

Parallel Statement Groups:


Restrictions on Data Types
• Data Flow and Structural Modeling
– Can use only wire data type
– Cannot use reg data type

• Behavioral Modeling
– Can use only reg data type (within initial and
always constructs)
– Cannot use wire data type
Compiler Directives
• `define – (Similar to #define in C) used to define global
parameter
• Example:
`define BUS_WIDTH 16
reg [ `BUS_WIDTH - 1 : 0 ] System_Bus;

• `undef – Removes the previously defined directive


• Example:
`define BUS_WIDTH 16

reg [ `BUS_WIDTH - 1 : 0 ] System_Bus;

`undef BUS_WIDTH
Compiler Directives (cont.)

• `include – used to include another file


• Example
`include “./fulladder.v”
System Tasks
• Display tasks
– $display : Displays the entire list at the time when
statement is encountered
– $monitor : Whenever there is a change in any argument,
displays the entire list at end of time step

• Simulation Control Task


– $finish : makes the simulator to exit
– $stop : suspends the simulation

• Time
– $time: gives the simulation
Timing Control
• Delay Timing Control.
• Event Timing control.

Delay timing control


Regular delay control
Intra assignment delay control
Timing Control

Regular delay control


Defers (postponed) the execution of the entire
statement.

reg x, y;
integer count;
#25 y <= ~x; // at time 25
#15 count <= count + 1; // at time 40
Timing Control

Intra-assignment delay control


Defers the assignment to the left-hand-side variable.

y= #25 ~x; // assign to y at time 25


count = #15 count + 1; // assign to count at time 40

y <= #25 ~x; // assign to y at time 25


count <= #15 count + 1; // assign to count at time 15
Timing Control
Event Timing Control
Edge-triggered event control
 Named event control
 Event or control
Level-sensitive event control
Edge-triggered event control
@(posedge clock)
 @(negedge clock)
always @(posedge clock) begin
reg1 <= #25 in_1;
reg2 <= @(negedge clock) in_2 ^ in_3;
reg3 <= in_1;
end
Timing Control
Named Event Control
A named event

event received_data; // declare


always @(posedge clock)
if (last_byte) -> received_data; // trigger
always @(received_data) // recognize
begin ... end
Timing Control
Event or Control
Event or control
 or
,
 * or (*) means any signals.

always @(posedge clock or negedge reset_n)


if (!reset_n) q <= 1`b0;
else q <= d;
Timing Control
Level-Sensitive Event Control
 Level sensitive event control.

always
wait (count_enable) count = count –1 ;
always
wait (count_enable) #10 count = count –1 ;
Combinational Logic Design using Verilog HDL.

 To model comb. Logic using procedure block must be


sensitive to any change on input.

Important rule to be followed while modeling


combinational logic.

If you use conditional checking using “if” then you need
to mention else part.
Missing else part results in LATCH.
if else is not typed then all the variables of comb. Block
must be initialize with zero as soon as it enters in.
Structural Description of a Half and Full Adder

Half Adder

Full Adder
Combinational Logic Design using Verilog HDL.

 1-Bit Adder Module adder(a,b,sum,carry);


Input a,b;
Output sum, carry;
reg sum, carry;
Always @(a or b)
begin
{carry,sum}= a+ b;
end

endmodule
Tri-State buffer (uses Cont. assignment statement)
Module tri_buff();
reg data_in, enable;
wire Bout;
assign Bout =(enable) ? data_in:1’bZ;  Cont. assignment statement

//Test Bench
initial begin
$montor(“Enable=%b, D = %b, BOUT=%B”, enable,data_in,Bout)
#1 enable =0;
#1 data_in =1;
#1 enable =1;
#1 data_in =0;
#1 enable =0;
#1 $finish;
end
endmodule
Tri-State buffer (uses Cont. assignment statement with delay)
Module tri_buff();
reg data_in, enable;
wire Bout;
assign #(1:2:3) Bout =(enable) ? data_in:1’bZ;  Cont. assignment
statement
//Test bench
initial begin
$montor(“Enable=%b, D = %b, BOUT=%B”, enable,data_in,Bout)
#10 enable =0;
#10 data_in =1;
#10 enable =1; Propagation Delay: only one delay for
#10 data_in =0; all transaction may be specified.
#10 enable =0;  A Min:typical:Max dalay range may be
#10 $finish; specified.
end
endmodule
4-Bit Adder (Beh. Modeling)
Module adder(a,b,sum,carry);
input [3:0] a, b;
output[3:0] sum;
output carry;
reg [3:0] sum;
reg carry;

always@(a or b)
begin
{carry,sum}=a+b;
end
endmodule;
Sequential Logic Design using Verilog HDL.

To model sequential Logic using procedure block must


be sensitive to positive edge or negative edge of the clock.

 To model asy. reset procedure block must be sensitive to


both clock and reset.

 All the assignment to sequential logic should be made


through non-blocking assignment.

Important : Clock signal should not be made as enable


input. Its fine for simulation but this is not right for
synthesis.
Ex:D flip flop with asyn reset(clear) and async preset.
Ex:D flip flop with syn reset(clear) and sync preset.

Module dff_syn();
reg clk, reset, preset,d;
reg q;

always@(posedge clk)
If (reset)
begin
q<=0;
end else if(preset) begin
q<=1;
end else begin
q<=d;
end
Procedure block concurrency & Race Condition.

 If we have multiple always block inside one module then all


blocks(always and initial blocks ) starts with execution at time
0.
 It will continue to execute concurrently.
This sometimes leads to Race condition if coding is not
done properly.
Module race_condition();
reg b;
Initial begin
b=0;
end
initial begin
b=1;
endmodule
4-bit Unsigned Up Counter with Asynchronous Clear

module counter (C, CLR, Q);


input C, CLR;
output [3:0] Q;
reg [3:0] tmp;
always @(posedge C or posedge CLR)
begin if (CLR)
tmp = 4'b0000;
else
tmp = tmp + 1'b1;
end
assign Q = tmp;
endmodule
4-bit Unsigned down Counter with synchronous Set

module counter (C, S, Q); input C, S;


output [3:0] Q;
reg [3:0] tmp;
always @(posedge C)
begin
if (S)
tmp = 4'b1111;
else
tmp = tmp - 1'b1;
end
assign Q = tmp;
endmodule
BCD Counter using Behavior Modeling Style
module BCD_Counter ( clk ,reset ,dout );
output [3:0] dout ;
reg [3:0] dout ;
input clk ;
wire clk ;
input reset ;
wire reset ;
initial dout = 0 ;
always @ (posedge (clk)) begin
if (reset)
dout <= 0;
else if (dout<9) begin
dout <= dout + 1;
end else if (dout==9) begin
dout <= 0;
end
end
end module;

You might also like