verilog introduction by iit kharagpur profs- ppts
TRANSCRIPT
11103/08/10 11
Embedded Systems: HDL
(Lect 9)
Dr. RAJIB MALLProfessor
Department Of Computer Science & Engineering
IIT Kharagpur.
2
Hardware Description Languages
• HDL can be used to describe any digital system:
• For example, a computer or a component.
• A digital system can be described at several levels: • Switch level: wires, resistors and
transistors
• Gate level: logic gates and flip flops
• Register Transfer Level (RTL): registers and the transfers of information between registers.
3
Application Areas of HDL
System SpecificationSystem Specification
HW/SW Partition
HW/SW Partition
Hardware Spec
Hardware Spec
Softwre Spec
Softwre Spec
ASICASIC
FPGAFPGA
PLDPLD
Std PartsStd Parts
Boards&
Systems
Boards&
SystemsSoftwareSoftware
Suitable for all levelsBehavioral levelNot suitable
4
Description of digital systems only
Basic Limitation of HDL
5
Abstraction Levels in HDLs
BehavioralBehavioral
RTLRTL
GateGate
Layout (VLSI)Layout (VLSI)
Our focus
6
Main Language Concepts (i)
• Concurrency
• Structure
7
Main Language Concepts (ii)
•Procedural Statements
• Time
8
Why use HDL? 1•When HDL was first developed:
Most logic simulators operated on netlists
•Netlist: List of gates and how they’re connected
A natural representation of a digital logic circuit
•Not a very convenient way to express designs, simulate, debug…
9
Why use HDL? 2•Text-based•Allows simulation before
building circuit•Can be compiled (synthesized)
into logic circuit•Much easier to write test
benches
10
Why use HDL? 3• More abstract models of circuits
Easier to writeSimulates faster
• More flexible
• Provides sequencing
• A major par of Verilog’s success:It allowed both the model and the testbench to be described together
11
How HDL Is Used?
•Design written in HDL•Simulated to death to check
functionality•Synthesized (netlist
generated)•Static timing analysis to
check timing
12
Two Major HDLs•VHDL •Verilog HDL•Virtually every chip (FPGA, ASIC,
etc.):Designed in part using one of these two languages
• Combines structural and behavioral modeling styles.
13
VHDL• “V” is short for Very High Speed
Integrated Circuits. • Designed for and sponsored by US
Department of Defense. • Designed by a committee (1981-
1985).
• Syntax based on Ada programming language.
• Was made an IEEE Standard in 1987.
14
Verilog HDL•Introduced in 1985 by Gateway
Design System Corporation:Now a part of Cadence Design Systems, Inc.
•Became an IEEE Standard in 1995
•Syntax based on C programming language.
15
Verilog Compared to VHDL
•VHDLProvides some high-level constructs not available in Verilog:•E.g. user defined types, configurations
•VerilogProvides comprehensive support for low-level digital design.
Not available in native VHDL•E.g. Range of type definitions and supporting functions (called packages).
16
Verilog Compared to VHDL
• Verilog and VHDL are comparable languages
• VHDL has a slightly wider scopeSystem-level modelingFewer sources of nondeterminism (e.g., no shared variables)
• VHDL is harder to simulate quickly• VHDL has fewer built-in facilities for
hardware modelling• VHDL is a much more verbose language
Most examples don’t fit on slides
17
Design Methodology
18
Two Main Components of
Verilog•Behavior
Concurrent, event-triggered processes
•Structure:Wires, interconnection, etc.
Structural vs. Behaviorial Verilog
•Structural verilog:Module instances and their interconnections (by wires) only.
•Behavioral verilog: The use of regs, explicit time delays, arithmetic expressions, procedural assignments, and other verilog control flow structures.
20
Concept of Verilog “Module”
• In Verilog, the basic unit of hardware is called a module. Modules cannot contain definitions of
other modules. A module can, however, instantiate
another module. Allows the creation of a hierarchy in
a Verilog description.
21
Basic Syntax of Module Definition
module module_name (list_of_ports);
input/output declarationslocal net declarationsParallel statements
endmodule
22
Example 1 :: Simple AND gate
module simpleand (f, x, y); input x, y; output f; assign f = x & y;endmodule
23
Verilog Half Adder
module half_adder_v(x, y, s, c); input x, y; output s, c;
assign s = x ^ y;assign c = x & y;
endmodule
24
Verilog Full Addermodule full_adder_v(x, y, z, s, c); input x, y, z; output s, c;
half_adder_v HA1(x, y, hs, hc), HA2(hs, z, s, tc); assign c = tc | hc;
endmodule
Mixing structural and behaviorial code.
25
Four-Bit Addermodule adder_4_v(B, A, C0, S, C4); input[3:0] B, A; input C0; output[3:0] S; output C4;
wire[3:1] C;
full_adder_v Bit0(B[0], A[0], C0, S[0], C[1]), Bit1(B[1], A[1], C[1], S[1], C[2]), Bit2(B[2], A[2], C[2], S[2], C[3]), Bit3(B[3], A[3], C[3], S[3], C4);endmodule
Look at connections
between adders
Behavioral Verilog// 4-bit Adder: Behavioral Verilog
module adder_4_b_v(A, B, C0, S, C4);input[3:0] A, B;input C0;output[3:0] S;output C4;
assign {C4, S} = A + B + C0;endmodule
Addition (unsigned)
Concatenation operation
Mixing structural and behaviorial code.
27
Verilog Program Structure
•Program composed of modules:Main moduleOther modules
•Each module takes parameters and returns values
•Let us write a Verilog program for (A NAND B) NAND (C NAND D)
28
First Verilog Program• module mynand(out,in1,in2);
input in1,in2; output out; assign out=~(in1 & in2);
• endmodule• module firstprog(o,p,q,m,n);
input p,q,m,n; output o; wire w1,w2; mynand nand1(p,q,w1); mynand nand2(m,n,w2); mynand nand3(w1,w2,o);
• endmodule
o
p
q
m
n
o
o
29
Discrete-event Simulation
• Basic idea: only do work when something changes
• Centered around an event queue Contains events labeled with the simulated time at
which they are to be executed
• Basic simulation paradigm Execute every event for the current simulated time Doing this changes system state and may
schedule events in the future When there are no events left at the current time
instance, advance simulated time to the next event in the queue
30
Module portsModule name
Verilog keywords
Taste of Verilog: Structural
module Add_half ( sum, c_out, a, b ); input a, b;
output sum, c_out;wire c_out_bar;
xor (sum, a, b);nand (c_out_bar, a, b);not (c_out, c_out_bar);
endmodule
Declaration of port modes
Declaration of internal signal
c_out
a
b sum
c_out_bar
Instantiation of primitive gates
31
module Add_half ( sum, c_out, a, b ); input a, b;
output sum, c_out;
assign {c_out, sum} = a + b;endmodule
c_out
a
b sum
c_out_bar
Taste of Verilog: Behaviorial
32
Module Structure•Verilog program built from
modules with I/O interfaces A module may contain instances of
other modules
A module can contain local signals, etc.
Module configurations are static and all run concurrently
33
Two Main Data Types• Nets represent connections between things
Do not hold their value Take their value from a driver such as a gate 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
34
Data Types: Variables• Variables are instances of two basic
families of data types: Nets and Registers • Net variables – e.g. wire
• Variable used simply to connect components together
• Usually corresponds to a wire in the circuit.
• Register variables – e.g. reg • Variable used to store data as part of a
behavioral description • Just like variables in C language.
35
Nets •Can be thought as hardware wires
driven by logic•Equals z when unconnected•Various types of nets–wire–wand (wired-AND)–wor (wired-OR)–tri (tri-state)
36
Net data type• Different ‘net’ types supported for
synthesis: wire, wor, wand, tri, supply0, supply1
• ‘wire’ and ‘tri’ are equivalent; when there are multiple drivers driving them,
the outputs of the drivers are shorted together.
• ‘wor’ / ‘wand’ inserts an OR / AND gate at the connection.
• ‘supply0’ / ‘supply1’ model power supply connections.
37
Nets A
BY wire Y; // declaration
assign Y = A & B;
B
A
Y
wand Y; // declarationassign Y = A; assign Y = B;
wor Y; // declarationassign Y = A; assign Y = B;
A Y
dr
tri Y; // declarationassign Y = (dr) ? A : z;
38
Register data type
• Different ‘register’ types supported: reg, integer
• The ‘reg’ declaration requires explicit specification of the size.
reg x, y; // single-bit register variables
reg [15:0] bus; // 16-bit bus, bus[15] MSB
• For ‘integer’, it takes the default size, usually 32-bits. Synthesizer tries to determine the size.
39
Registers• Variables that store values• Do not represent real hardware but ..
.. real hardware can be implemented with registers
• Only one type: regreg A, C; // declaration// assignments always done inside a procedureA = 1;C = A; // C gets the logical value 1A = 0; // C is still 1C = 0; // C is now 0
40
Nets and Registers• Wires and registers can be bits or 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
41
Vectors• Represent buses
wire [3:0] busA;reg [1:4] busB; reg [1:0] busC;
• Left number is MS bit
• Slice managementbusC[1] = busA[2];
busC[0] = busA[1];
• Vector assignment (by position!!)busB[1] = busA[3];
busB[2] = busA[2];busB[3] = busA[1];busB[4] = busA[0];
busB = busA;
busC = busA[2:1];
42
Integer & Real Data Types• Declaration
integer i, k;real r;
• Use as registers (inside procedures)i = 1; // assignments occur inside procedurer = 2.9;k = r; // k is rounded to 3
• Integers are not initialized!!• Reals are initialized to 0.0
43
Time Data Type• Special data type for simulation time
measurement.
• Declaration
time my_time;
• Use inside procedure
my_time = $time; // get current sim time
• Simulation runs at simulation time, not
real time
44
Arrays (i)• Syntax
integer count[1:5]; // 5 integersreg var[-15:16]; // 32 1-bit regsreg [7:0] mem[0:1023]; // 1024 8-bit regs
• Accessing array elements Entire element: mem[10] = 8’b 10101010; Element subfield (needs temp storage):
reg [7:0] temp;..temp = mem[10];var[6] = temp[2];
45
Arrays (ii)• Limitation: Cannot access array subfield
or entire array at oncevar[2:9] = ???; // WRONG!!
var = ???; // WRONG!!
• No multi-dimentional arraysreg var[1:10] [1:100]; // WRONG!!
• Arrays don’t work for the Real data typereal r[1:10]; // WRONG !!
46
Verilog Operators• Arithmetic operators
*, /, +, -, % • Logical operators
! logical negation && logical AND | | logical OR
• Relational operators
>, <, >=, <=, ==, !=• Bitwise operators
~, &, |, ^, ~^
47
• Reduction operators (operate on all the bits within a word)
&, ~&, |, ~|, ^, ~^ accepts a single word operand and produces a single bit as output
• Shift operators
>>, <<• Concatenation { }• Replication { { } }• Conditional
<condition> ? <expression1> : <expression2>
48
Bitwise Operators~ NOT
& AND
| OR
^ XOR
~| NOR
~& NAND
^~ or ~^ XNOR
49
Value Logic System• Data type for signals
• Bits (value on a wire) – 0, 1 – x unknow value
• Vectors of bits (parallel wires or registers) – A[3:0] is a vector of 4 bits: A[3], A[2],
A[1], A[0] – Concatenating bits/vectors into a vector
• B[7:0] = {A[3], A[3], A[3], A[3], A[3:0]};• B[7:0] = {4{A[3]}, A[3:0]};
50
Note•reg are used with always and initial
blocks.
•reg variables: Store the last value that was procedurally assigned to them
•wire variables: Represent physical connections between structural entities such as gates.
51
Continuous Assignment• A continuous assignment statement is
declared with the keyword assign, • followed by a net variable, an
assignment operator(=), and an expression.
• assign corresponds to a connection.• Target should not be a reg variable.
– assign A = B | (C & ~D); – assign B[3:0] = 4'b01XX; – assign C[15:0] = 16'h00ff; //(MSB:LSB) – assign {Cout, S[3:0]} = A[3:0] + B[3:0] +
Cin;
52
Other differences:• In arithmetic expressions,
An ‘integer’ is treated as a 2’s complement signed integer.
A ‘reg’ is treated as an unsigned quantity.
•General rule of thumb ‘reg’ used to model actual hardware
registers such as counters, accumulator, etc.
‘integer’ used for situations like loop counting.
53
Modules and Instances
• Basic structure of a Verilog module:
module mymod(output1, output2, … input1, input2);
output output1;output [3:0] output2;input input1;input [2:0] input2;…endmodule
Verilog convention lists outputs first
54
Instantiating a Module• Instances of module mymod(y, a, b);
• look like
mymod mm1(y1, a1, b1); // Connect-by-position
mymod (y2, a1, b1), (y3, a2, b2); // Instance names
omitted
mymod mm2(.a(a2), .b(b2), .y(c2)); // Connect-by-name
55
Gate-level Primitives• Verilog provides the following:
and nand logical AND/NAND
or nor logical OR/NOR
xor xnor logical XOR/XNOR
buf not buffer/inverter
bufif0 notif0 Tristate with low enable
bifif1 notif1 Tristate with high enable
56
Delays on Primitive Instances
• Instances of primitives may include delays
buf b1(a, b); // Zero delaybuf #3 b2(c, d); // Delay of 3buf #(4,5) b3(e, f); // Rise=4, fall=5buf #(3:4:5) b4(g, h); // Min-typ-
max
57
User-Defined Primitives
• Way to define gates and sequential elements using a truth tableOften simulate faster than using expressions, collections of primitive gates, etc.
Gives more control over behavior with X inputs
Most often used for specifying custom gate libraries
58
• When ‘integer’ is used: The synthesis system often carries out a data
flow analysis of the model to determine its actual size.
• Example: wire [1:10] A, B; integer C; C = A + B;
The size of C can be determined to be equal to 11 (10 bits plus a carry).
59
A Carry Primitiveprimitive carry(out, a, b, c);output out;input a, b, c;table 00? : 0; 0?0 : 0; ?00 : 0; 11? : 1; 1?1 : 1; ?11 : 1;endtableendprimitive
Always have exactly one output
Truth table may include don’t-care (?) entries
60
A Sequential CircuitPrimitive dff( q, clk, data);output q; reg q;input clk, data;table// clk data q new-q (01) 0 : ? : 0; // Latch a 0 (01) 1 : ? : 1; // Latch a 1 (0x) 1 : 1 : 1; // Hold when d and q both
1 (0x) 0 : 0 : 0; // Hold when d and q both 0 (?0) ? : ? : -; // Hold when clk falls ? (??) : ? : -; // Hold when clk stableendtableendprimitive
61
Continuous Assignment• Another way to describe combinational
function• Convenient for logical or datapath
specifications
wire [8:0] sum;wire [7:0] a, b;wire carryin;
assign sum = a + b + carryin;
Define bus widths
Continuous assignment: permanently sets the value of sum to be a+b+carryin
Recomputed when a, b, or carryin changes
62
Identifiers• An identifier is composed of a space-free
sequence of uppercase and lowercase letters:• alphabet, digits (0,1,….9), underscore
(_), and the $ symbol. • Verilog is a case sensitive language.
– c_out_bar and C_OUT_BAR are two different identifiers
• The name of a variable may not begin with a digit or $, and may be up to 1,024 characters long. – e.g. clock_, state_3
63
Comments• There are two kinds of comments:
• single line and multiline. • A single-line comment begins // • A multiline comment: /* comment */ • Example:
– // This is a single-line comments– /* This is a multiline comments
more comments here
…………………………………. */
64
Numbers in Verilog
<size>’<radix> <value>
8’h ax = 1010xxxx 12’o 3zx7 = 011zzzxxx111
No of bits
No of bits
Binary b or BOctal o or ODecimal d or DHex h or H
Binary b or BOctal o or ODecimal d or DHex h or H
Consecutive chars 0-f, x, z
Consecutive chars 0-f, x, z
65
Numbers• Numbers are specified using the
following form
<size><base format><number>• Size: a decimal number specifies the size
of the number in bits.
• Base format: is the character ’ followed by one of the following characters – b for binary,d for decimal,o(octal),h(hex).
• Number: set of digits to represent the number.
66
Numbers• Example :
x = 347 // decimal number
x = 4’b101 // 4- bit binary number 0101
x = 6’o12 // 6-bit octal number
x = 16’h87f7 // 16-bit hex number h87f7
x = 6’b101010
• String in double quotes
“ this is an introduction”
67
Numbers in Verilog •You can insert “_” for readability
12’b 000_111_010_100 12’b 000111010100 12’o 07_24
•Bit extension MS bit = 0, x or z extend this
•4’b x1 = 4’b xx_x1
MS bit = 1 zero extension•4’b 1x = 4’b 00_1x
Represent the same number
68
Data Types: Constants
• A constant is declared:
• With the keyword parameter in a statement assigning a name and a value to the constant
• The value of a constant is fixed during simulation.
• Examples: – parameter HIGH_INDEX= 31; // integer
– parameter BYTE_SIZE = 8;
69
Parameters• A parameter is a constant with a name.• No size is allowed to be specified for a parameter.
The size gets decided from the constant itself (32-bits if nothing is specified).
• Examples: parameter HI = 25, LO = 5; parameter up = 2b’00, down = 2b’01, steady = 2b’10;
70
Four-valued Data• Verilog’s nets and registers hold four-valued
data• 0, 1
Obvious
• Z Output of an undriven tri-state driver Models case where nothing is setting a wire’s value
• X Models when the simulator can’t decide the value Initial state of registers When a wire is being driven to 0 and 1
simultaneously Output of a gate with Z inputs
71
Logic Values• The common values used in
modeling hardware are: 0 :: Logic-0 or FALSE 1 :: Logic-1 or TRUE x :: Unknown (or don’t care) z :: High impedance
• Initialization: All unconnected nets set to ‘z’ All register variables set to ‘x’
72
Four-valued Logic• Logical operators work on three-
valued logic
0 1 X Z
0 0 0 0 0
1 0 1 X X
X 0 X X X
Z 0 X X X
Output 0 if one input is 0
Output X if both inputs are gibberish
73
Predefined logic gates.
• Verilog provides a set of predefined logic gates. They respond to inputs (0, 1, x, or z)
in a logical way. Example :: AND
0 & 0 0 0 & x 0
0 & 1 0 1 & z x
1 & 1 1 z & x x
1 & x x
74
Primitive Gates• 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);
75
Some Points to Note• For all primitive gates,
The output port must be connected to a net (a wire).
The input ports may be connected to nets or register type variables.
They can have a single output but any number of inputs.
An optional delay may be specified.•Logic synthesis tools ignore time delays.
76
`timescale 1 ns / 1nsmodule 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
77
Hardware Modeling Issues
• The values computed can be held in A ‘wire’ A ‘flip-flop’ (edge-triggered storage cell) A ‘latch’ (level-sensitive storage cell)
• A variable in Verilog can be of ‘net’ data type
•Maps to a ‘wire’ during synthesis ‘register’ data type
•Maps either to a ‘wire’ or to a ‘storage cell’ depending on the context under which a value is assigned.
78
module reg_maps_to_wire (A, B, C, f1, f2);
input A, B, C; output f1, f2; wire A, B, C; reg f1, f2; always @(A or B or C) begin f1 = ~(A & B); f2 = f1 ^ C; endendmodule
The synthesis systemwill generate a wire
for f1
79
module operator_example (x, y, f1, f2); input x, y; output f1, f2; wire [9:0] x, y; wire [4:0] f1; wire
f2;
assign f1 = x[4:0] & y[4:0]; assign f2 = x[2] | ~f1[3]; assign f2 = ~& x; assign f1 = f2 ? x[9:5] : x[4:0];endmodule
80
// 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
81
Some Points•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.
82
Some Valid Statements
assign outp = (p == 4’b1111);if (load && (select == 2’b01)) …….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
timesassign f = {2’b10, 3{2’b01}, x};
83
Description Styles in Verilog
• Two different styles of description:
1. Data flow• Continuous assignment
2. Behavioral• Procedural assignment
BlockingNonblocking
84
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.
85
•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”.
86
module generate_mux (data, select, out);
input [0:7] data; input [0:2] select; output out;
assign out = data [ select];endmodule Non-constant index in
expression on RHS generates a MUX
87
module generate_decoder (out, in, select);
input in; input [0:1] select; output [0:3] out;
assign out [ select] = in;endmodule Non-constant index in
expression on LHS generates a decoder
88
module generate_set_of_MUX (a, b, f, sel);
input [0:3] a, b, sel; output [0:3] f;
assign f = sel ? a : b;endmodule
Conditional operatorgenerates a MUX
89898903/08/10 8989
Embedded Systems: HDL
(Lect 10)
Dr. RAJIB MALLProfessor
Department Of Computer Science & Engineering
IIT Kharagpur.
90
Behavioral Style: Procedural Assignment
• A procedural block defines A region of code containing sequential
statements. Statements execute in the order they are
written.• Two types of procedural blocks in Verilog
The “always” block•A continuous loop that never terminates.
The “initial” block•Executed once at the beginning of simulation
(used in Test-benches).
91
Concurrent, event-triggered processes
(behavior)• Initial and Always blocks define
procedures.• Procedures define imperative code:
Perform standard data manipulation tasks (assignment, if-then, case)
• Procedures run: until they delay for a period of time or wait for a triggering event
92
Initial and Always Blocks
• Basic components for behavioral modeling
initial
begin
… imperative statements …
end
Runs when simulation starts
Terminates when control reaches the end
Good for providing stimulus
always
begin
… imperative statements …
end
Runs when simulation starts
Restarts when control reaches the end
Good for modeling/specifying hardware
93
Procedural Blocks• There are two types of procedural
blocks in Verilog.
–initial for single-pass behavior : initial blocks execute only once at time zero (start execution at time zero).
–always for cyclic behavior: always blocks loop to execute over and over again, in other words as name means, it executes always.
94
Procedural Blocks• Procedural assignment may only
appear in initial and always constructs.
• The initial and always constructs are used to model sequential logic.
• Continuous statement is used to model combinational logic.
95
Behavioral Model - Procedures (i)
•Procedures = sections of code that we know execute sequentially
•e.g. 2-to-1 mux implem:begin if (sel == 0)
Y = B; else
Y = A;end
ExecutionFlow
Procedural assignments:Y must be reg !!
Procedural assignments:Y must be reg !!
96
Events (i)• @
always @(signal1 or signal2 or ..) begin..end
always @(posedge clk) begin..end
always @(negedge clk) begin..end
execution triggers every time any signal changes
execution triggers every time any signal changes
execution triggers every time clk changes
from 0 to 1
execution triggers every time clk changes
from 0 to 1
execution triggers every time clk changes
from 1 to 0
execution triggers every time clk changes
from 1 to 0
97
Initial and Always• Run until they encounter a delay
initial begin #10 a = 1; b = 0; #10 a = 0; b = 1;end
• or a wait for an event
always @(posedge clk) q = d;always begin wait(i); a = 0; wait(~i); a = 1; end
98
Procedural Assignment
• Inside an initial or always block: sum = a + b + cin;• Just like in C:
RHS evaluated and assigned to LHS before next statement executes
• RHS may contain wires and regsTwo possible sources for data
• LHS must be a regPrimitives or cont. assignment may set wire values
99
Imperative Statements
if (select == 1) y = a;else y = b;
case (op) 2’b00: y = a + b; 2’b01: y = a – b; 2’b10: y = a ^ b; default: y = ‘hxxxx;endcase
100
For Loops• A increasing sequence of values on
an output
reg [3:0] i, output;
for ( i = 0 ; i <= 15 ; i = i + 1 ) begin output = i; #10;end
101
While Loops• A increasing sequence of values on
an output
reg [3:0] i, output;
i = 0;while (I <= 15) begin output = i; #10 i = i + 1;end
102
About “Loop” Statements• Verilog supports four types of loops:
‘while’ loop ‘for’ loop ‘forever’ loop ‘repeat’ loop
• Many Verilog synthesizers supports only ‘for’ loop for synthesis: Loop bound must evaluate to a
constant. Implemented by unrolling the ‘for’ loop,
and replicating the statements.
103
Modeling A Flip-Flop With Always
• Very basic: an edge-sensitive flip-flop
reg q;
always @(posedge clk) q = d;
• q = d assignment runs when clock rises: exactly the behavior you expect
104
Behavioral Model - Procedures (ii)
• Modules can contain any number of procedures
• Procedures execute in parallel (in respect to
each other) and ..
• .. can be expressed in two types of blocks:
initial they execute only once
always they execute for ever (until
simulation finishes)
105
Example: Initial Block
module initial_example();reg clk,reset,enable,data;initial begin
clk = 0;reset = 0;enable = 0;data = 0;
endendmodule
The initial block is executed at time 0.Initial block just executes all the statements within begin and end statements.
106
“Initial” Blocks•Start execution at sim time zero and
finish when their last statement executesmodule nothing;initial
$display(“I’m first”);initial begin
#50;$display(“Really?”);end
endmodule
Will be displayedat sim time 0
Will be displayedat sim time 0
Will be displayedat sim time 50
Will be displayedat sim time 50
107
“Always” Blocks•Start execution at sim time zero
and continue until sim finishes
108
• 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.
Sequentialstatements
109
• Only “reg” type variables can be assigned within an “always” block. Why??
The sequential “always” block executes only when the event expression triggers.
At other times the block is doing nothing. An object being assigned to must therefore
remember the last value assigned (not continuously driven).
So, only “reg” type variables can be assigned within the “always” block.
Of course, any kind of variable may appear in the event expression (reg, wire, etc.).
110
Sequential Statements in Verilog
1. begin sequential_statements end2. if (expression) sequential_statement [else sequential_statement]3. case (expression) expr: sequential_statement ……. default: sequential_statement endcase
begin...end not required
if there is only 1 stmt.
111
4. forever sequential_statement5. repeat (expression) sequential_statement6. while (expression) sequential_statement7. for (expr1; expr2; expr3) sequential_statement
112
8. # (time_value)• Makes a block suspend for
“time_value” time units.9. @ (event_expression)
• Makes a block suspend until event_expression triggers.
113
Control Constructs– Used in the procedural
sections of code.
Selection if statement:
if (A == 4)begin
B = 2;end else begin
B = 4;end
case statements: case (<expression>)
<value1>: <statement>
<value2>: <statement>
default: <statement>endcase
114
// 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
115
// A sequential logic example
module dff_negedge (D, clock, Q, Qbar); input D, clock; output Q, Qbar; reg Q, Qbar;
always @ (negedge clock) begin Q = D; Qbar = ~D; endendmodule
116
module ALU_4bit (f, a, b, op);
input [1:0] op; input [3:0] a, b; output [3:0] f; reg [3:0] f;
parameter ADD=2’b00, SUB=2’b01, MUL=2’b10, DIV=2’b11;
always @ (a or b or op) case (op) ADD : f = a + b; SUB : f = a – b; MUL : f = a * b; DIV : f = a / b; endcaseendmodule
117
module priority_encoder (in, code); input [0:3] in; output [0:1] code; reg [0:1] code; always @ (in) case (1’b1) input[0] : code = 2’b00; input[1] : code = 2’b01; input[2] : code = 2’d10; input[3] : code = 2’b11; endcaseendmodule
118
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; endendmodule
119
Example: 4-1 MUX in behavioral (1)
module mux4 (sel, A, B, C, D, Y);input [1:0] sel; // 2-bit control signalinput A, B, C, D;output Y;reg Y; // target of assignmentalways @(sel or A or B or C or D)
If (sel == 2’b00) Y = A;else if (sel == 2’b01) Y = B;else if (sel == 2’b10) Y = C;else if (sel == 2’b11) Y = D;
endmodule
A
B
C
D
Y
Sel[1:0]
120
Example: 4-1 MUX in behavioral (2)
// 4-1 mux using case statement
module mux4 (sel, A, B, C, D, Y);
input [1:0] sel; // 2-bit control signal
input A, B, C, D;
output Y;
reg Y; // target of assignment
always @(sel or A or B or C or D)
case (sel)
2’b00: Y = A;
2’b01: Y = B;
2’b10: Y = C;
2’b11: Y = D;
endcase
endmodule
A
B
C
D
Y
Sel[1:0]
121
Example: 4-1 MUX in behavioral (3)
// 4-1 mux using case statementmodule mux4 (select, d, q);
input [1:0] select; // 2-bit control signalinput [3:0] d;output q;reg q; // target of assignmentalways @(select or d)
case (select)2’b00: q = d[0];2’b01: q = d[1];2’b10: q = d[2];2’b11: q = d[3];
endcaseendmodule
122
Example: 4-1 MUX in structuralmodule mux4( select, d, q );
input[1:0] select; input[3:0] d; output q; wire q, q1, q2, q3, q4;
wire NOTselect0, NOTselect1; wire[1:0] select; wire[3:0] d;
not n1( NOTselect0, select[0] ); not n2( NOTselect1, select[1] ); and a1( q1, NOTselect0, NOTselect1, d[0] ); and a2( q2, select[0], NOTselect1, d[1] ); and a3( q3, NOTselect0, select[1], d[2] ); and a4( q4, select[0], select[1], d[3] ); or o1( q, q1, q2, q3, q4 );
endmodule
123
Another Example: 4-bit Full Adder using 1-bit Full Adder
module FourBitAdder( sum, c_out, x, y, c_in);output [3:0] sum; output c_out; input [3:0] x, y; input c_in; wire c1, c2, c3; fulladder fa0( sum[0], c1, x[0], y[0], c_in ); fulladder fa1( sum[1], c2, x[1], y[1], c1 ); fulladder fa2( sum[2], c3, x[2], y[2], c2 ); fulladder fa3( sum[3], c_out, x[3], y[3], c3 );
endmodule
module fulladder( sum, c_out, x, y, c_in ); output sum, c_out; input x, y, c_in; wire a, b, c; xor( a, x, y); xor( sum, a, c_in ); and( b, x, y ); and( c, a, c_in ); or( c_out, c, b );
endmodule
124
Examples• module half_adder(S,
C, A, B);output S, C;input A, B;reg S,C;wire A, B;always @(A or B) begin
S = A ^ B;C = A & B;end
endmodule
• Behavioral edge-triggered DFF module dff(Q, D, Clk);output Q;input D, Clk;reg Q;wire D, Clk;always @(posedge Clk)
Q = D;
endmodule
125
Timing (i)
initial begin#5 c = 1;#5 b = 0;#5 d = c;end
initial begin#5 c = 1;#5 b = 0;#5 d = c;end
0 5 10 15
Time
b
c
d
Each assignment isblocked by its previous one
126
Timing (ii)
initial beginfork#5 c = 1;#5 b = 0;#5 d = c;joinend
initial beginfork#5 c = 1;#5 b = 0;#5 d = c;joinend
0 5 10 15
Time
b
c
d
Assignments are not blocked here
127
Blocking & Non-blocking Assignments
• Sequential statements within procedural blocks (“always” and “initial”) can use two types of assignments: Blocking assignment
•Uses the ‘=’ operator
Non-blocking assignment•Uses the ‘=>’ operator
128
Blocking and Non-blocking Procedural
Assignments• The blocking assignment statement (= operator): Acts much like in traditional programming
languages. Blocking statement must complete execute
before the next statement in the behavior can execute.
• The non-blocking (<= operator): Evaluates all the right-hand sides for the
current time unit and assigns the left-hand sides at the end of the time unit.
Non-blocking assignment statements execute concurrently rather than sequentially.
129
Blocking vs. Nonblocking
• Verilog has two types of procedural assignment
• Fundamental problem:In a synchronous system, all flip-flops sample simultaneously
In Verilog, always @(posedge clk) blocks run in some undefined sequence
130
A Flawed Shift Register
• This doesn’t work as you’d expect:
reg d1, d2, d3, d4;
always @(posedge clk) d2 = d1;always @(posedge clk) d3 = d2;always @(posedge clk) d4 = d3;
• These run in some order, but you don’t know which
131
Non-blocking Assignments
• This version does work:
reg d1, d2, d3, d4;
always @(posedge clk) d2 <= d1;always @(posedge clk) d3 <= d2;always @(posedge clk) d4 <= d3;
Nonblocking rule:
RHS evaluated when assignment runs
LHS updated only after all events for the current instant have run
132
Nonblocking Can Behave Oddly
• A sequence of nonblocking assignments don’t communicatea = 1;
b = a;
c = b;
Blocking assignment:
a = b = c = 1
a <= 1;
b <= a;
c <= b;
Nonblocking assignment:
a = 1
b = old value of a
c = old value of b
133
Nonblocking Looks Like Latches
• RHS of nonblocking taken from latches• RHS of blocking taken from wires
a = 1;
b = a;
c = b;
a <= 1;
b <= a;
c <= b;
1a b c
a
b
c
1
134
Blocking Assignment (using ‘=’)
• Most commonly used type.
• The target of assignment gets updated: Before the next sequential statement in
the procedural block is executed.
• A statement using blocking assignment: Blocks the execution of the statements
following it, until it gets completed.
• Recommended style for modeling combinational logic.
135
Non-Blocking Assignment (using ‘<=’)
• The assignment to the target gets scheduled for the end of the simulation cycle. 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.
136
Some Rules to be Followed
• Verilog synthesizer ignores the delays specified in a procedural assignment statement.
–May lead to functional mismatch between the design model and the synthesized netlist.
•A variable cannot appear as the target of both a blocking and a non-blocking assignment.
Following is not permissible: value = value + 1;
value <= init;
137
// Up-down counter (synchronous clear)
module counter (mode, clr, ld, d_in, clk, count); input mode, clr, ld, clk; input [0:7] d_in; output [0:7] count; reg [0:7] count; always @ (posedge clk) if (ld) count <= d_in; else if (clr) count <= 0; else if (mode) count <= count + 1; else count <= count + 1;endmodule
138
// 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
139
// Using more than one clocks in a module
module multiple_clk (clk1, clk2, a, b, c, f1, f2); input clk1, clk2, a, b, c; output f1, f2; reg f1, f2; always @ (posedge clk1) f1 <= a & b; always @ (negedge clk2) f2 <= b ^ c;endmodule
140
// Using multiple edges of the same clock
module multi_phase_clk (a, b, f, clk); input a, b, clk; output f; reg f, t; always @ (posedge clk) f <= t & b; always @ (negedge clk) t <= a | b;endmodule
141
A Ring Counter Examplemodule ring_counter (clk, init, count); input clk, init; output [7:0] count; reg [7:0] count; always @ (posedge clk) begin if (init) count = 8’b10000000; else begin count = count << 1; count[0] = count[7]; end endendmodule
142
A Ring Counter Example (Modified--1)
module ring_counter_modi1 (clk, init, count); input clk, init; output [7:0] count; reg [7:0] count; always @ (posedge clk) begin if (init) count = 8’b10000000; else begin count <= count << 1; count[0] <= count[7]; end endendmodule
143
A Ring Counter Example (Modified – 2)
module ring_counter_modi2 (clk, init, count); input clk, init; output [7:0] count; reg [7:0] count; always @ (posedge clk) begin if (init) count = 8’b10000000; else count = {count[6:0], count[7]};endmodule
144
Modeling Memory•Synthesis tools are usually not very
efficient in synthesizing memory.Best modeled as a component. Instantiated in a design.
• Implementing memory as a two-dimensional register file is inefficient.
145
module memory_example (en, clk, adbus, dbus,
rw);
parameter N = 16; input en, rw, clk; input [N-1:0] adbus; output [N-1:0] dbus; ………… ROM Mem1 (clk, en, rw, adbus, dbus); …………endmodule
146
Modeling Tri-state Gates
module bus_driver (in, out, enable); input enable; input [0:7] in; output [0:7] out; reg [0:7] out;
always @ (enable or in) if (enable) out = in; else out = 8’bz;endmodule;
147
• Two types of FSMs Moore Machine
Mealy Machine
Modeling Finite State Machines
NSLogic F/F O/p
LogicPSNS
NSLogic F/F
O/pLogicPSNS
148
Moore Machine : Example 1• Traffic Light Controller
Simplifying assumptions made Three lights only (RED, GREEN,
YELLOW) The lights glow cyclically at a fixed rate
•Say, 10 seconds each•The circuit will be driven by a clock of appropriate frequency
clkREDGREEN
YELLOW
149
module traffic_light (clk, light); input clk; output [0:2] light; reg [0:2] light; parameter S0=0, S1=1, S2=2; parameter RED=3’b100, GREEN=3’b010, YELLOW=3’b001; reg [0:1] state; always @ (posedge clk) case (state) S0: begin // S0 means RED light <= YELLOW; state <= S1; end
150
S1: begin // S1 means YELLOW
light <= GREEN; state <= S2; end S2: begin // S2 means GREEN light <= RED; state <= S0; end default: begin light <= RED; state <= S0; end endcaseendmodule
151
• Comment on the solution Five flip-flops are synthesized•Two for ‘state’
•Three for ‘light’ (outputs are also latched into flip-flops)
If we want non-latched outputs, we have to modify the Verilog code.
•Assignment to ‘light’ made in a separate ‘always’ block.
•Use blocking assignment.
152
module traffic_light_nonlatched_op (clk, light); input clk; output [0:2] light; reg [0:2] light; parameter S0=0, S1=1, S2=2; parameter RED=3’b100, GREEN=3’b010, YELLOW=3’b001; reg [0:1] state; always @ (posedge clk) case (state) S0: state <= S1; S1: state <= S2; S2: state <= S0; default: state <= S0; endcase
153
always @ (state) case (state) S0: light = RED; S1: light = YELLOW; S2: light = GREEN; default: light = RED; endcaseendmodule
154
Moore Machine: Example 2• Serial parity detector
x
clkz
EVEN ODD
x=1x=0 x=0
x=1
= 0, for even 1, for odd
155
module parity_gen (x, clk, z); input x, clk; output z; reg z; reg even_odd; // The machine state parameter EVEN=0, ODD=1;
always @ (posedge clk) case (even_odd) EVEN: begin z <= x ? 1 : 0; even_odd <= x ? ODD : EVEN; end
156
ODD: begin z <= x ? 0 : 1; even_odd <= x ? EVEN :
ODD; end endcaseendmodule
• If no output latches need to be synthesized, we can follow the principle shown in the last example.
157
Mealy Machine: Example• Sequence detector for the pattern
‘0110’.xz
clk
S0 S1 S2 S3
1/0
0/0
0/0
0/0 1/0
1/0
1/0
0/1
158
// Sequence detector for the pattern ‘0110’
module seq_detector (x, clk, z) input x, clk; output z; reg z; parameter S0=0, S1=1, S2=2, S3=3; reg [0:1] PS, NS;
always @ (posedge clk) PS <= NS;
159
always @ (PS or x) case (PS) S0: begin z = x ? 0 : 0; NS = x ? S0 : S1; end; S1: begin z = x ? 0 : 0; NS = x ? S2 : S1; end; S2: begin z = x ? 0 : 0; NS = x ? S3 : S1; end;
160
S3: begin z = x ? 0 : 1; NS = x ? S0 : S1; end; endcaseendmodule
161
Example with Multiple Modules
• A simple example showing multiple module definitions.
Complementor
Adder
Parity Checker P
AB
add_sub
Bout
sumcarry
en
c_in
162
module complementor (Y, X, comp); input [7:0] X; input comp; output [7:0] Y; reg [7:0] Y;
always @ (X or comp) if (comp) Y = ~X; else Y = X;endmodule
163
module adder (sum, cy_out, in1, in2, cy_in);
input [7:0] in1, in2; input cy_in; output [7:0] sum; reg [7:0] sum; output cy_out; reg cy_out;
always @ (in1 or in2 or cy_in) {cy_out, sum} = in1 + in2 + cy_in;endmodule
164
module parity_checker (out_par, in_word);
input [8:0] in_word; output out_par;
always @ (in_word) out_par = ^ (in_word);endmodule
165
// Top level modulemodule add_sub_parity (p, a, b, add_sub); input [7:0] a, b; input add_sub; // 0 for add, 1 for
subtract output p; // parity of the result wire [7:0] Bout, sum; wire carry;
complementor M1 (Bout, B, add_sub); adder M2 (sum, carry, A, Bout, add_sub); parity_checker M3 (p, {carry, sum});endmodule
166
Memory Modeling Revisited
• Memory is typically included by instantiating a pre-designed module.
• Alternatively, we can model memories using two-dimensional arrays. Array of register variables.
•Behavioral model of memory. Mostly used for simulation purposes. For small memories, even for synthesis.
167
Typical Example
module memory_model ( …….. )
reg [7:0] mem [0:1023];
endmodule
168
How to Initialize memory
• By reading memory data patterns from a specified disk file.
Used for simulation. Used in test benches.
• Two Verilog functions are available:1. $readmemb (filename, memname, startaddr, stopaddr)
Data read in binary format.
2. $readmemh (filename, memname, startaddr, stopaddr)
Data read in hexadecimal format.
169
An Example
module memory_model ( …….. ) reg [7:0] mem [0:1023]; initial begin $readmemh (“mem.dat”,
mem); endendmodule
170
A Specific Example :: Single Port RAM with Synchronous
Read-Write module ram_1 (addr, data, clk, rd, wr, cs)
input [9:0] addr; input clk, rd, wr, cs;
inout [7:0] data;
reg [7:0] mem [1023:0]; reg [7:0] d_out;
assign data = (cs && rd) ? d_out ; 8’bz;
always @ (posedge clk)
if (cs && wr && !rd) mem [addr] = data;
always @ (posedge clk)
if (cs && rd && !wr) d_out = mem [addr];
endmodule
171
A Specific Example :: Single Port RAM with Asynchronous
Read-Write module ram_2 (addr, data, rd, wr, cs)
input [9:0] addr; input rd, wr, cs;
inout [7:0] data;
reg [7:0] mem [1023..0]; reg [7:0] d_out;
assign data = (cs && rd) ? d_out ; 8’bz;
always @ (addr or data or rd or wr or cs)
if (cs && wr && !rd) mem [addr] = data;
always @ (addr or rd or wr or cs)
if (cs && rd && !wr) d_out = mem [addr];
endmodule
172
A Specific Example :: ROM/EPROM
module rom (addr, data, rd_en, cs)
input [2:0] addr; input rd_en, cs;
output [7:0] data;
reg [7:0] data;
always @ (addr or rd_en or cs)
case (addr)
0: 22;
1: 45;
…………………
7: 12;
endcase
endmodule
173
Verilog Test Bench
•What is test bench?A Verilog procedural block which executes only once.
Used for simulation.Testbench generates clock, reset, and the required test vectors.
174
ModuleUnderTest
Test Bench
Comparelogic
Stimulus
175
How to Write Testbench?
• Create a test module 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 Various ways to do so.
• May include several simulator directives Like $display, $monitor, $dumpfile,
$dumpvars, $finish.
176
• $display Prints text or variables to stdout. Syntax same as “printf”.
• $monitor Similar to $display, but prints the value whenever
the value of some variable in the given list changes.
• $finish Terminates the simulation process.
• $dumpfile Specify the file that will be used for storing the
waveform.
• $dumpvars Starts dumping all the signals to the specified file.
177
Repetition• // for loop
for(i = 0; i < 10; i = i + 1) begin$display(“i = %d", i); end
• //while loopi = 0;while(i < 10) begin
$display(“i = %d", i);i = i + 1;
end • // repeat loop
repeat (5) //repeats the block 5 times,begin
$display(“i = %d", i);i = i + 1;
end
178
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
always
#10 clk = !clk;
endmodule
179
Testbench: More Complete Version
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
always
#10 clk = !clk;
contd..
180
initial
begin
$dumpfile (“shifter.vcd”);
$dumpvars;
end
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
181
A Complete Examplemodule testbench;
wire w1, w2, w3;
xyz m1 (w1, w2, w3);
test_xyz m2 (w1, w2, w3);
endmodule
module xyz (f, A, B);
input A, B; output f;
nor #1 (f, A, B);
ndmodule
contd..
182
module test_xyz (f, A, B);
input f;
output A, B;
reg A, B;
initial
begin
$monitor ($time, “A=%b”, “B=%b”, f=%b”,
A, B, f);
#10 A = 0; B = 0;
#10 A = 1; B = 0;
#10 A = 1; B = 1;
#10 $finish;
end
endmodule
183
Test Benchmodule <test module name> ;// Data type declaration// Instantiate module ( call the
module that is going to be tested)// Apply the stimulus// Display resultsendmodule
184
Test Bench Examplemodule test_my_nand;
// Test bench to test half adder reg A, B; wire s, cOut;
Add_half test( s, cOut, A, B ); // instantiate my_NAND.
initial begin // apply the stimulus, test data
A = 1'b0; B = 1'b0;#100 A = 1'b1; // delay one simulation cycle, then
change A=>1. #100 B = 1'b1;
#100 A = 1'b0; end
initial #500 $finish;
initialbegin
// setup monitoring //$monitor("Time=%0d a=%b b=%b out1=%b",
$time, A, B, F); endendmodule
185
Logic Synthesis• Verilog is used in two ways
Model for discrete-event simulationSpecification for a logic synthesis system
• Logic synthesis :Converts a subset of the Verilog language into an efficient netlist
One of the major breakthroughs in designing logic chips in the last 20 years
• Most chips are designed using at least some logic synthesis
186
Logic Synthesis•Takes place in two stages:
Translation of Verilog source to a netlist
Optimization of the resulting netlist to improve speed and area•Most critical part of the process
•Algorithms very complicated
187
Simulation-synthesis Mismatches
• Many possible sources of conflict• Synthesis ignores delays (e.g., #10), but
simulation behavior can be affected by them• Simulator models X explicitly, synthesis
doesn’t• Behaviors resulting from shared-variable-like
behavior of regs is not synthesized always @(posedge clk) a = 1; New value of a may be seen by other @(posedge
clk) statements in simulation, never in synthesis
Practice Problem 1•Design an encoder
that encodes 16 input lines into a 4-bit binary output.
EncoderEncoder in
Binary Out
Enable
0000 0000 0000 0010 10000 0000 0000 0100 20000 0000 0000 1000 30000 0000 0001 0000 40000 0000 0010 0000 50000 0000 0100 0000 60000 0000 1000 0000 70000 0001 0000 0000 80000 0010 0000 0000 9 0000 0100 0000 0000 100000 1000 0000 0000 11 0001 0000 0000 0000 120010 0000 0000 0000 130100 0000 0000 0000 141000 0000 0000 0000 15
Solution• module encoder( binary_out , encoder_in ,
enable)
• //-----------Output Ports-------------
• output [3:0] binary_out ;
• //-----------Input Ports---------------
• input enable ; input [15:0] encoder_in ;
• //------------Internal Variables--------
• reg [3:0] binary_out ;
• always @ (enable or encoder_in) • begin binary_out = 0;
if (enable) • begin
– if (binary_in ==1) begin encoder_out = 16'h0002; end – if (binary_in ==2) begin encoder_out = 16'h0004; end– if (binary_in ==3) begin encoder_out = 16'h0008; end – if (binary_in ==4) begin encoder_out = 16'h0010; end – if (binary_in ==5) begin encoder_out = 16'h0020; end – if (binary_in ==6) begin encoder_out = 16'h0040; end – if (binary_in ==7) begin encoder_out = 16'h0080; end – if (binary_in ==8) begin encoder_out = 16'h0100; end – if (binary_in ==9) begin encoder_out = 16'h0200; end – if (binary_in ==10) begin encoder_out = 16'h0400; end – if (binary_in ==11) begin encoder_out = 16'h0800; end – if (binary_in ==12) begin encoder_out = 16'h1000; end – if (binary_in ==13) begin encoder_out = 16'h2000; end – if (binary_in ==14) begin encoder_out = 16'h4000; end – if (binary_in ==15) begin encoder_out = 16'h8000; end
• end end
• endmodule
Practice Problem 2• Design an decoder
that encodes 16 input lines into a 4-bit binary output using case stmt.
EncoderBinary inEncoder
Out
Enable
1 0000 0000 0000 0010 2 0000 0000 0000 0100 3 0000 0000 0000 1000 4 0000 0000 0001 0000 5 0000 0000 0010 0000 6 0000 0000 0100 0000 7 0000 0000 1000 0000 8 0000 0001 0000 0000 9 0000 0010 0000 0000 10 0000 0100 0000 0000 11 0000 1000 0000 0000 12 0001 0000 0000 0000 13 0010 0000 0000 0000 14 0100 0000 0000 0000 15 1000 0000 0000 0000
Solution• module encoder(encoder_out , binary_in ,
enable)
• //-----------Output Ports-------------
• output [15:0] encoder_out;
• //-----------Input Ports---------------
• input enable ; input [3:0] binary_in;
• //------------Internal Variables--------
• reg [3:0] binary_in ;
• always @ (enable or encoder_in) • begin binary_out = 0;
if (enable) • begin
– if (e_in == 16'h0002) begin binary_out = 1; end – if (encoder_in == 16'h0004) begin binary_out = 2; end– if (encoder_in == 16'h0008) begin binary_out = 3; end – if (encoder_in == 16'h0010) begin binary_out = 4; end – if (encoder_in == 16'h0020) begin binary_out = 5; end – if (encoder_in == 16'h0040) begin binary_out = 6; end – if (encoder_in == 16'h0080) begin binary_out = 7; end – if (encoder_in == 16'h0100) begin binary_out = 8; end – if (encoder_in == 16'h0200) begin binary_out = 9; end – if (encoder_in == 16'h0400) begin binary_out = 10; end – if (encoder_in == 16'h0800) begin binary_out = 11; end – if (encoder_in == 16'h1000) begin binary_out = 12; end – if (encoder_in == 16'h2000) begin binary_out = 13; end – if (encoder_in == 16'h4000) begin binary_out = 14; end – if (encoder_in == 16'h8000) begin binary_out = 15; end
• end end
• endmodule
194
References – Cadence Design Systems, Inc., Verilog-XL
Reference Manual.
– Ciletti, Michael D., Starting Guides to Verilog 2001, Prentice Hall 2004
– http://www.eg.bucknell.edu/~cs320/Fall2003/verilog.html
– http://www.verilog.net/index.html
– http://www.eecs.berkeley.edu/~culler
– http://www-inst.eecs.berkeley.edu/~cs150