Verilog

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 194

Embedded Systems: HDL

(Lect 9)
Dr. RAJIB MALL
Professor Department Of Computer Science & Engineering IIT Kharagpur.
03/08/10 1

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.
2

Application Areas of HDL


System Specification HW/SW Partition Hardware Spec ASIC FPGA PLD Std Parts Boards & Systems Software
Suitable for all levels Behavioral level Not suitable

Softwre Spec

Basic Limitation of HDL


Description of digital systems only

Abstraction Levels in HDLs


Behavioral RTL Gate Layout (VLSI)
5

Our focus

Main Language Concepts (i)


Concurrency

Structure

Main Language Concepts (ii)


Procedural Statements

Time
7

Why use HDL? 1


When HDL was first developed:
Most logic simulators operated on netlists

Netlist:
List of gates and how theyre connected A natural representation of a digital logic circuit

Not a very convenient way to express designs, simulate, debug

Why use HDL? 2


Text-based Allows simulation before building circuit Can be compiled (synthesized) into logic circuit Much easier to write test benches
9

Why use HDL? 3


More abstract models of circuits
Easier to write Simulates faster

More flexible Provides sequencing A major par of Verilogs success:


It allowed both the model and the testbench to be described together
10

How HDL Is Used?


Design written in HDL Simulated to death to check functionality Synthesized (netlist generated) Static timing analysis to check timing

11

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.


12

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.
13

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.


14

Verilog Compared to VHDL


VHDL
 Provides some high-level constructs not available in Verilog:
E.g. user defined types, configurations

Verilog
 Provides comprehensive support for low-level digital design.  Not available in native VHDL
E.g. Range of type definitions and supporting functions (called packages).
15

Verilog Compared to VHDL


Verilog and VHDL are comparable languages VHDL has a slightly wider scope
 System-level modeling  Fewer 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 dont fit on slides
16

Design Methodology

17

Two Main Components of Verilog


Behavior
Concurrent, event-triggered processes

Structure:
Wires, interconnection, etc.
18

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.

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.
20

Basic Syntax of Module Definition


module module_name (list_of_ports); input/output declarations local net declarations Parallel statements endmodule

21

Example 1 :: Simple AND gate


module simpleand (f, x, y); input x, y; output f; assign f = x & y; endmodule

22

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
23

Verilog Full Adder


module full_adder_v(x, y, z, s, c); input x, y, z; Mixing structural and output s, c; behaviorial code. half_adder_v HA1(x, y, hs, hc), HA2(hs, z, s, tc); assign c = tc | hc; endmodule
24

Four-Bit Adder
module 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;
Look at connections between adders

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

25

Behavioral Verilog
// 4-bit Adder: Behavioral Verilog module adder_4_b_v(A, B, C0, S, C4); input[3:0] A, B; Mixing structural and input C0; behaviorial code. output[3:0] S; output C4; Addition (unsigned) assign {C4, S} = A + B + C0; endmodule Concatenation operation

Verilog Program Structure


Program composed of modules:
 Main module  Other modules

Each module takes parameters and returns values Let us write a Verilog program for
 (A NAND B) NAND (C NAND D)
27

First Verilog Program


module mynand(out,in1,in2);
 input in1,in2;  output out;  assign out=~(in1 & in2);

p q o o o

endmodule m 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

28

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
29

Taste of Verilog: Structural


module Add_half ( sum, c_out, a, b ); input a, b; Declaration of port output sum, c_out; modes wire c_out_bar; Declaration of internal
signal Module name Module ports

Verilog keywords

xor (sum, a, b); nand (c_out_bar, a, b); not (c_out, c_out_bar); endmodule

Instantiation of primitive gates a b c_out_bar c_out 30 sum

Taste of Verilog: Behaviorial


module Add_half ( sum, c_out, a, b ); input a, b; output sum, c_out; assign {c_out, sum} = a + b; endmodule
a b c_out_bar c_out
31

sum

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
32

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 33

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.
34

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)
35

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.

36

Nets
A Y B

wire Y; // declaration assign Y = A & B; wand Y; // declaration assign Y = A; assign Y = B; wor Y; // declaration assign Y = A; assign Y = B;

A Y B

dr A Y

tri Y; // declaration assign Y = (dr) ? A : z;


37

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.
38

Registers
Variables that store values Do not represent real hardware but ..
 .. real hardware can be implemented with registers

Only one type: reg


reg A, C; // declaration // assignments always done inside a procedure A = 1; C = A; // C gets the logical value 1 A = 0; // C is still 1 C = 0; // C is now 0 39

Nets and Registers


Wires and registers can be bits or arrays wire a; tri [15:0] dbus; tri #(5,4,8) b; reg [-1:4] vec; trireg (small) q; // Simple wire // 16-bit tristate bus // Wire with delay // Six-bit register // Wire stores a small charge

integer imem[0:1023]; // Array of 1024 integers reg [31:0] dcache[0:63];// A 32-bit memory
40

Vectors
Represent buses
wire [3:0] busA; reg [1:4] busB; reg [1:0] busC;

Left number is MS bit Slice management


busC = busA[2:1];

busC[1] = busA[2]; busC[0] = busA[1];

Vector assignment (by position!!)


busB[1] = busA[3];

busB = busA;

busB[2] = busA[2]; busB[3] = busA[1]; busB[4] = busA[0];

41

Integer & Real Data Types Declaration


integer i, k; real r;

Use as registers (inside procedures)


i = 1; // assignments occur inside procedure r = 2.9; k = r; // k is rounded to 3

Integers are not initialized!! Reals are initialized to 0.0


42

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


43

Arrays (i)
Syntax
integer count[1:5]; // 5 integers reg var[-15:16]; // 32 1-bit regs reg [7:0] mem[0:1023]; // 1024 8-bit regs

Accessing array elements


 Entire element: mem[10] = 8b 10101010;  Element subfield (needs temp storage): reg [7:0] temp; .. temp = mem[10]; var[6] = temp[2];

44

Arrays (ii)
Limitation: Cannot access array subfield or entire array at once
var[2:9] = ???; // WRONG!! var = ???; // WRONG!!

No multi-dimentional arrays
reg var[1:10] [1:100]; // WRONG!!

Arrays dont work for the Real data type


real r[1:10]; // WRONG !!
45

Verilog Operators
Arithmetic operators

*, /, +, -, %
Logical operators

! && ||

logical negation logical AND logical OR

Relational operators

>, <, >=, <=, ==, !=


Bitwise operators
~, &, |, ^, ~^
46

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>


47

Bitwise Operators
~ & | ^ ~| ~& ^~ or ~^ NOT AND OR XOR NOR NAND XNOR
48

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]};
49

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.

50

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

Other differences:
In arithmetic expressions,
 An integer is treated as a 2s 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.
52

Modules and Instances


Basic structure of a Verilog module: module mymod(output1, output2, input1, input2); output output1; Verilog convention lists outputs first output [3:0] output2; input input1; input [2:0] input2; 53 endmodule

Instances of look like

Instantiating a Module
module mymod(y, a, b);

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

54

Gate-level Primitives
Verilog provides the following: and or xor buf bufif0 bifif1 nand nor xnor not notif0 notif1 logical AND/NAND logical OR/NOR logical XOR/XNOR buffer/inverter Tristate with low enable Tristate with high enable
55

Delays on Primitive Instances


Instances of primitives may include delays buf b1(a, b); buf #3 b2(c, d); buf #(4,5) b3(e, f); buf #(3:4:5) b4(g, h); // Zero delay // Delay of 3 // Rise=4, fall=5 // Min-typ-max
56

User-Defined Primitives
Way to define gates and sequential elements using a truth table
Often 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
57

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).
58

A Carry Primitive
primitive carry(out, a, b, c); output out; Always have exactly input a, b, c; one output table Truth table may 00? : 0; include dont-care (?) 0?0 : 0; entries ?00 : 0; 11? : 1; 1?1 : 1; ?11 : 1; endtable endprimitive

59

A Sequential Circuit
Primitive dff( q, clk, data); output q; reg q; input clk, data; table // clk data q new-q // Latch a 0 (01) 0 : ? : 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 stable endtable endprimitive
60

Continuous Assignment
Another way to describe combinational function Convenient for logical or datapath specifications
Define bus widths

wire [8:0] sum; wire [7:0] a, b; wire carryin;

Continuous assignment: permanently sets the value of sum to be a+b+carryin Recomputed when a, b, or carryin changes
61

assign sum = a + b + carryin;

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
62

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 . */
63

Numbers in Verilog
<size><radix> <value>
No of bits Binary Octal Decimal Hex b or B o or O d or D h or H Consecutive chars 0-f, x, z

 8h ax = 1010xxxx  12o 3zx7 = 011zzzxxx111


64

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.

65

Example : x = 347 // decimal number

Numbers

x = 4b101 // 4- bit binary number 0101 x = 6o12 // 6-bit octal number x = 16h87f7 // 16-bit hex number h87f7 x = 6b101010

String in double quotes this is an introduction


66

Numbers in Verilog
You can insert _ for readability
 12b 000_111_010_100  12b 000111010100 Represent the same number  12o 07_24

Bit extension
 MS bit = 0, x or z extend this
4b x1 = 4b xx_x1

 MS bit = 1 zero extension


4b 1x = 4b 00_1x
67

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

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 = 2b00, down = 2b01, steady = 2b10;


69

Four-valued Data
Verilogs 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 wires value

X
 Models when the simulator cant 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
70

Logic Values
The common values used in modeling hardware are:
0 1 x z :: :: :: :: Logic-0 or FALSE Logic-1 or TRUE Unknown (or dont care) High impedance

Initialization:
 All unconnected nets set to z  All register variables set to x
71

Four-valued Logic
Logical operators work on threevalued logic
0
0 1 X Z 0 0 0 0

1
0 1 X X

X
0 X X X

Z
0 X X X Output X if both inputs are gibberish Output 0 if one input is 0

72

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&1 1&1 1&x 0 0 1 x 0&x 1&z z&x x
73

0 x

Primitive Gates
Primitive logic gates (instantiations):
and nand or nor xor xnor not buf G (out, in1, in2); G (out, in1, in2); G (out, in1, in2); G (out, in1, in2); G (out, in1, in2); G (out, in1, in2); G (out1, in); G (out1, in);
74

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.
75

`timescale 1 ns / 1ns module exclusive_or (f, a, b); input a, b; output f; wire t1, t2, t3; nand #5 m1 (t1, a, b); and #5 m2 (t2, a, t1); and #5 m3 (t3, t1, b); or #5 m4 (f, t2, t3); endmodule
76

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. 77

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 The synthesis system f1 = ~(A & B); will generate a wire for f1 f2 = f1 ^ C; end endmodule
78

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 assign f2 assign f2 assign f1 endmodule = = = = x[4:0] & y[4:0]; x[2] | ~f1[3]; ~& x; f2 ? x[9:5] : x[4:0];
79

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

80

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 1b0 Boolean true is equivalent to 1b1.
81

Some Valid Statements


assign outp = (p == 4b1111); if (load && (select == 2b01)) . assign a = b >> 1; assign a = b << 3; assign f = {a, b}; assign f = {a, 3b101, b}; assign f = {x[2], y[0], a}; assign f = { 4{a} }; // replicate four times assign f = {2b10, 3{2b01}, x};
82

Description Styles in Verilog


Two different styles of description:
1. Data flow
Continuous assignment

2. Behavioral
Procedural assignment  Blocking Nonblocking
83

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.
84

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.
85

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
86

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
87

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 operator
generates a MUX
88

Embedded Systems: HDL


(Lect 10)
Dr. RAJIB MALL
Professor Department Of Computer Science & Engineering IIT Kharagpur.
03/08/10 89

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).
90

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
91

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
92

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.
93

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.
94

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

Execution Flow

Procedural assignments: Y must be reg !!

95

Events (i)

always @(signal1 or signal2 or ..) begin .. execution triggers every end time any signal changes always @(posedge clk) begin .. end

execution triggers every time clk changes from 0 to 1

always @(negedge clk) begin .. end

execution triggers every time clk changes from 1 to 0


96

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

97

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 regs


 Two possible sources for data

LHS must be a reg


 Primitives or cont. assignment may set wire values
98

Imperative Statements
if (select == 1) y = a; else y = b; case (op) 2b00: y = a + b; 2b01: y = a b; 2b10: y = a ^ b; default: y = hxxxx; endcase

99

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

100

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

101

Verilog supports four types of loops:


 while loop  for loop  forever loop  repeat loop

About Loop Statements

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. 102

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

103

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:  initialp they execute only once  always p they execute for ever (until
104

simulation finishes)

Example: Initial Block


module initial_example(); reg clk,reset,enable,data; initial begin The initial block is executed clk = 0; at time 0. reset = 0; Initial block just executes all the statements within enable = 0; begin and end statements. data = 0; end endmodule
105

Initial Blocks
Start execution at sim time zero and finish when their last statement executes
module nothing; initial $display(Im first); initial begin #50; $display(Really?); end endmodule
Will be displayed at sim time 0

Will be displayed at sim time 50

106

Always Blocks
Start execution at sim time zero and continue until sim finishes

107

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
Sequential statements

The @(event_expression) is required for both combinational and sequential logic descriptions.
108

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.). 109

Sequential Statements in Verilog


1. begin sequential_statements begin...end not required end if there 2. if (expression) is only 1 stmt. sequential_statement [else sequential_statement] 3. case (expression) expr: sequential_statement . default: sequential_statement endcase
110

4. forever sequential_statement 5. repeat (expression) sequential_statement 6. while (expression) sequential_statement 7. for (expr1; expr2; expr3) sequential_statement

111

8. # (time_value) Makes a block suspend for time_value time units. 9. @ (event_expression) Makes a block suspend until event_expression triggers.

112

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
113

// 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
114

// 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; end endmodule

115

module ALU_4bit (f, a, b, op); input [1:0] op; output [3:0] f; input [3:0] a, b; reg [3:0] f;

parameter ADD=2b00, SUB=2b01, MUL=2b10, DIV=2b11; always @ (a or b or op) case (op) ADD : f = a + b; SUB : f = a b; MUL : f = a * b; DIV : f = a / b; endcase endmodule
116

module priority_encoder (in, code); input [0:3] in; output [0:1] code; reg [0:1] code; always @ (in) case (1b1) input[0] : code = 2b00; input[1] : code = 2b01; input[2] : code = 2d10; input[3] : code = 2b11; endcase endmodule

117

module simple_counter (clk, rst, count); input clk, rst; output count; reg [31:0] count; always @(posedge clk) begin if (rst) count = 32b0; else count = count + 1; end endmodule
118

Example: 4-1 MUX in behavioral (1)


module mux4 (sel, A, B, C, D, Y); input [1:0] sel; // 2-bit control signal A input A, B, C, D; B output Y; C reg Y; // target of assignment D always @(sel or A or B or C or D) If (sel == 2b00) Y = A; else if (sel == 2b01) Y = B; Sel[1:0] else if (sel == 2b10) Y = C; else if (sel == 2b11) Y = D; endmodule

119

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) 2b00: Y = A; 2b01: Y = B; 2b10: Y = C; 2b11: Y = D; endcase endmodule
120

A B C D Y

Sel[1:0]

Example: 4-1 MUX in behavioral (3)


// 4-1 mux using case statement module mux4 (select, d, q); input [1:0] select; // 2-bit control signal input [3:0] d; output q; reg q; // target of assignment always @(select or d) case (select) 2b00: q = d[0]; 2b01: q = d[1]; 2b10: q = d[2]; 2b11: q = d[3]; endcase endmodule
121

Example: 4-1 MUX in structural


module 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

122

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

123

Examples
module half_adder(S, Behavioral edgeC, A, B); triggered DFF output S, C; module dff(Q, D, Clk);
input A, B; reg S,C; wire A, B; always @(A or B) begin S = A ^ B; C = A & B; end endmodule

output Q; input D, Clk; reg Q; wire D, Clk; always @(posedge Clk) Q = D; endmodule
124

Timing (i)
d initial begin #5 c = 1; #5 b = 0; #5 d = c; end c b 0 5 10 15

Time Each assignment is blocked by its previous one

125

Timing (ii)
d initial begin fork #5 c = 1; #5 b = 0; #5 d = c; join end c b 0 5 10 15

Time

Assignments are not blocked here

126

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
127

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 128 concurrently rather than sequentially.

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
129

A Flawed Shift Register


This doesnt work as youd 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 dont know which

130

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;
LHS updated only after all events for the current 131 instant have run Nonblocking rule: RHS evaluated when assignment runs

Nonblocking Can Behave Oddly


A sequence of nonblocking assignments dont communicate
a = 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
132

RHS of nonblocking taken from latches RHS of blocking taken from wires
a = 1; b = a; c = b; 1 a <= 1; b <= a; c <= b; c
133

Nonblocking Looks Like Latches


a 1 b c

a b

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.

134

The assignment to the target gets scheduled for the end of the simulation cycle.

Non-Blocking Assignment (using <=)

 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.
135

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

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

137

// 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
138

// 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
139

// 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
140

A Ring Counter Example


module ring_counter (clk, init, count); input clk, init; output [7:0] count; reg [7:0] count; always @ (posedge clk) begin if (init) count = 8b10000000; else begin count = count << 1; count[0] = count[7]; end end endmodule

141

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 = 8b10000000; else begin count <= count << 1; count[0] <= count[7]; end end endmodule

A Ring Counter Example (Modified-1)

142

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 = 8b10000000; else count = {count[6:0], count[7]}; endmodule
143

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 twodimensional register file is inefficient.
144

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

145

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 = 8bz; endmodule;

146

Modeling Finite State Machines


Two types of FSMs
 Moore Machine
NS NS F/F Logic PS O/p Logic

 Mealy Machine
NS NS F/F Logic PS O/p Logic
147

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 clk RED GREEN YELLOW
148

module traffic_light (clk, light); input clk; output [0:2] light; reg [0:2] light; parameter S0=0, S1=1, S2=2; parameter RED=3b100, GREEN=3b010, YELLOW=3b001; reg [0:1] state; always @ (posedge clk) case (state) S0: begin // S0 means RED light <= YELLOW; state <= S1; 149 end

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 endcase 150 endmodule

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.
151

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=3b100, GREEN=3b010, YELLOW=3b001; reg [0:1] state; always @ (posedge clk) case (state) S0: state <= S1; S1: state <= S2; S2: state <= S0; default: state <= S0; 152 endcase

always @ (state) case (state) S0: light S1: light S2: light default: light endcase endmodule

= = = =

RED; YELLOW; GREEN; RED;

153

Moore Machine: Example 2


Serial parity detector
x clk x=1 x=0
EVEN ODD

z = 0, for even 1, for odd

x=0

x=1
154

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

ODD: begin z <= x ? 0 : 1; even_odd <= x ? EVEN : ODD; end endcase endmodule If no output latches need to be synthesized, we
can follow the principle shown in the last example.

156

Sequence detector for the pattern 0110. x z


clk 1/0 1/0 S0 0/0 S1 0/0 1/0 0/0 0/1 S2 1/0

Mealy Machine: Example

S3

157

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

158

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;

159

S3: begin z = x ? 0 : 1; NS = x ? S0 : S1; end; endcase endmodule

160

Example with Multiple Modules


A simple example showing multiple module definitions. B A en
Complementor

Bout
c_in Adder

add_sub P
161

carry

sum

Parity Checker

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
162

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

163

module parity_checker (out_par, in_word); input [8:0] in_word; output out_par; always @ (in_word) out_par = ^ (in_word); endmodule

164

// Top level module module 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
165

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.
166

Typical Example
module memory_model ( .. )

reg [7:0] mem [0:1023];

endmodule

167

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.
168

An Example
module memory_model ( .. ) reg [7:0] mem [0:1023]; initial begin $readmemh (mem.dat, mem); end endmodule

169

A Specific Example ::
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;

Single Port RAM with Synchronous Read-Write

assign data = (cs && rd) ? d_out ; 8bz; always @ (posedge clk) if (cs && wr && !rd) mem [addr] = data; always @ (posedge clk) if (cs && rd && !wr) d_out = mem [addr]; endmodule
170

A Specific Example ::
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;

Single Port RAM with Asynchronous Read-Write

assign data = (cs && rd) ? d_out ; 8bz; 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
171

A Specific Example ::
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

ROM/EPROM

172

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.
173

Stimulus

Module Under Test

Compare logic

Test Bench

174

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.
175

$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.
176

// for loop for(i = 0; i < 10; i = i + 1) begin


$display(i = %d", i); end

Repetition

//while loop i = 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

177

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

178

Testbench:
module shifter_toplevel; reg clk, clear, shift; wire [7:0] data;

More Complete Version

shift_register S1 (clk, clear, shift, data); initial begin clk = 0; clear = 0; shift = 0; end always #10 clk = !clk; contd..

179

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

180

A Complete Example
module 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..
181

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

182

Test Bench
module <test module name> ; // Data type declaration // Instantiate module ( call the module that is going to be tested) // Apply the stimulus // Display results endmodule
183

module test_my_nand; // Test bench to test half adder reg A, B; wire s, cOut; Add_half initial begin

Test Bench Example


test( s, cOut, A, B ); // instantiate my_NAND. // 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; initial begin // setup monitoring //$monitor("Time=%0d a=%b b=%b out1=%b", $time, A, B, F); end endmodule
184

Logic Synthesis
Verilog is used in two ways
 Model for discrete-event simulation  Specification 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

185

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
186

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 doesnt 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
187

Practice Problem 1
Design an encoder that encodes 16 input lines into a 4bit binary output.
Encoder in 0000 0000 0000 0010 1 0000 0000 0000 0100 2 0000 0000 0000 1000 3 0000 0000 0001 0000 4 0000 0000 0010 0000 5 0000 0000 0100 0000 6 0000 0000 1000 0000 7 0000 0001 0000 0000 8 Binary 0000 0010 0000 0000 9 Out 0000 0100 0000 0000 10 0000 1000 0000 0000 11 0001 0000 0000 0000 12 0010 0000 0000 0000 13 0100 0000 0000 0000 14 1000 0000 0000 0000 15

Encoder

Enable

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 if if if if if if if if if if if if if if (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in (binary_in ==1) begin encoder_out = 16'h0002; end ==2) begin encoder_out = 16'h0004; end ==3) begin encoder_out = 16'h0008; end ==4) begin encoder_out = 16'h0010; end ==5) begin encoder_out = 16'h0020; end ==6) begin encoder_out = 16'h0040; end ==7) begin encoder_out = 16'h0080; end ==8) begin encoder_out = 16'h0100; end ==9) begin encoder_out = 16'h0200; end ==10) begin encoder_out = 16'h0400; end ==11) begin encoder_out = 16'h0800; end ==12) begin encoder_out = 16'h1000; end ==13) begin encoder_out = 16'h2000; end ==14) begin encoder_out = 16'h4000; end ==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.
Binary in 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 Encoder 9 0000 0010 0000 0000 Out 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

Encoder

Enable

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 if if if if if if if if if if if if if if (e_in == 16'h0002) begin binary_out = 1; end (encoder_in == 16'h0004) begin binary_out = 2; end (encoder_in == 16'h0008) begin binary_out = 3; end (encoder_in == 16'h0010) begin binary_out = 4; end (encoder_in == 16'h0020) begin binary_out = 5; end (encoder_in == 16'h0040) begin binary_out = 6; end (encoder_in == 16'h0080) begin binary_out = 7; end (encoder_in == 16'h0100) begin binary_out = 8; end (encoder_in == 16'h0200) begin binary_out = 9; end (encoder_in == 16'h0400) begin binary_out = 10; end (encoder_in == 16'h0800) begin binary_out = 11; end (encoder_in == 16'h1000) begin binary_out = 12; end (encoder_in == 16'h2000) begin binary_out = 13; end (encoder_in == 16'h4000) begin binary_out = 14; end (encoder_in == 16'h8000) begin binary_out = 15; end

end  end

endmodule

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
194

You might also like