0% found this document useful (0 votes)
21 views

Chapter-3 verilogHDLUPD

The document discusses Verilog HDL and provides examples of how to model digital systems in Verilog at different levels of abstraction. It covers the basics of Verilog, including why it is used, its history, basic modeling concepts, and examples of gate-level, data flow, behavioral, and structural modeling in Verilog.

Uploaded by

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

Chapter-3 verilogHDLUPD

The document discusses Verilog HDL and provides examples of how to model digital systems in Verilog at different levels of abstraction. It covers the basics of Verilog, including why it is used, its history, basic modeling concepts, and examples of gate-level, data flow, behavioral, and structural modeling in Verilog.

Uploaded by

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

Chapter-3

INTRODUCTION TO VERILOG HDL


FPGA DESIGN FLOW USING VERILOG HDL
Hardware Description Languages

 In the beginning HDLs were developed as a ‘standard way’ of drawing circuit


schematics.
 Modeled the interface of circuits, described how they were connected
 Allowed connections between these modules
 Supported some common logic functions
 AND OR NOT XOR
 Multiplexers
History of HDLs

CS 150 - Fall 2005 - Lecture #4: Verilog - 3


 ISP (circa 1977) - research project at CMU
 Simulation, but no synthesis
 Abel (circa 1983) - developed by Data-I/O
 Targeted to programmable logic devices
 Not good for much more than state machines
 Verilog (circa 1985) - developed by Gateway (now Cadence)
 Similar to Pascal and C
 Delays is only interaction with simulator
 Fairly efficient and easy to write
 IEEE standard
 VHDL (circa 1987) - DoD sponsored standard
 Similar to Ada (emphasis on re-use and maintainability)
 Simulation semantics visible
 Very general but verbose
 IEEE standard
Convenient Way of Drawing Schematics
Convenient Way of Drawing Schematics

 It is standard
 Everybody will interpret the schematic the same way
 It is not proprietary
 HDLs are not tool specific
 It is machine readable
 It is easier for computers to understand the circuit
 Only later on additional benefits were discovered
 Simulation and Synthesis
Two Hardware Description Languages

 Verilog
 developed in 1984 by Gateway Design Automation
 became an IEEE standard (1364) in 1995
 More popular in US
 VHDL (VHSIC Hardware Description Language)
 Developed in 1981 by the Department of Defense
 Became an IEEE standard (1076) in 1987
 More popular in Europe
 In this course we will use Verilog
Introduction and Basic Concept

Whatis Verilog?
Hardware Description Language(HDL)
Why use Verilog?
Because 60% of US companies use it.
Verilog 8

8/31/2007
EECS150 Lab Lecture #1
 What’s an HDL?
 Textual description of a circuit.
 Human and machine readable.
 Hierarchical.
 NOT A PROGRAM
 Describe what the circuit IS.
 Not what is DOES.
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)
Why Verilog?
Verilog HDL and Verilog-XL
 Verilog HDL
 Hardware design language that allows you to
design circuit.
 Verilog-XL
 High speed, event-driven simulator that reads
Verilog HDL and simulates the behavior of
hardware.
What is Verilog HDL? 12

 Verilog Hardware Description Language(HDL)?


 A high-level computer language can model, represent and simulate digital design
 Hardware concurrency
 Parallel Activity Flow
 Semantics for Signal Value and Time
 Design examples using Verilog HDL
 Intel Pentium, AMD K5, K6, Atheon, ARM7, etc
 Thousands of ASIC designs using Verilog HDL
What is VHDL? 13

 VHDL represents another high level language for digital system design.
 In this course we study Verilog HDL
 reason:
 used more often in electronic and computer industry
 programming style is very similar to C programming language
Basic Design Methodology
14
Requirements

RTL Model Simulate

Synthesize

Gate-level
Model Simulate Test Bench

ASIC or FPGA Place & Route

Timing
Model Simulate
Modeling Digital Systems
15
• Verilog HDL is for writing models of a system
• Reasons for modeling
– requirements specification
– documentation
– testing using simulation
– formal verification
– synthesis
• Goal
– most reliable design process, with minimum cost and
time
– avoid design errors!
Domains and Levels of Modeling
16

Structural Functional

high level of
abstraction

low level of
abstraction

“Y-chart” due to
Gajski & Kahn
Geometric
Domains and Levels of Modeling
17

Structural Functional
Algorithm
(behavioral)

Register-Transfer
Language

Boolean Equation

Differential Equation

“Y-chart” due to
Geometric Gajski & Kahn
Domains and Levels of Modeling
18

Structural Functional
Processor-Memory
Switch

Register-Transfer

Gate

Transistor

“Y-chart” due to
Gajski & Kahn
Geometric
Domains and Levels of Modeling
19

Structural Functional

Polygons

Sticks

Standard Cells

Floor Plan

Geometric “Y-chart” due to


Gajski & Kahn
Verilog HDL Models 20

 HDL model specifies the relationship between input signals and output signals
 HDL uses special constructs to describe hardware concurrency, parallel activity
flow, time delays and waveforms

Verilog code for a AND gate


module and_gate(y, x1, x2);
input x1, x2;
output y;
and(y, x1, x2);
endmodule
Verilog code modeling

 Gate level – logic circuit of the AND gate example


module AND-2(output Y, input A,B);
AND(Y,A,B);
endmodule;
 Data flow – Equations of the AND Gate
assign Y = A & B;
endmodule;
 Behavioral – AND gate truth table
equation from the truth table
Y = A.B say Y = A & B
Verilog Examples 22

module Add_half (sum, c_out, a, b);


output sum, c_out;
input a, b;
wire c_out_bar;
xor G1 (sum, a, b);
nand G2 (c_out_bar, a, b);
not G3 (c_out, c_out_bar);
endmodule

* the instance name of Verilog primitives is optional.


Verilog Example: A D Flip Flop 23

module Flip_Flop (q, data_in, clk, rst);


input data_in, clk, rst;
output q;
reg q;
always @ (posedge clk)
begin
if (rst = = 1) q = 0;
else q = data_in;
end
endmodule
Verilog Example: behavioral model 24

module adder_4_RTL (a, b, c_in, sum, c_out);


output [3:0] sum;
output c_out;
input [3:0] a, b;
input c_in;

assign {c_out, sum} = a + b + c_in;

endmodule
Verilog Example: Structural Models
25
• Structural models
– Are built from gate primitives and/or other modules
– They describe the circuit using logic gates — much as
you would see in an implementation of a circuit.
• Identify
– Gate instances, wire names, delay from a or b to f.

a module mux (f, a, b, sel);


output f;
f input a, b, sel;
b
and #5 g1 (f1, a, nsel),
sel g2 (f2, b, sel);
or #5 g3 (f, f1, f2);
not g4 (nsel, sel);
endmodule
Verilog Example: Gate-Level Models
26
• Need to model the gate’s:
– Function
– Delay
• Function
– Generally, HDLs have built-in gate-level primitives
• Verilog has NAND, NOR, AND, OR, XOR, XNOR,
BUF, NOT, and some others
– The gates operate on input values producing an output value
• typical Verilog gate instantiation is:

optional “many”
and #delay instance-name (out, in1, in2, in3, …);
How to build and test a module 27

Construct a “test bench” for your design


– Develop your hierarchical system within a module that has
input and output ports (called “design” here)
– Develop a separate module to generate tests for the module
(“test”)
– Connect these together within another module (“testbench”)
28
module testbench (); module design (a, b, c);
wire l, m, n; input a, b;
output c;
design d (l, m, n); …
test t (l, m);

initial begin
//monitor and display
module test (q, r);

output q, r;

initial begin
//drive the outputs with signals

Another view of this
29
• 3 chunks of verilog, one for each of:

TESTBENCH is the final piece of hardware which


connect DESIGN with TEST so the inputs generated
go to the thing you want to test...

Another piece of
hardware, called Your hardware
TEST, to generate called
interesting inputs DESIGN
Verilog Examples 30
Module testAdd generated inputs for module halfAdd and displayed
changes. Module halfAdd was the design
module testAdd(a, b, sum, cOut);
module tBench;
input sum, cOut;
wire su, co, a, b;
output a, b;
reg a, b;
halfAdd ad(su, co, a, b);
testAddtb(a, b, su, co);
initial begin
endmodule
$monitor ($time,,
“a=%b, b=%b, sum=%b, cOut=%b”,
a, b, sum, cOut);
module halfAdd (sum, cOut, a, b); a = 0; b = 0;
output sum, cOut; #10 b = 1;
input a, b; #10 a = 1;
#10 b = 0;
xor #2 (sum, a, b); #10 $finish;
and #2 (cOut, a, b); end
endmodule endmodule
The test module
31
• It’s the test generator
• $monitor module testAdd(a, b, sum, cOut);
input sum, cOut;
– prints its string when output a, b;
executed. reg a, b;
– after that, the string is initial begin
printed when one of the $monitor ($time,,
listed values changes. “a=%b, b=%b, sum=%b, cOut=%b”,
a, b, sum, cOut);
– only one monitor can be a = 0; b = 0;
active at any time #10 b = 1;
#10 a = 1;
– prints at end of current #10 b = 0;
simulation time #10 $finish;
end
endmodule
The test module (continued)
32
• Function of this tester
– at time zero, print values module testAdd(a, b, sum, cOut);
input sum, cOut;
and set a=b=0 output a, b;
– after 10 time units, set b=1 reg a, b;
– after another 10, set a=1 initial begin
– after another 10 set b=0 $monitor ($time,,
“a=%b, b=%b, sum=%b, cOut=%b”,
– then another 10 and finish a, b, sum, cOut);
a = 0; b = 0;
#10 b = 1;
#10 a = 1;
#10 b = 0;
#10 $finish;
end
endmodule
Other things you can do
33
• More than modeling hardware
– $monitor — give it a list of variables. When one of them changes, it prints the
information. Can only have one of these active at a time.
e.g. …
• $monitor ($time,,, “a=%b, b=%b, sum=%b, cOut=%b”,a, b, sum, cOut);

extra commas %b is binary (also,


print a spaces %h, %d and others)
• The above will print:
2 a=0, b=0, sum=0, cOut=0<return>

newline
automatically
– $display() — sort of like printf()
included
• $display (“Hello, world — %h”, hexvalue)

display contents of data item called


“hexvalue” using hex digits (0-9,A-F)
Structural vs Behavioral Models
34
• Structural model
– Just specifies primitive gates and wires
– i.e., the structure of a logical netlist
– You basically know how to do this now.

• Behavioral model
– More like a procedure in a programming language
– Still specify a module in Verilog with inputs and outputs...
– ...but inside the module you write code to tell what you want to have
happen, NOT what gates to connect to make it happen
– i.e., you specify the behavior you want, not the structure to do it

• Why use behavioral models


– For testbench modules to test structural designs
– For high-level specs to drive logic synthesis tools
Summary 35

 Model hardware at different levels of abstraction


 Mix different levels of abstraction in description and simulation
 Able to model hardware concurrency
 Support Hierarchical decomposition
 Availability of ASIC Foundry Support
Modern Project Methodology

Always Synthesis
inst1
inst2
inst3

n g
pi
ap
m

Place and
Route
clb 1
clb 2
Levels of design description

Algorithmic level
Level of description
Register Transfer Level
most suitable for
synthesis
Logic (gate) level

Circuit (transistor) level

Physical (layout) level


Register Transfer Level (RTL)
Design Description

Combinational
Logic
Combinational …
Logic

Registers
What is an FPGA?

Configurable
Logic

Block RAMs

Block RAMs
Blocks

I/O
Blocks

Block
RAMs
Hardware Description Languages
 The functionality of hardware
 concurrency
 timing controls
 The implementation of hardware
 structure
 net-list
Different Levels of Abstraction
 Algorithmic
 the function of the system
 RTL
 the data flow
 the control signals
 the storage element and clock
 Gate
 gate-level net-list
 Switch
 transistor-level net-list
Verilog for Digital System Design
 Structural description
net-list using primitive gates and switches
continuous assignment using Verilog operators
 RTL
functional description
timing controls and concurrency specification
procedural blocks (always and initial)
registers and latches
C + timing controls + concurrency
Behavioral vs Structural 43

05/31/2024
 Behavioral description describes functionality of design. It is independent of
implementation.
 There is a one-to-many mapping between a behavioral module and a structural
module.

 Structural description defines and decides on an implementation of a module.


 Here we map the design to actual cells/gates.
Behavioral vs. Structural (2) 44

05/31/2024
 Rule of thumb:
 Behavioral doesn’t have sub-components
 Structural has sub-components:
 Instantiated Modules
 Instantiated Gates
 Instantiated Primitives
 Most modules are mixed
 Obviously this is the most flexible
Behavioral vs. Structural 45

05/31/2024
Structural

Structural
Structural Behavioral
Behavioral

Behavioral Primitive
Hierarchical structure and Modules

 Represent the hierarchy of a design

 modules
 the basic building blocks
 ports
 the I/O pins in hardware
 input, output or inout
Event Driven Simulation
 Verilog is really a language for modeling event-driven systems
 Event : change in state

0 t t+1
Event ••• •••
queue

Events

 Simulation starts at t = 0
 Processing events generates new events
 When all events at time t have been processed simulation time advances to t+1
 Simulation stops when there are no more events in the queue
Modeling Structure: Modules

 The module is the basic building block in Verilog


 Modules can be interconnected to describe the structure of your digital system
 Modules start with keyword module and end with keyword endmodule

Module AND <port list> Module CPU <port list>

• •
• •
• •

endmodule endmodule

 Modules have ports for interconnection with other modules


Modeling Structure: Ports
 Module Ports
 Similar to pins on a chip
 Provide a way to communicate with outside world
 Ports can be input, output or inout

Module AND (i0, i1, o);


input i0, i1;
output o;
i0
o
i1

endmodule
Modeling Structure: Instances
 Module instances
 Verilog models consist of a hierarchy of module instances
 In C++ speak: modules are classes and instances are objects

AND3

i0

i1
o
i2

Module AND3 (i0, i1, i2, o);


input i0, i1, i2;
output 0;

wire temp;

AND a0 (.i0(i0), .i1(i1), .o(temp));


AND a1 (.i0(i2), .i1(temp), .o(0));
endmodule
Logic Values
 0: zero, logic low, false, ground

 1: one, logic high, power

 X: unknown

 Z: high impedance, unconnected, tri-state


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
 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
- int is also used
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
Structural Modeling
 Structural Verilog describes connections of modules (netlist)

 and a0(.i0(a), .i1(b), .o(out));

Modules: The principal design entity


Example
 4-bit adder
module add4 (s,c3,ci,a,b)
input [3:0] a,b ; // port declarations
input ci ;
output [3:0] s : // vector Simpler than VHDL
output c3 ; Only Syntactical Difference
wire [2:0] co ;
add a0 (co[0], s[0], a[0], b[0], ci) ;

add a1 (co[1], s[1], a[1], b[1], co[0]) ;

add a2 (co[2], s[2], a[2], b[2], co[1]) ;

add a3 (c3, s[3], a[3], b[3], co[2]) ;

endmodule c3 a3 a2 a1 a0 ci
Two Main Data Types

 Nets represent connections between things


 Do not hold their value
 Take their value from a driver such as a gate or other module
 Cannot be assigned in an initial or always block

 Regs represent data storage


 Behave exactly like memory in a computer
 Hold their value until explicitly assigned in an initial or always block
 Never connected to something
 Can be used to model latches, flip-flops, etc., but do not correspond exactly
 Shared variables with all their attendant problems
Data types
 Net
 physical wire between devices
 the default data type
 used in structural modeling and continuous assignment
 types of nets
 wire, tri : default
 wor, trior : wire-ORed
 wand, triand : wire-ANDed
 trireg : with capacitive storage
 tri1 : pull high
 tri0 ; pull low
 supply1 ; power
 supply0 ; ground
Nets and Registers

 Wires and registers can be bits, vectors, and arrays

wire a; // Simple wire


tri [15:0] dbus; // 16-bit tristate bus
tri #(5,4,8) b; // Wire with delay
reg [-1:4] vec; // Six-bit register
trireg (small) q; // Wire stores a small charge
integer imem[0:1023]; // Array of 1024 integers
reg [31:0] dcache[0:63]; // A 32-bit memory
Verilog Simulator
Circuit Description Testfixture

Verilog Simulator

Simulation Result
Sample Design
module fadder ( sum, cout, a, b , ci ); 1-bit full adder sum
// port declaration a
output sum, cout; b
ci
input a, b, ci;
reg sum, cout;
cout
// behavior description
always @( a or b or ci )
begin
sum = a ^ b ^ ci;
cout = ( a&b ) | ( b&ci ) | ( ci&a); Simpler than VHDL
end Only Syntactical Difference
endmodule
Basic Instructions
Reg and Parameters
 Reg
 variables used in RTL description
 a wire, a storage device or a temporary variable
 reg : unsigned integer variables of varying bit width
 integer : 32-bit signed integer
 real : signed floating-point
 time : 64-bit unsigned integer
 Parameters
 run-time constants
Special Language Tokens
 $<identifier>: System tasks and functions
 $time
 $stop
 $finish
 $monitor
 $ps_waves
 $gr_waves
 $gr_regs
 #<delay specification>
 used in
 gate instances and procedural statements
 unnecessary in RTL specification
Modeling Structures
 Net-list
 structural description for the top level
 Continuous assignments (combination circuits)
 data flow specification for simple combinational
 Verilog operators
 Procedural blocks (RTL)
 always and initial blocks
 allow timing control and concurrency
 C-like procedure statements
 primitives (=truth table, state transition table)
 function and task (»function and subroutine)
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) ;
nand (n3,n1, c) ;
nand (co, n3,n2) ;

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 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 ;


Operators

Arithmetic Operators +, -, *, /, %
Relational Operators <, <=, >, >=
Equality Operators ==, !=, ===, !==
Logical Operators !, &&, ||
Bit-Wise Operators ~, &, |, ^, ~^
Unary Reduction &, ~&, |, ~|, ^, ~^
Shift Operators >>, <<
Conditional Operators ?:
Concatenations {}
Operator Precedence
[ ] bit-select or >, >=, <, <=
part-select relational
( ) parentheses ==, != logical equality
!, ~ logical and bit-wise & bit-wise AND
negation
^, ^~, ~^
&, |, ~&, ~|, ^, ~^, ^~
reduction operators bit-wise XOR and
XNOR
+, - unary arithmetic
| bit-wise OR
{ } concatenation
&& logical AND
*, /, % arithmetic
|| logical OR
+, - arithmetic
?: conditional
Operators
{} concatenation ~ bit-wise NOT
+ - * / & bit-wise AND
arithmetic | bit-wise OR
^ bit-wise XOR
% modulus
^~ ~^ bit-wise XNOR
> >= < <=
& reduction AND
relational
| reduction OR
! logical NOT
~& reduction NAND
&& logical AND ~| reduction NOR
|| logical OR ^ reduction XOR
== logical equality ~^ ^~ reduction XNOR
!= logical inequality << shift left
?: conditional >> shift right
Simple Behavioral Model: the always block

CS 150 - Fall 2005 - Lecture #4: Verilog - 81


 always block
 Always waiting for a change to a trigger signal
 Then executes the body
module and_gate (out, in1, in2);
input in1, in2;
output out;
Not a real register!!
reg out; A Verilog register
Needed because of
always @(in1 or in2) begin assignment in always
block
out = in1 & in2;
end
endmodule
Specifies when block is executed
I.e., triggered by which signals
always Block

CS 150 - Fall 2005 - Lecture #4: Verilog - 82


 Procedure that describes the function of a circuit
 Can contain many statements including if, for, while, case
 Statements in the always block are executed sequentially
 (Continuous assignments <= are executed in parallel)
 Entire block is executed at once
 Final result describes the function of the circuit for current set of inputs
 intermediate assignments don’t matter, only the final result
 begin/end used to group statements
Numbers
Format : <size>’<base><value>
Example : 8’d16
8’h10
8’b00010000
8’o20
Keywords
Note : All keywords are defined in lower case
Examples :
module, endmodule
input, output, inout
reg, integer, real, time
not, and, nand, or, nor, xor
parameter
begin, end
fork, join
specify, endspecify
Value Set in Verilog

4-value logic system in Verilog :

‘0’
‘X’

‘1’ ‘Z’
0
Major Data Type Class

Nets
Registers
Parameters
Nets
Net data type represent physical connections between
structural entities.
A net must be driven by a driver, such as a gate or a
continuous assignment.
Verilog automatically propagates new values onto a
net when the drivers change value.
Registers & Parameters

Registers represent abstract storage elements.


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.
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
Assignments ( cont. )
Blocking procedural assignment.
rega = regb + regc;
Non-blocking procedural assignment.
rega <= regb * regc;
Blocking vs. Non-Blocking (1) 92

05/31/2024
Verilog Fragment Result

always @ (a) begin C=B=A


b = a;
c = b; A-----B-------C
end

always @ (posedge Clock) begin B = Old A


C = Old B
b <= a;
c <= b; B C
end A D Q D Q

Clock
Blocking vs. Non-Blocking (2) 93

05/31/2024
 Use Non-Blocking for FlipFlop Inference
 posedge/negedge require Non-Blocking
 Else simulation and synthesis wont match
Blocking vs. Non-Blocking (3) 94

05/31/2024
 If you use blocking for FlipFlops:

YOU WILL NOT GET WHAT YOU WANT!


always @ (posedge Clock) begin
b = a; // b will go away
c = b; // c will be a FlipFlop
end
// b isn’t needed at all

always @ (posedge Clock) begin


c = b; // c will be a FlipFlop
b = a; // b will be a FlipFlop
end
Defining a module

 A module is the main building block in Verilog


 We first need to declare:
 Name of the module
 Types of its connections (input, output)
 Names of its connections

a
Verilog
b y
Module
c
Defining a module
module example (a, b, c, y);
input a;
input b;
input c;
output y;

// here comes the circuit description

endmodule

a
Verilog
b y
Module
c
A question of style
The following two codes are identical
module test ( a, b, y ); module test ( input a,
input a; input b,
input b; output y );
output y;
endmodule
endmodule
What if we have busses?
 You can also define multi-bit busses.
 [ range_start : range_end ]
 Example:

input [31:0] a; // a[31], a[30] .. a[0]


output [15:8] b1; // b1[15], b1[14] .. b1[8]
output [7:0] b2; // b2[7], b2[6] .. b1[0]
input clk; // single signal
Basic Syntax
 Verilog is case sensitive:
 SomeName and somename are not the same!
 Names cannot start with numbers:
 2good is not a valid name
 Whitespace is ignored

// Single line comments start with a //

/* Multiline comments
are defined like this */
Good Practices

 Develop/use a consistent naming style


 Use MSB to LSB ordering for busses (little-endian)
 Try using “a[31:0]” and not “a[0:31]”
 Define one module per file
 Makes managing your design hierarchy easier
 Use a file name that equals module name
 i.e. module TryThis is defined in a file called TryThis.v
There are Two Main Styles of HDL

 Structural
 Describe how modules are interconnected
 Each module contains other modules (instances)
 … and interconnections between these modules
 Describes a hierarchy
 Behavioral
 The module body contains functional description of the circuit
 Contains logical and mathematical operators

 Practical circuits would use a combination of both


Structural HDL: Instantiating a Module
Structural HDL Example
Module Definitions
module top (A, SEL, C, Y);
input A, SEL, C;
output Y;
wire n1;

module small (A, B, Y);


input A;
input B;
output Y;

// description of small
endmodule
endmodule
Structural HDL Example
Wire definitions
module top (A, SEL, C, Y);
input A, SEL, C;
output Y;
wire n1;

module small (A, B, Y);


input A;
input B;
output Y;

endmodule // description of small

endmodule
Structural HDL Example
Instantiate first module
module top (A, SEL, C, Y);
input A, SEL, C;
output Y;
wire n1;

// instantiate small once


small i_first ( .A(A),
.B(SEL),
.Y(n1) );
module small (A, B, Y);
input A;
input B;
output Y;

// description of small
endmodule
endmodule
Structural HDL Example
Instantiate second module
module top (A, SEL, C, Y);
input A, SEL, C;
output Y;
wire n1;

// instantiate small once


small i_first ( .A(A),
.B(SEL),
.Y(n1) );
module small (A, B, Y);
// instantiate small second time input A;
small i2 ( .A(n1), input B;
.B(C), output Y;
.Y(Y) );
// description of small
endmodule
endmodule
Structural HDL Example
Short Instantiation
module top (A, SEL, C, Y);
input A, SEL, C;
output Y;
wire n1;

// alternative
small i_first ( A, SEL, n1 );

/* Shorter instantiation,
pin order very important */ module small (A, B, Y);
input A;
// any pin order, safer choice input B;
small i2 ( .B(C), output Y;
.Y(Y),
.A(n1) ); // description of small

endmodule endmodule
What Happens with HDL code?

 Automatic Synthesis (combine)


 Modern tools are able to map a behavioral HDL code into gate-level schematics
 They can perform many optimizations
 … however they can not guarantee that a solution is optimal
 Most common way of Digital Design these days
 Simulation
 Allows the behavior of the circuit to be verified without actually manufacturing the
circuit
 Simulators can work on behavioral or gate-level schematics
Behavioral HDL: Defining Functionality

module example (a, b, c, y);


input a;
input b;
input c;
output y;

// here comes the circuit description


assign y = ~a & ~b & ~c |
a & ~b & ~c |
a & ~b & c;

endmodule
Behavioral HDL: Synthesis Results
b
c y
un5_y y

un8_y
Behavioral HDL: Simulating the Circuit
Bitwise Operators
module gates(input [3:0] a, b,
output [3:0] y1, y2, y3, y4, y5);

/* Five different two-input logic


gates acting on 4 bit busses */

assign y1 = a & b; // AND


assign y2 = a | b; // OR
assign y3 = a ^ b; // XOR
assign y4 = ~(a & b); // NAND
assign y5 = ~(a | b); // NOR

endmodule
Bitwise Operators: Synthesis Results
Reduction Operators

module and8(input [7:0] a,


output y);

assign y = &a;

// &a is much easier to write than


// assign y = a[7] & a[6] & a[5] & a[4] &
// a[3] & a[2] & a[1] & a[0];

endmodule
Reduction Operators: assign y = &a;
Conditional Assignment
module mux2(input [3:0] d0, d1,
input s,
output [3:0] y);

assign y = s ? d1 : d0;
// if (s) then y=d1 else y=d0;

endmodule

 ? : is also called a ternary operator as it operates on three inputs:


 s
 d1
 d0.
Conditional Assignment: y = s ? d1: d0;
More Conditional Assignments

module mux4(input [3:0] d0, d1, d2, d3


input [1:0] s,
output [3:0] y);

assign y = s[1] ? ( s[0] ? d3 : d2)


: ( s[0] ? d1 : d0);
// if (s1) then
// if (s0) then y=d3 else y=d2
// else
// if (s0) then y=d1 else y=d0

endmodule
Even More Conditional Assignments

module mux4(input [3:0] d0, d1, d2, d3


input [1:0] s,
output [3:0] y);

assign y = (s == 2’b11) ? d3 :
(s == 2’b10) ? d2 :
(s == 2’b01) ? d1 :
d0;
// if (s = “11” ) then y= d3
// else if (s = “10” ) then y= d2
// else if (s = “01” ) then y= d1
// else y= d0

endmodule
How to Express numbers ?

N’Bxx
8’b0000_0001
 (N) Number of bits
 Expresses how many bits will be used to store the value
 (B) Base
 Can be b (binary), h (hexadecimal), d (decimal), o (octal)
 (xx) Number
 The value expressed in base, apart from numbers it can also have X and Z as values.
 Underscore _ can be used to improve readability
Number Representation in Verilog
Verilog Stored Number Verilog Stored Number

4’b1001 1001 4’d5 0101

8’b1001 0000 1001 12’hFA3 1111 1010 0011

8’b0000_1001 0000 1001 8’o12 00 001 010

8’bxX0X1zZ1 XX0X 1ZZ1 4’h7 0111

‘b01 0000 .. 0001 12’h0 0000 0000 0000


What have seen so far:

 Describing structural hierarchy with Verilog


 Instantiate modules in an other module
 Writing simple logic equations
 We can write AND, OR, XOR etc
 Multiplexer functionality
 If … then … else
 We can describe constants
 But there is more:
Precedence of operations in Verilog

Highest ~ NOT
*, /, % mult, div, mod
+, - add,sub
<<, >> shift

<<<, >>> arithmetic shift


<, <=, >, >= comparison
==, != equal, not equal
&, ~& AND, NAND
^, ~^ XOR, XNOR
|, ~| OR, NOR
Lowest ?: ternary operator
Example: Comparing two numbers
An XNOR gate An AND gate
module MyXnor (input a, b, module MyAnd (input a, b,
output z); output z);

assign z = ~(a ^ b); //not XOR assign z = a & b; // AND

endmodule endmodule
Example: Comparing Two Numbers

module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3, c01, c23;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR
MyAnd haha (.A(c0), .B(c1), .Z(c01) ); // AND
MyAnd hoho (.A(c2), .B(c3), .Z(c23) ); // AND
MyAnd bubu (.A(c01), .B(c23), .Z(eq) ); // AND

endmodule
Example: Comparing Two Numbers

module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3, c01, c23;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR
assign c01 = c0 & c1;
assign c23 = c2 & c3;
assign eq = c01 & c23;

endmodule
Example: Comparing Two Numbers

module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire c0, c1, c2, c3;

MyXnor i0 (.A(a0), .B(b0), .Z(c0) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c1) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c2) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c3) ); // XNOR

assign eq = c0 & c1 & c2 & c3;

endmodule
Example: Comparing Two Numbers

module compare (input a0, a1, a2, a3, b0, b1, b2, b3,
output eq);
wire [3:0] c; // bus definition

MyXnor i0 (.A(a0), .B(b0), .Z(c[0]) ); // XNOR


MyXnor i1 (.A(a1), .B(b1), .Z(c[1]) ); // XNOR
MyXnor i2 (.A(a2), .B(b2), .Z(c[2]) ); // XNOR
MyXnor i3 (.A(a3), .B(b3), .Z(c[3]) ); // XNOR

assign eq = &c; // short format

endmodule
Example: Comparing Two Numbers

module compare (input [3:0] a, input [3:0] b,


output eq);
wire [3:0] c; // bus definition

MyXnor i0 (.A(a[0]), .B(b[0]), .Z(c[0]) ); // XNOR


MyXnor i1 (.A(a[1]), .B(b[1]), .Z(c[1]) ); // XNOR
MyXnor i2 (.A(a[2]), .B(b[2]), .Z(c[2]) ); // XNOR
MyXnor i3 (.A(a[3]), .B(b[3]), .Z(c[3]) ); // XNOR

assign eq = &c; // short format

endmodule
Example: Comparing Two Numbers

module compare (input [3:0] a, input [3:0] b,

output eq);

wire [3:0] c; // bus definition

assign c = ~(a ^ b); // XNOR

assign eq = &c; // short format

endmodule
Example: Comparing Two Numbers

module compare (input [3:0] a, input [3:0] b,


output eq);

assign eq = (a == b) ? 1 : 0; // really short

endmodule
What is the BEST way of writing Verilog

 Quite simply IT DOES NOT EXIST!


 Code should be easy to understand
 Sometimes longer code is easier to comprehend
 Hierarchy is very useful
 In the previous example it did not look like that, but for larger designs it is
indispensible
 Try to stay closer to hardware
 After all the goal is to design hardware
Parameterized Modules
module mux2
#(parameter width = 8) // name and default value
(input [width-1:0] d0, d1,
input s,
output [width-1:0] y);

assign y = s ? d1 : d0;
endmodule

 We can pass parameters to a module


Parameterized Modules: Instantiating
module mux2
#(parameter width = 8) // name and default value
(input [width-1:0] d0, d1,
input s,
output [width-1:0] y);

assign y = s ? d1 : d0;
endmodule

 // If parameter is not given, default is assumed (here 8)


 mux2 i_mux (d0, d1, s, out);

 // The same module with 12-bit bus width:


 mux2 #(12) i_mux_b (d0, d1, s, out);

 // More verbose version:


 mux2 #(.width(12)) i_mux_b (.d0(d0), .d1(d1),
 .s(s), .out(out));
Manipulating Bits
 // You can assign partial busses
 wire [15:0] longbus;
 wire [7:0] shortbus;
 assign shortbus = longbus[12:5];

 // Concatenating is by {}
 assign y = {a[2],a[1],a[0],a[0]};

 // Possible to define multiple copies


 assign x = {a[0], a[0], a[0], a[0]}
 assign y = { 4{a[0]} }
Z floating output
module tristate(input [3:0] a,
input en, en
output [3:0] y); a[3:0] [3:0] [3:0] [3:0] [3:0]
y[3:0]

y_1[3:0]
assign y = en ? a : 4'bz;

endmodule
Truth Table for AND with Z and X

A
&
0 1 Z X

0 0 0 0 0

1 0 1 X X
B
Z 0 X X X

X 0 X X X
What About Timing ?
 It is possible to define timing relations in Verilog
 These are ONLY for Simulation
 They CAN NOT be synthesized
 They are used for modeling delays in simulation

‘timescale 1ns/1ps
module simple (input a, output z1, z2);

assign #5 z1 = ~a; // inverted output after 5ns


assign #9 z2 = a; // output after 9ns

endmodule

You might also like