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

System Verilog

Uploaded by

tranhoang230202
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

System Verilog

Uploaded by

tranhoang230202
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

INTRODUCTION TO SYSTEM

VERILOG

• THS. TRINH VU DANG NGUYEN


MỤC LỤC

1. Thế nào là Verilog hoặc


System Verilog khả tổng hợp 4. Digial system Design with
Verilog

2. Verilog Overview 5. Phụ Lục Verilog

3. System Verilog Overview

THS. TRINH VU DANG NGUYEN


1
Thế nào là Verilog hoặc
System Verilog khả
tổng hợp

THS. TRINH VU DANG NGUYEN


1. Giới thiệu

Verilog hoặc system verilog khả


tổng hợp ( Verilog for synthesis,
synthesizable Verilog) là một phần
(tập con) của ngôn ngữ Verilog và
System Verilog

THS. TRINH VU DANG NGUYEN


2. Khả tổng hợp là gì

Verilog khả tổng hợp là khả năng


của RTL (Register Transfer Level)
code viết bằng Verilog được phần
mềm tổng hợp (synthesis tool) hiểu
và biên dịch thành "phần cứng"
(netlist) hoạt động chính xác theo
những hành vi, chức năng mà RTL
code thể hiện. "Phần cứng" ở đây là
các thành phần logic như cổng OR,
AND, XOR, Flip-Flop, MUX, AOI, ...
gọi chung là các cell chuẩn
(standard cell) được tập hợp trong
một thư viện chung gọi là thư viện
tổng hợp (synthesis library) hay thư
viện công nghệ (technology library)
hay thư viện cell chuẩn (Standard
cell library).

THS. TRINH VU DANG NGUYEN


3. Ví dụ

module veriloghdl_1 (clk, data_in, data_out);


module tb;
//
//
//Interface //Interface
// //
input clk; reg clk;
input [3:0] data_in; reg [3:0] data_in;
output reg [3:0] data_out; wire [3:0] data_out;
veriloghdl_ex dut (clk, data_in, data_out);
initial begin initial begin
data_out[3:0] = 4'b0000; data_in = 4'b1010;
end clk = 0;
always @ (posedge clk) begin forever #10 clk = !clk;
end
data_out[3:0] <= data_in[3:0];
endmodule
end
endmodule

THS. TRINH VU DANG NGUYEN


3. Ví dụ
module veriloghdl_1 (clk, data_in, data_out);
module tb;
//
//
//Interface //Interface
// //
input clk; reg clk;
input [3:0] data_in; reg [3:0] data_in;
wire [3:0] data_out;
output reg [3:0] data_out;
veriloghdl_ex dut (clk, data_in, data_out);
initial begin initial begin
data_out[3:0] = 4'b0000; data_in = 4'b1010;
end clk = 0;
always @ (posedge clk) begin forever #10 clk = !clk;
end
data_out[3:0] <= data_in[3:0]; endmodule
end
endmodule

THS. TRINH VU DANG NGUYEN


3. Ví dụ module tb;
//
module veriloghdl_2 (clk, rst_n, data_in, data_out); //Interface
// //
//Interface reg clk;
// reg rst_n;
input clk; reg [3:0] data_in;
input rst_n; wire [3:0] data_out;
input [3:0] data_in; veriloghdl_ex dut (clk, rst_n, data_in, data_out);
output reg [3:0] data_out; initial begin
always @ (posedge clk, negedge rst_n) begin data_in = 4'b1010;
if (~rst_n) clk = 0;
data_out[3:0] <= 4'd0; forever #10 clk = !clk;
else end
data_out[3:0] <= data_in[3:0]; initial begin
end rst_n = 0;
endmodule #20
rst_n = 1;
end
endmodule

THS. TRINH VU DANG NGUYEN


2
Verilog Overview

THS. TRINH VU DANG NGUYEN


1. User Identifiers And Comments

o Formed from {[A-Z], [a-z], [0-9], _, $}, but ..


o .. can’t begin with $ or [0-9]
• myidentifier !
• m_y_identifier !
• 3my_identifier "
• $my_identifier "
• _myidentifier$ !
o Case sensitivity
• myid ¹ Myid

o // The rest of the line is a comment

o /* Multiple line comment


or block comment */

THS. TRINH VU DANG NGUYEN


2. Verilog Value set

o0 represents low logic level or false condition

o1 represents high logic level or true condition

ox represents unknown logic level (don’t care)

oz represents high impedance logic level (Hi-Z)

THS. TRINH VU DANG NGUYEN


3. Numbers in Verilog

<size>’<radix> <value> You can insert “_” for readability


12’b 000111010100
12’b 0001_1101_0100
No. of Binary ® b or B Consecutive chars 12’h 1d4
bits Octal ® o or O 0-f, x, z 12’b 000_111_010_100
Decimal ® d or D 12’o 07_24
Hexadecimal ® h or H

Bit extension
n 8’h ax = 1010xxxx MSB = 0, x or z Þ extend this
n 12’o 3zx7 = 011zzzxxx111 4’b x1 = 4’b xx_x1
4’b z1 = 4’b zz_z1
4’b 01 = 4’b 00_01
o If size is ommitted, it is interpreted as 32 bits MSB = 1 Þ zero extension
e.g. ‘d33 = 4’b 1x = 4’b 00_1x
0000_0000_0000_0000_0000_0000_0010_0001
o If radix is ommitted too .. decimal is assumed
e.g. 15 = <size>’d 15
12 THS. TRINH VU DANG NGUYEN
4. Net

A wire Y; // declaration
Y
B assign Y = A & B;
o Can be thought as hardware wires driven
by logic
wand Y; // declaration o Equal z (high impedance logic level)
assign Y = A; when unconnected
A assign Y = B; o Various types of nets
Y • wire
B • wand (wired-AND)
wor Y; // declaration • wor (wired-OR)
assign Y = A; • tri (tri-state)
assign Y = B;
o In following examples: Y is evaluated,
automatically, every time A or B changes
dr
tri Y; // declaration
A Y
assign Y = (dr) ? A : z;

THS. TRINH VU DANG NGUYEN


5. Registers

o Variables that store values


o Do not represent real hardware but ..
o .. real hardware can be implemented with registers
o Only one type: reg
• reg A, C; // declaration
// assignments are always done inside a procedure
• A = 1;
• C = A; // C gets the logical value 1
• A = 0; // A is 0 now, but C is still 1
• C = 0; // C is 0 now, and A is still 0
o Register values are updated explicitly!!

THS. TRINH VU DANG NGUYEN


11. Bitwise Operators
c = ~a; c = a & b;

• a = 4’b1010;
b = 4’b1100;
o & ® bitwise AND
o | ® bitwise OR
o ~ ® bitwise NOT
o ^ ® bitwise XOR
o ~^ or ^~ ® bitwise XNOR c = a ^ b;

o Operation on bit by bit basis

a = 4’b1010;
b = 2’b11;

15 THS. TRINH VU DANG NGUYEN


6. Vectors
• Represent buses
wire [3:0] busA;
reg [1:4] busB;
reg [1:0] busC;
• Left number is MSB
• Slice management
busC[1] = busA[2];
busC = busA[2:1]; Û
busC[0] = busA[1];

• Vector assignment (by position!!)


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

THS. TRINH VU DANG NGUYEN


7. Integer & Real Data Type

o Declaration
• integer i, k; //default 32-bit
• real r;
o Use as registers (inside procedures)
• i = 1; // assignments occur inside procedure
• r = 2.9;
• k = r; // k is rounded to 3
o Integers are not initialized!!
o Reals are initialized to 0.0

THS. TRINH VU DANG NGUYEN


8. Time Data Type

o Special data type for simulation time measuring


o Declaration
• time my_time;
o Use inside procedure
• my_time = $time; // get current sim time
o Simulation runs at simulation time, not real time

THS. TRINH VU DANG NGUYEN


9. Arrays
o 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 (2D array)

o An array of n 1-bit reg is not the same as an n-bit vector reg


n reg A[0:3];//4 1-bit array à column matrix
n reg [3:0]A;//4-bit vector à row matrix

o Accessing array elements


n Entire element: mem[10] = 8’b 10101010;
n Element subfield (needs temp storage):
reg [7:0] temp;
...
temp = mem[10]; //temp = 8’b 10101010;
var[6] = temp[2]; //var[6] = 0;
THS. TRINH VU DANG NGUYEN
10. Logical Operators

o && ® logical AND


o || ® logical OR
o ! ® logical NOT
o If any bit of operand is x or z, then the operand is tread as x
o Operands evaluated to ONE bit value: 0, 1 or x
o Result is ONE bit value: 0, 1 or x
A = 6; A && B ® 1 && 0 ® 0
B = 0; A || !B ® 1 || 1 ® 1
C = x; C || B ® x || 0 ® x

THS. TRINH VU DANG NGUYEN


12. Reduction and Shift Operators

o & ® AND
o | ® OR >> ® logical shift right
o ^ ® XOR << ® logical shift left
o ~& ® NAND
o ~| ® NOR Result is same size as first operand, always zero filled
o ~^ or ^~ ® XNOR a = 4’b1010;
...
o One multi-bit operand ® One single-bit result
d = a >> 2; // d = 0010
• a = 4’b1001; c = a << 1; // c = 0100
• ..
• c = |a; // c = 1|0|0|1 = 1

THS. TRINH VU DANG NGUYEN


12. Reduction and Shift Operators

o >>> ® arithmetic shift right


o <<< ® arithmetic shift left

o Result is same size as first operand


• <<< : zero filled (same as logical shift left)
• >>> : MSB extended
a = 4’b1010;
...
d = a >>> 2; // d = 1110
c = a <<< 1; // c = 0100

THS. TRINH VU DANG NGUYEN


13. Concatenation Operator

o {op1, op2, ..} ® concatenates op1, op2, .. to single number


o Operands must be sized !!
reg a;
reg [2:0] b, c;
..
a = 1’b 1;
b = 3’b 010;
c = 3’b 101;
catx = {a, b, c}; // catx = 1_010_101
caty = {b, 2’b11, a}; // caty = 010_11_1
catz = {b, 1}; // WRONG !!
o Replication ..
catr = {4{a}, b, 2{c}}; // catr = 1111_010_101101

THS. TRINH VU DANG NGUYEN


14. Relational Operators

o > ® greater than


o < ® less than
o >= ® greater or equal than
o <= ® less or equal than

o Result is one bit value: 0, 1 or x


1>0 ®1
’b1x1 <= 0 ®x
10 < z ®x
Note that: if any bit of operand is x or z, then the result is tread as x

THS. TRINH VU DANG NGUYEN


15. Equality Operators

o == ® logical equality
o != ® logical inequality
o === ® case equality
o !== ® case inequality

• 4’b 1z0x == 4’b 1z0x ® x


• 4’b 1z0x === 4’b 1z0x ® 1
• 4’b 1z0x != 4’b 1z0x ® x
• 4’b 1z0x !== 4’b 1z0x ® 0

THS. TRINH VU DANG NGUYEN


16. Conditional Operator

ocond_expr ? true_expr : false_expr


oLike a 2-to-1 mux ..

A
1
Y
B Y = (sel)? A : B;
0
sel

THS. TRINH VU DANG NGUYEN


17. Arithmetic Operators

o+, -, *, /, %
oIf any bit of operand is x or z, then the result is tread as x
oNegative registers:
o regs can be assigned negative but are treated as unsigned
reg [15:0] regA;
..
regA = -5’d12;// stored as 216-12 = 65524
regA/3 // evaluates to 21841

THS. TRINH VU DANG NGUYEN


17. Arithmetic Operators

• Negative integers:
• can be assigned negative values
• different treatment depending on base specification or not
reg [15:0] regA;
16-bit two’s complement of (-4)
integer intA;

regA = -12/3; //evaluates to 65532 because regA is unsigned


-4 intA = -12/3; //evaluates to -4 (no base spec)
(signed)
intA = -’d12/3; //evaluates to 1431655761 (base spec)

4294967284: 32-bit two’s complement of (-12)


o A register data type is seen as unsigned value and an integer date type is seen as a signed
value.
o An arithmetic operation on a register data type behaves differently than an arithmetic
operation on an integer date type. THS. TRINH VU DANG NGUYEN
18. Operator Precedence

sign

Use parentheses to
enforce the priority.

THS. TRINH VU DANG NGUYEN


19. Strings

• Implemented with regs:


reg [8*13:1] string_val; // can hold up to 13 chars
..
string_val = “Hello Verilog”;
string_val = “hello”; // MS Bytes are filled with 0
string_val = “I am overflowed”; // “I ” is truncated

• Escaped chars:
• \n newline
• \t tab
• %% %
• \\ \
• \“ “

THS. TRINH VU DANG NGUYEN


20. Module

module my_module(out1, .., inN);


in1 my_module out1
output out1, .., outM;
in2 out2
input in1, .., inN;

f
.. // declarations
inN outM
.. // description of f (maybe sequential)

endmodule

q Everything you write in Verilog must be inside a module exception: compiler directives

THS. TRINH VU DANG NGUYEN


20. Module

A S module half_adder(S, C, A, B);


half output S, C;
B adder C input A, B;

wire S, C, A, B;
A
S assign S = A ^ B;
B assign C = A & B; //assign C = A && B;
C
endmodule

o && ® logical AND o & ® bitwise AND


o || ® logical OR o | ® bitwise OR
o ! ® logical NOT o ~ ® bitwise NOT
o ^ ® bitwise XOR
o ~^ or ^~ ® bitwise XNOR
THS. TRINH VU DANG NGUYEN
20. Module
in1 A S I1 A S sum
half_adder half_adder
B ha1 C I2 B ha2 C I3
in2
full_adder cout

cin

module full_adder(sum, cout, in1, in2, cin);


output sum, cout;
input in1, in2, cin;

wire sum, cout, in1, in2, cin;


Module wire I1, I2, I3; Instance
name name
half_adder ha1(I1, I2, in1, in2);
half_adder ha2(sum, I3, I1, cin);

assign cout = I2 || I3;

endmodule

half_adder ha1(.S(I1), .C(I2), .A(in1), .B(in2));


half_adder ha2(.S(sum), .C(I3), .A(I1), .B(cin));

THS. TRINH VU DANG NGUYEN


20. Module

module
• Inputs reg or net net
Internal connection http://www.asic-world.com/verilog/syntax2.html
External connection

q Inputs : internally must always


module be of type net, externally the
inputs can be connected to a
reg or net net
• Outputs variable of type reg or net.
q Outputs : internally can be of
type net or reg, externally the
outputs must be connected to a
variable of type net.
module
q Inouts: internally or externally
net net must always be type net, can only
• Inouts be connected to a variable net
type.

34 THS. TRINH VU DANG NGUYEN


21. Dataflow Model ( Continuous Asignments)

• Syntax:
assign #del <id> = <expr>;

optional net type !!

• Where to write them:


• inside a module
• outside procedures(*)
• Properties:
• they all execute in parallel
• are order independent
• are continuously active

(*)Procedures = sections of code that we know they execute sequentially.

THS. TRINH VU DANG NGUYEN


22. Structural Model (Gate Level)

• Built-in gate primitives:


and, nand, nor, or, xor, xnor, buf, not, bufif0, bufif1,
notif0, notif1

• Usage:
nand (out, in1, in2); //2-input NAND without delay
and #2 (out, in1, in2, in3); //3-input AND with 2 t.u. delay
not #1 N1(out, in); //NOT with 1 t.u. delay and instance name
xor X1(out, in1, in2); //2-input XOR with instance name

• Write them inside module, outside procedures


half_adder module half_adder(S, C, A, B);
output S, C;
A input A, B;
S Assuming:
B wire S, C, A, B; • XOR: 2 t.u. delay
C • AND: 1 t.u. delay
xor #2 (S, A, B);
and #1 (C, A, B);

endmodule THS. TRINH VU DANG NGUYEN


23. Behavioral Model – Procedures
• Procedures = sections of code that we know they execute sequentially
• Procedural statements = statements inside a procedure, they execute
sequentially.
• e.g. another 2-to-1 mux implementation:
begin • Modules can contain any number of
if (sel == 0) procedures
Execution Procedural assignments:
Y = B; Y must be reg !! • Procedures execute in parallel (in respect to
Flow
else each other) and ..
Y = A;
end • .. can be expressed in two types of blocks:
• initial ® they execute only once
A
1 Dataflow model • always ® they execute for ever (until
Y assign Y = (sel)? A : B; simulation finishes)
B 0
Y must be wire !!
sel

THS. TRINH VU DANG NGUYEN


23.1 “Initial” Block

• Start execution at simulation time zero and finish


when their last statement executes
• Only used in test benches for simulation.
module nothing;

initial
$display(“I’m first”); Will be displayed
at sim time 0
initial
begin
#50; Will be displayed
$display(“Really?”); at sim time 50 t.u.
end
t.u. = time units
endmodule

THS. TRINH VU DANG NGUYEN


23.2. “Always” Block
• A always block contains a trigger list of signals (variables) which will cause the block to be
executed whenever a signal changes it’s value.
• Start execution at simulation time zero and continue until simulation finishes.
• Multiple always block operate in parallel, not in sequence or order.

THS. TRINH VU DANG NGUYEN


23.3. Events

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

always @(posedge clk)


begin execution triggers every
..
time clk changes
end
from 0 to 1

always @(negedge clk)


begin execution triggers every
.. time clk changes
end from 1 to 0
THS. TRINH VU DANG NGUYEN
23.3 Events

• wait (expr) Not synthesizable only used for testbench.


always begin execution loops every
wait (ctrl) time ctrl = 1 (level
#10 cnt = cnt + 1;
#10 cnt2 = cnt2 + 2;
sensitive timing control)
end

• e.g. Level triggered DFF ?

THS. TRINH VU DANG NGUYEN


Examples
• 3rd half adder implem. • Behavioral edge-triggered DFF
module half_adder(S, C, A, B); implementation
output S, C; module dff(Q, D, Clk);
input A, B; output Q;
input D, Clk;
reg S,C;
wire A, B; reg Q;
wire D, Clk;
always @(A or B)
begin always @(posedge Clk)
S = A ^ B; Q = D;
C = A && B;
end endmodule

endmodule

THS. TRINH VU DANG NGUYEN


Examples

always @(res or posedge clk) begin


res if (res) begin
a Y = 0;
b Y W = 0;
end
else begin
c W Y = a & b;
W = ~c;
clk end
end

THS. TRINH VU DANG NGUYEN


24. Timming don’t care (x)

d
initial begin
#5 c = 1; c
#5 b = 0;
#5 d = c; b
end
0 5 10 15
Time
Each assignment is
blocked by its previous one
d
initial begin
fork c
#5 c = 1;
#5 b = 0; b
#5 d = c;
join 0 5 10 15
end Time

Assignments are
THS. TRINH VU DANG NGUYEN
not blocked here
25. Procedural Statements: If

E.g. 4-to-1 mux:


module mux4_1(out, in, sel);
output out;
if (expr1) input [3:0] in;
in[3]
true_stmt1; input [1:0] sel; 11
in[2] 10
in[1] 01 out
reg out; in[0] 00
else if (expr2) wire [3:0] in;
wire [1:0] sel; 2
true_stmt2;
sel
.. always @(in or sel)
if (sel == 0) //2’b00
else out = in[0];
def_stmt; else if (sel == 1) //2’b01
out = in[1];
else if (sel == 2) //2’b10
qUsed for synthesizable code out = in[2];
else //2’b11
out = in[3];
endmodule

THS. TRINH VU DANG NGUYEN


26. Procedural Statements: Case

E.g. 4-to-1 mux:


module mux4_1(out, in, sel);
case (expr) output out;
input [3:0] in; in[3] 11
input [1:0] sel; in[2] 10 out
in[1] 01
item_1, .., item_n: stmt1; in[0] 00
reg out;
item_n+1, .., item_m: stmt2; wire [3:0] in; 2
.. wire [1:0] sel;
sel
default: def_stmt; always @(in or sel)
case (sel)
0: out = in[0];
endcase 1: out = in[1];
2: out = in[2];
qUsed for synthesizable code 3: out = in[3];
endcase
endmodule

THS. TRINH VU DANG NGUYEN


27. Procedural Statements: For
for (init_assignment; cond; step_assignment)
stmt;
E.g.
module count(Y, start);
output [3:0] Y;
input start;

reg [3:0] Y;
wire start;
integer i;

initial
Y = 0;

always @(posedge start)


//execute code while i < 3
for (i = 0; i < 3; i = i + 1)
#10 Y = Y + 1;
endmodule

q Can be used for synthesizable code but has generally been difficult to use.
THS. TRINH VU DANG NGUYEN
28. Procedural Statements: While

q Executes code as E.g.


module count(Y, start);
long as the specified output [3:0] Y;
condition is true. input start;

q Not synthesizable. reg [3:0] Y;


wire start;
integer i;
while (expr) stmt;
initial
Y = 0;

always @(posedge start) begin


i = 0;
while (i < 3) begin
#10 Y = Y + 1;
i = i + 1;
end
end
endmodule

THS. TRINH VU DANG NGUYEN


29. Procedural Statements: Repeat

qExecutes the following E.g.


module count(Y, start);
statement a fixed number of output [3:0] Y;
times. input start;

qOnly used for test benches. reg [3:0] Y;


qNot synthesizable. wire start;

initial
repeat (times) stmt; Y = 0;

always @(posedge start)


repeat (4) #10 Y = Y + 1;
endmodule
Can be either an
integer or a variable

THS. TRINH VU DANG NGUYEN


30. Procedural Statements: Forever

q Repeats a statement indefinitely Typical example:


until simulator stops. clock generation in test modules
q Only used for test benches, module test;
excellent for implementing reg clk; Tclk = 20 time units
clocks and repeating sequences.
q Not synthesizable. initial begin
clk = 0;
forever #10 clk = ~clk;
end
forever stmt;
other_module1 o1(clk, ..);
other_module2 o2(.., clk, ..);

endmodule
Executes until sim
finishes

THS. TRINH VU DANG NGUYEN


31. Mixed Model

q Code that contains various both structure and behavioral styles


module simple(Y, c, clk, res);
output Y;
input c, clk, res;

simple reg Y;
wire c, clk, res;
res wire n;
c n Y not(n, c); // gate-level
clk
always @(res or posedge clk)
if (res)
Y = 0;
else
Y = n;
endmodule

THS. TRINH VU DANG NGUYEN


32. Parameters

in[3:0] p_in[3:0]
out[1:0]
wu
Implelementation
without parameters
wd
clk
module dff4bit(Q, D, clk); module dff2bit(Q, D, clk);
output [3:0] Q; output [1:0] Q;
input [3:0] D; input [1:0] D;
input clk; input clk;

reg [3:0] Q; reg [1:0] Q;


wire [3:0] D; wire [1:0] D;
wire clk; wire clk;

always @(posedge clk) always @(posedge clk)


Q = D; Q = D;

endmodule endmodule

THS. TRINH VU DANG NGUYEN


32. Parameters

module top(out, in, clk);


output [1:0] out;
Implelementation input [3:0] in;
input clk;
without parameters (cont.)
wire [1:0] out;
wire [3:0] in;
wire clk;

in[3:0] p_in[3:0] wire [3:0] p_in; // internal nets


out[1:0] wire wu, wd;
wu
assign wu = p_in[3] & p_in[2];
assign wd = p_in[1] & p_in[0];
wd
clk dff4bit instA(p_in, in, clk);
dff2bit instB(out, {wu, wd}, clk);
dff4bit(Q, D, clk) // notice the concatenation!!

dff2bit(Q, D, clk) endmodule

THS. TRINH VU DANG NGUYEN


32. Parameters

module top(out, in, clk);


Implelementation output [1:0] out;
input [3:0] in;
with parameters input clk;
wire [1:0] out;
module dff(Q, D, clk); wire [3:0] in;
wire clk;
parameter WIDTH = 4;
output [WIDTH-1:0] Q; wire [3:0] p_in;
input [WIDTH-1:0] D; wire wu, wd;
input clk;
assign wu = p_in[3] & p_in[2];
reg [WIDTH-1:0] Q; assign wd = p_in[1] & p_in[0];
wire [WIDTH-1:0] D;
dff instA(p_in, in, clk);
wire clk; // WIDTH = 4, from declaration
always @(posedge clk) dff instB(out, {wu, wd}, clk);
Q = D; defparam instB.WIDTH = 2;
// We changed WIDTH for instB only
endmodule
endmodule

THS. TRINH VU DANG NGUYEN


3
SYSTEM VERILOG
OVERVIEW

THS. TRINH VU DANG NGUYEN


I. Combinational Logic Modeling – Mạch Tổ Hợp
1. Module và khai báo
Module Một design (thiết kế) gồm có ba thành phần
• Ngõ vô (input)
• Ngõ ra (output)
• Mạch logic (logic circuit)
Trong hình trên, có 2 input là a và b, 1 output là y, và mạch logic bên trong đơn giản chỉ là mạch xor. Mô tả mạch
này trong SystemVerilog như sau:

Khai báo Để khai báo một signal (tín hiệu), ta cần gán cho nó data type (dạng dữ liệu), trong SystemVerilog, data type
được sử dụng là logic.

logic có 4 giá trị: 0, 1, x, z. Data type này có thể tổng hợp được (synthesizable).
Keyword input và output báo cho compiler biết signal này là port (cổng) của design.
THS. TRINH VU DANG NGUYEN
2. Vector và Number
Vector Trong thực tế, dữ liệu không phải lúc nào cũng chỉ có 1 bit (1 dây signal) nhưng có nhiều, ví dụ 1 byte = 8
bit, hay signal có 8 dây. Khai báo một vector như sau:

1. Để giúp code trở nên dễ đọc và dễ debug về


sau, khuyến khích khai báo tín hiệu kèm hậu tố _i
hoặc _o tùy vô tín hiệu là input hoặc output.
2. Tên signal và tên module nên viết dưới dạng
lower_snake_case

o Với một vector signal được khai báo như sau: logic [7:0] signal
• Truy cập bit thứ i (0 ≤ i ≤ 7): signal[i]
• Truy cập một slice bit từ bit thứ i tới bit thứ j (0 ≤ i ≤ j ≤ 7): signal[j:i]

THS. TRINH VU DANG NGUYEN


2. Vector và Number
Number SystemVerilog quy định number dựa theo 4 yếu tố: độ dài, hệ số, dấu toán học, và giá trị.
1. Lưu ý độ dài number là số bit hay
xét theo binary, không phải số ký tự
2. Khi gán giá trị, phải để ý độ dài bit
đặng tránh khác nhau độ dài → bug

Trong SystemVerilog còn có một dạng gán giá trị như sau:

THS. TRINH VU DANG NGUYEN


3. Assign
Assign hay continuous assignment, tức gán liên tục, có thể hiểu như mạch tổ hợp ngoài thực tế, liên tục gán
giá trị sau khi “tính toán” từ ngõ vô lên ngõ ra.

Như tên của nó, continuous assignment, nên vị trí các dòng assign không ảnh hưởng tới kết quả sau cùng.

THS. TRINH VU DANG NGUYEN


3.1 Bitwise operators – Phép toán với bit
Bốn phép toán Boolean cơ bản:

Đối với vector, từng cặp bit tương ứng sẽ thực hiện phép toán bitwise với nhau.

THS. TRINH VU DANG NGUYEN


3.2 Reduciton operators – Phép toán rút gọn bit
SystemVerilog cung cấp Reduction operators cho những trường hợp cần lấy một bit từ một signal nhiều bit bằng
một phép toán.

3.3 Logic operators – Phép toán luận lý


Logical operators gần giống với bitwise operators, tuy nhiên nó chỉ tính toán giá trị true/false.

Nên sử dụng logical operators với giá trị đơn (1-bit), đặng xác định giá trị true/false (điều kiện).

THS. TRINH VU DANG NGUYEN


3.4 Comparison Operators – Phép toán so sánh
Những phép toán so sánh sau là synthesizable:

3.5 Shift operators – Phép toán dịch


Có ba phép toán dịch cơ bản mà SystemVerilog cung cấp:

THS. TRINH VU DANG NGUYEN


3.6 Arithmetic operators – Phép toán số học
Những phép toán trên phần nhiều là phép toán Boolean, ngoài ra phép toán số học cũng được SystemVerilog hỗ trợ.

1. Cần lưu tâm đến việc sử dụng Arithmetic operators, ví dụ cần có FPGA có hỗ trợ bộ nhân mới nên sử dụng phép *
khi assign.
2. Phép toán + và﹣thì hầu hết đều được hỗ trợ, nhưng các phép toán còn lại chỉ nên sử dụng đặng tính toán số học,
ví dụ các thông số, thay vì dùng trong assign.
3.7 Conditional operators – Phép toán điều kiện
Phép toán điều kiện là cách ngắn gọn thay vì tạo một bộ mux và sử dụng nó. Phép toán này có dạng giống như
trong C.

Condition phải mang giá trị true/false, nên cần đặt condition là signal đơn (1-bit), reduction operators, logical
operators, hoặc phép so sánh.
THS. TRINH VU DANG NGUYEN
3.8 Concatenate and replicate operators – Phép toán ghép và lặp số
Đối với việc tạo ra vector có số bit lớn, hoặc ghép nhiều signal lại thành một signal có số bit lớn.

Cần lưu tâm tới độ dài bit của signal khi


concatenate hoặc replicate

THS. TRINH VU DANG NGUYEN


4. Instantiation
Instantiation chỉ sự sử dụng một hay nhiều module khác đã tạo trong module hiện tại. Ví dụ:

THS. TRINH VU DANG NGUYEN


4. Instantiation
Có nhiều cách để khai báo/gán signals/data vô các ports của module, nhưng cách trên bảo đảm chúng được nối với
nhau cách chính xác.

THS. TRINH VU DANG NGUYEN


5. Parameter và localparam
Có hai cách để khai báo hằng số, parameter và localparam, điểm khác nhau ở chỗ parameter có thể được
gán trong lúc sử dụng module (instantiation), còn localparam chỉ sử dụng nội trong module đó.

THS. TRINH VU DANG NGUYEN


5. Parameter và localparam
o Mặc dù giá trị của DataSize được gán
vốn là 4 trong mux_two_nbit, khi
design_4 sử dụng mux_two_nbit, nó
thể thay đổi giá trị đó thành 8.

1. Tên parameter nên viết dưới dạng


UpperCamelCase
2. Tên localparam nên viết dưới dạng
ALL_CAPS

THS. TRINH VU DANG NGUYEN


6. Always_comb
Keyword này có thể được hiểu như việc thực hiện các statement liên tục. Nếu có nhiều phép gán, các statement
gần đặt trong begin và end. Đặt tên cho always_comb là không bắt buộc nhưng nên làm vì sẽ dễ debug hơn.

Bên trong always_comb, các phép gán này gọi là blocking


statement, vì statement sau sẽ sử dụng kết quả của
statement trước.

Ngoài blocking-statement, một vài synthesizable statements khác


cũng có thể được sử dụng như: if và case.
Nên sử dụng always_comb khi thiết kế combinational logic phức tạp.
Với bản chất của blocking statement, cần biết rõ thứ tự các khối logic
để nối dây cách chính xác.
THS. TRINH VU DANG NGUYEN
7. If Statement
Mạch mux có thể viết lại với if statement như sau:

THS. TRINH VU DANG NGUYEN


8. Case Statement
Nếu đã quen với switch trong C, case trong SystemVerilog cũng hoạt động tương tự.

Khi thiết kế cần bảo đảm sự đầy đủ của các giá trị case hoặc có default.

THS. TRINH VU DANG NGUYEN


9. Packed Array
o Một vector có thể hoạt động như một thanh ghi, ví dụ khai báo sau: logic [31:0] register; một thanh ghi 32
bit gồm có 4 byte, [31:24], [23:16], [15:8], [7:0].
o Tuy nhiên, việc truy cập từng byte nhỏ như trên sẽ trở nên khó khăn nếu truy cập thường xuyên.
o Xét cơ bản, array cũng tương tự như vector nhưng giúp việc truy cập những bit bên trong có dễ hơn.

o Lúc này việc truy cập các byte sẽ tiện hơn rất nhiều.

o Nhìn từ trái qua phải, register khai báo ở dạng array được hiểu như sau:
o Có thể hiểu vector như một bảng chỉ có 1
hàng, còn array là một bảng có nhiều hàng,
hoặc nhiều tập hợp bảng.

THS. TRINH VU DANG NGUYEN


10. Unpacked Array
Khi các vector không cần phải liên tiếp nhau như packed array, unpacked array cũng có thể được sử dụng.

11. Bài Tập


1. Thiết kế mạch combinational sau sử dụng assign và always_comb. (2 Ξles)

2. Thiết kế bộ tính toán đơn giản N bit với yêu cầu sau:
a. 3 ngõ vô data0, data1, và sel
b. 1 ngõ ra result
c. 4 phép toán (NONE, ADD, AND, OR)

THS. TRINH VU DANG NGUYEN


II. Sequential Logic Modeling – Mạch Tuần Tự
1. Always
always tương tự như always_comb nhưng nó không thực hiện các statement liên tục mà dựa vô sự thay đổi của
sensitivity list.

Trường hợp thứ 1 và 2 có thể hoạt động giống


always_comb nhưng không khuyến khích sử dụng thay
thế always_comb vì những điểm không hoàn hảo mà
trong đây không tiện đề cập.

THS. TRINH VU DANG NGUYEN


1. Always
Ngoài blocking statement thì trong always còn có thể chứa non-blocking statement. Giả sử trước thời điểm
xung clk kích cạnh lên, giá trị lúc đó của foo là 1, so sánh bốn kết quả sau sau khi xung clk kích cạnh lên.

Từ ví dụ trên, chỉ sử dụng non-blocking statement trong always, còn blocking statement thì trong
always_comb nhưng với sự thông hiểu datapath của mạch.

THS. TRINH VU DANG NGUYEN


2. Always_ff
Từ ví dụ trên, always có thể tạo ra D-FlipΟop như sau:

Tuy nhiên, để báo cho compiler biết ở đó người thiết kế muốn tạo ΟipΟop, always_Λ sẽ được sử dụng thay cho
always thông thường.

Luôn luôn sử dụng always_ff khi thiết kế mạch có liên quan tới flipflop hoặc register.

THS. TRINH VU DANG NGUYEN


3. Sequential Logic
o Mạch sequential cơ bản là mạch combinational nhưng có phần tử memory (nhớ), điều này khiến ngõ ra (thông
thường) sẽ thay đổi khi có sự thay đổi phần tử lái của memory (tín hiệu thay đổi (latch) hoặc xung clock). Ở đây
chỉ xét xung clock.
o Như vậy, một mạch sequential khi viết bằng SystemVerilog sẽ có dạng như sau:

THS. TRINH VU DANG NGUYEN


4. Bài Tập
1. Thiết kế DFF có port synchronous reset và enable.
2. Thiết kế mạch synchronizer sử dụng 2 DFF có dạng
như hình sau.

3. Thiết kế mạch counter 4-bit đếm lên nếu en = 1, ngõ ra counter cho biết giá trị hiện tại, ngõ ra này
luôn bằng 0 nếu rst = 0.

4. Thiết kế mạch ALU 8-bit với ngõ ra ổn định bằng DFF.


(Sử dụng lại module đã thiết kế ở câu 4 phần 1)

THS. TRINH VU DANG NGUYEN


II. Thiết Kế FSM – Máy Trạng Thái
1. Enum
Nếu như logic chỉ có hai trạng thái 0, 1 được sử dụng (bỏ qua x, z) thì nếu muốn tạo nhiều trạng thái, ví dụ đèn giao
thông có ba trạng thái RED, YELLOW, và GREEN. Ngoài việc khai báo 2 bit cho data, các giá trị RED, YELLOW,
GREEN còn cần phải được đặt là localparam ứng với giá trị tự đặt.

Tuy nhiên, SystemVerilog cung cấp một phương tiện giúp khai báo dễ hơn và dễ đọc hơn.
o typedef giúp tạo User-defined data type, logic[1:0] là storage
type, do ở đây có 3 giá trị nên cần 2 bit.
o Lúc này, light_e là một data type, có 3 giá trị RED, YELLOW,
và GREEN. Khai báo light có data type là light_e.
o Nếu không gán giá trị cho items trong lúc khai báo enum, khi
synthesize, compiler sẽ tự tìm đường tối ưu hơn hết cho
code.

THS. TRINH VU DANG NGUYEN


1. Enum
Như bài tập thiết kế ALU, ta có thể dùng enum cho tiện việc thảo code trong always_comb.

THS. TRINH VU DANG NGUYEN


2. FSM
FSM nhìn chung cũng chỉ như mạch sequential, bên dưới là một template cho việc code FSM.

THS. TRINH VU DANG NGUYEN


3. Bài Tập
1. Thiết kế FSM có giản đồ trạng thái như sau.

THS. TRINH VU DANG NGUYEN


4
Digital System Design
With Verilog

THS. TRINH VU DANG NGUYEN


1. Combinational Circuit

inputs
0

1
outputs

w0 y0
w1 y1
y2
En y3

1) Outputs only depend on inputs


2) Could include: gates, multiplexers, encoders, decoders, code
converters, comparators …
3) Verilog description: gates, logic expression, behavior

THS. TRINH VU DANG NGUYEN


1. Combinational Circuit

o Conditional operator
o if-else statement
o case statement
o casez, casex

THS. TRINH VU DANG NGUYEN


1.1 Conditional Operator

o Format
• Conditional_expression ? true_expression : false_expression
o Behavior
• If the conditional expression is 1 (true), then the value of true_expression is chosen;
• Otherwise, the value of false_expression is chosen
o Example
• A = (B<C) ? (D+5) : (D+2);
o Can be used in continuous assign and procedural statements
Behavior
w0
s s f f (s, w0 , w1 ) = s w0 + sw1
s f
w0 0 0 w0
f
w1 1 1 w1
Logic expression w1

Gates
THS. TRINH VU DANG NGUYEN
1.1 Conditional Operator

module mux2to1 (w0, w1, s, f); Conditional operator


input w0, w1, s; s in continuous assignment
output f;
w0 0
f
assign f = s ? w1 : w0; w1 1 Conditional operator
in procedural statement
endmodule
module mux2to1 (w0, w1, s, f);
input w0, w1, s;
output f;
reg f;

1) f is reg always @(w0 or w1 or s)


2) Include all input signals f = s ? w1 : w0;
3) Blocking assignment
endmodule

THS. TRINH VU DANG NGUYEN


1.1 Conditional Operator module mux4to1 (w0, w1, w2, w3, S, f);
input w0, w1, w2, w3;
s0 input [1:0] S;
s1 s1 s0 f
output f;
w0
w1
00 0 0 w0 assign f = S[1] ? (S[0] ? w3 : w2) : (S[0] ? w1 : w0);
01 0 1 w1
w2 10
f
1 0 w2 endmodule
w3 11
1 1 w3

s1
s0 s0
w0
s1
w0 0
w1 w1 1
f
0
w2 f
1

w2 0
w3
w3 1

THS. TRINH VU DANG NGUYEN


1.2 If-else
o Format
if (conditional_expression) statement;
else statement;
o Behavior
• If the conditional_expression is true, then the first statement is executed;
• Or else the second statement is executed.
o Used inside an always block, the statements are procedural.

module mux2to1 (w0, w1, s, f);


input w0, w1, s;
reg data type
output f;
reg f;
Include all input signals
always @(w0 or w1 or s)
if (s==0)
f = w0;
s
else s f

f = w1; w0 0
f
0 w0
w1 1 w1
endmodule 1

THS. TRINH VU DANG NGUYEN


1.2 If-else

module mux4to1 (w0, w1, w2, w3, S, f); module mux4to1 (W, S, f);
input w0, w1, w2, w3; input [0:3] W;
input [1:0] S; input [1:0] S;
output f; output f;
reg f; reg f;

always @(w0 or w1 or w2 or w3 or S) always @(W or S)


if (S == 2'b00) if (S == 0)
f = w0; f = W[0];
s0
else if (S == 2'b01) s1 else if (S == 1)
f = w1; w0 00
f = W[1];
else if (S == 2'b10) w1
w2
01
f else if (S == 2)
10
f = w2; w3 11 f = W[2];
else // S == 2'b11 else // S == 3
f = w3; f = W[3];

endmodule endmodule

THS. TRINH VU DANG NGUYEN


1.2 If-else
s0
s1

w0 module mux16to1 (W, S16, f);


M[0]
input [0:15] W;
w3 input [3:0] S16;
output f;
wire [0:3] M;
w4 s2
s3 M[1]
mux4to1 Mux1 (W[0:3], S16[1:0], M[0]);
w7
mux4to1 Mux2 (W[4:7], S16[1:0], M[1]);
f mux4to1 Mux3 (W[8:11], S16[1:0], M[2]);
mux4to1 Mux4 (W[12:15], S16[1:0],
w8
M[2] M[3]);
mux4to1 Mux5 (M[0:3], S16[3:2], f);
w11

M[3]
endmodule
w12

w15

A 16-to-1 multiplexer.
THS. TRINH VU DANG NGUYEN
1.3. Case Statement
• Format module mux4to1 (W, S, f); s0
s1 s1 s0 f
input [0:3] W;
case (expression) w0 00 0 0 w0
input [1:0] S; w1 01
f 0 1 w1
alternative1: statement; output f;
w2
w3
10 1 0 w2
11 w3
1 1
alternative2: statement; reg f;
… s1
alternativej: statement; always @(W or S) s0
case (S)
[default: statement;]
0: f = W[0];
endcase 1: f = W[1]; w0 0

or binary numbers 2: f = W[2]; w1 1

1) Many possible alternatives e.g. 2’b00, etc. 3: f = W[3]; 0


2) Expression and each alternative are endcase f
1
compared bit by bit.
3) If there is a match, the statement is endmodule w2 0
executed w3 1
4) If the alternatives do not cover all
possibilities, default should be
included. Otherwise, a sequential
circuit will be generated.
THS. TRINH VU DANG NGUYEN
1.3. Case Statement En w1 w0 y0 y1 y2 y3
w0 y0
1 0 0 1 0 0 0
w1 y1
module dec2to4 (W, En, Y); 1 0 1 0 1 0 0
y2
Concatenate operator 1 1 0 0 0 1 0
input [1:0] W; 1 1 1 0 0 0 1 En y3
input En; Default for En=0
0 x x 0 0 0 0
output [0:3] Y; (a) Truth table (b) Graphical symbol
reg [0:3] Y;
Truth table
always @(W or En) En w1 w0 y0 y1 y2 y3
case ({En, W})
1 0 0 1 0 0 0
3'b100: Y = 4'b1000; 1 0 1 0 1 0 0
3'b101: Y = 4'b0100; 1 1 0 0 0 1 0
3'b110: Y = 4'b0010; 1 1 1 0 0 0 1
0 x x 0 0 0 0
3'b111: Y = 4'b0001;
default: Y = 4'b0000;
endcase
endmodule

THS. TRINH VU DANG NGUYEN


1.3. Case Statement

module dec2to4 (W, En, Y,);


En w1 w0 y0 y1 y2 y3
input [1:0] W;
1 0 0 1 0 0 0 input En;
1 0 1 0 1 0 0 output [0:3] Y;
1 1 0 0 0 1 0 reg [0:3] Y;
1 1 1 0 0 0 1
0 x x 0 0 0 0 always @(W or En)
(a) Truth table begin
if (En == 0)
Y = 4'b0000;
else
w0 y0 case (W)
w1 y1 0: Y = 4'b1000;
y2 1: Y = 4'b0100;
En y3 2: Y = 4'b0010;
3: Y = 4'b0001;
endcase
(b) Graphical symbol end

endmodule

THS. TRINH VU DANG NGUYEN


1.3. Case Statement
module dec4to16 (W, En, Y);
input [3:0] W;
input En;
output [0:15] Y;
wire [0:3] M;

dec2to4 Dec1 (W[3:2], M[0:3], En);


dec2to4 Dec2 (W[1:0], Y[0:3], M[0]);
dec2to4 Dec3 (W[1:0], Y[4:7], M[1]);
dec2to4 Dec4 (W[1:0], Y[8:11], M[2]);
dec2to4 Dec5 (W[1:0], Y[12:15], M[3]);

endmodule

module dec2to4 (W, En, Y);


input [1:0] W;
input En;
output [0:3] Y;
reg [0:3] Y;
……..
……..
endmodule

THS. TRINH VU DANG NGUYEN


1.4. Case, Casez and Casex
o case : bit-by-bit comparison {0, 1, x, z} à can detect x and z
Example: 4’b01xz only matches 4’b01xz; 4’b0110 does not match 4’b01xx in a case
o casez: treat all z (or ?) as 0, 1, x, z module priority (W, Y, z);
Example: 4’b0110 matches 4’b01zz, but not 4’b01xz input [3:0] W;
o casex: treat all z (or ?) and x (or ?) as 0, 1, x, z output [1:0] Y;
Example: 4’b0110 matches 4’b01xx and also 4’b01xz output z;
reg [1:0] Y;
reg z;

always @(W)
begin
z = 1;
casex(W)
x x 4'b1xxx: Y = 3;
4'b01xx: Y = 2;
4'b001x: Y = 1;
4'b0001: Y = 0;
default: begin
z = 0;
Y = 2'bx;
x: don’t care end
endcase
end
THS. TRINH VU DANG NGUYEN
endmodule
2. Sequential Circuit Blocks

o Edge-sensitive always block


o Verilog for latch
o Verilog for flip-flops
o Blocking and Nonblocking assignments
o Verilog for asyn and syn reset
o Verilog for registers
o Shift register
o Counter
o Finite State Machines (FSM)

THS. TRINH VU DANG NGUYEN


2.1 Always block (overview)
o Level-sensitive always block
• always @ (signal1 or signal2)
• Used for combinational circuits and Latches
o Edge-sensitive always block
• always @ (posedge clk)
–Response to positive edge of clk signal
• always @ (negedge clk)
–Response to negative edge of clk signal
• Used for sequential circuits and flip-flops
Clk D Q( t + 1 )
0 x Q( t )
module D_latch (D, Clk, Q);
module flipflop (D, Clock, Q); input D, Clk;
1 0 0
D Q input D, Clock; 1 1 1 output Q;
output Q; reg Q;
Clock Q reg Q; always @(D or Clk)
always @(posedge Clock) if (Clk)
Sensitivity list contains only Clock Q = D; D Q Q = D;
endmodule endmodule
Clk Q
No else clause
Sensitivity list should include D and Clk

THS. TRINH VU DANG NGUYEN


2.2 Assignments (overview)
o Continuous assignments – fixed connection Initially, Q1=1, Q2=0 Initially, Q1=1, Q2=0
• assign f1 = a && b;
• assign f2 = ~ f1;
o Blocking assignments – evaluate in order
• = in always block
Ø begin always @ ( posedge clk) always @ ( posedge clk)
Q1 = D; // new Q1 will be used in evaluating all
subsequent statements in this block begin begin
Q2 = Q1; // new Q1 goes to Q2, so Q2 is equal to Q1 = Q2 ; Q1 <= Q2;
D.
Ø end Q2 = Q1 ; Q2 <= Q1;
o Nonblocking assignments – evaluate in parallel end end
• <= in always block
begin
Q1<= D; After one clk positive edge After one clk positive edge
Q2<= Q1; // old Q1 goes to Q2
end
• The order of statements doesn’t matter
Q1=0, Q2=0 Q1=0, Q2=1

Q1=Q2 Q1,Q2 exchange

THS. TRINH VU DANG NGUYEN


2.2 Assignments (overview)
module blocking_assign (D, Clock, Q1, Q2); D D Q Q
1
input D, Clock;
output Q1, Q2;
Clock
reg Q1, Q2; Q
Parallel Flip-Flop
always @(posedge Clock)
begin
Q1 = D;
D Q Q
Q2 = Q1; 2

end
endmodule Q

module nonblocking_assign (D, Clock, Q1, Q2);


input D, Clock;
Q Q
output Q1, Q2; 1 2
D D Q D Q
reg Q1, Q2; Shift register
always @(posedge Clock)
begin Clock Q Q
Q1 <= D;
Q2 <= Q1;
end
endmodule
THS. TRINH VU DANG NGUYEN
2.2 Assignments (overview)

—
—

THS. TRINH VU DANG NGUYEN


2.2 Assignments (overview) x3
module blocking_assign (x1, x2, x3, Clock, f, g);
input x1, x2, x3, Clock; x1 D Q g
output f, g; x2
reg f, g; Q
always @(posedge Clock)
begin
f = x1 & x2;
g = f | x3;
f
end D Q

endmodule
Clock Q

module blocking_assign (x1, x2, x3, Clock, f, g);


input x1, x2, x3, Clock; x3
D Q g
output f, g;
reg f, g;
always @(posedge Clock) Q

begin
g = f | x3;
f = x1 & x2;
x1
end D Q f
endmodule x2

Clock Q
THS. TRINH VU DANG NGUYEN
2.2 Assignments (overview)
module nonblocking_assign (x1, x2, x3, Clock, f, g); x3
D Q g
input x1, x2, x3, Clock;
output f, g;
Q
reg f, g;
always @(posedge Clock)
begin
f <= x1 & x2; x1
g <= f | x3; x2
D Q f

end
endmodule Clock Q

• It is better to use blocking assignments when


describing combinational circuits.
• It is better to use nonblocking assignments when
describing sequential circuits.

THS. TRINH VU DANG NGUYEN


3. Finite State Machines
o General diagram of FSMs
o Two types of FSMs: Moore and Mealy
o Comparison between Moore and Mealy
o Introduction to Verilog for FSMs
Moore-type
Combinational Z
Combinational Q
Flip-flops circuit
circuit
W

Clock

Mealy-type
Combinational Z
Combinational Q
Flip-flops circuit
circuit
W

Clock THS. TRINH VU DANG NGUYEN


3.1 First Verilog template for Moore FSMs
module FSM_name (Clock, Resetn, input_signal, output_signal);
input Clock, Resetn, input_signal; y: present state
output output_signal; Y: next state
reg [n:1] state_present, STATE_NEXT;
parameter [n:1] STATE1 = 2'b00, STATE2 = 2'b01…. ;

// Define the next state combinational circuit 3 parallel blocks:


always @(input_signal or state_present) 1) always block:
case (state_present)
STATE1: if (input_signal) STATE_NEXT = …;
combinational circuit for
else STATE_NEXT = …; next state
STATE2: if (input_signal) STATE_NEXT = …; 2) always block:
else STATE_NEXT = …;
update states
……
default: STATE_NEXT = n'bxx; 3) assign:
endcase combinational circuit for
output
// Define the sequential block
always @(negedge Resetn or posedge Clock)
if (Resetn == 0) state_present <= STATE1;
else state_present <= STATE_NEXT; Y y
Next state Output z
Flip-flops
// Define output w circuit circuit
assign output_signal = ….;
clock Resetn
endmodule

THS. TRINH VU DANG NGUYEN


3.1 First Verilog template for Moore FSMs

module simple (Clock, Resetn, w, z); y: present state Present state


input Clock, Resetn, w;
output z;
Y: next state input

reg [2:1] y, Y;
parameter [2:1] A = 2'b00, B = 2'b01, C = 2'b10;
State assignment
output
// Define the next state combinational circuit
always @(w or y)
case (y)
A: if (w) Y = B; Moore-type
else Y = A;
B: if (w) Y = C;
else Y = A;
C: if (w) Y = C;
else Y = A;
default: Y = 2'bxx;
endcase

// Define the sequential block


always @(negedge Resetn or posedge Clock) y
if (Resetn == 0) y <= A; Next state Y Output z
else y <= Y; Flip-flops
w circuit circuit
// Define output clock
assign z = (y == C);
Resetn

endmodule THS. TRINH VU DANG NGUYEN


3.2 Second Verilog Template

module FSM_name (Clock, Resetn, input_signal, output_signal); y: present state


input Clock, Resetn, input_signal; Y: next state
output output_signal;
reg [n:1] state_present, STATE_NEXT;
parameter [n:1] STATE1 = 2'b00, STATE2 = 2'b01…. ; 2 parallel blocks:
1) always block:
// Define the next state combinational circuit
combinational circuit for:
always @(input_signal or state_present)
begin a. next state
case (state_present) b. output
STATE1: if (input_signal) STATE_NEXT = …; 2) always block:
else STATE_NEXT = …;
STATE2: if (input_signal) STATE_NEXT = …; update states
else STATE_NEXT = …;
……
default: STATE_NEXT = n'bxx; merge
endcase

// Define output Y y
output_signal =….; Next state Output z
end w Flip-flops
circuit circuit
// Define the sequential block
always @(negedge Resetn or posedge Clock)
if (Resetn == 0)y <= STATE1; clock Resetn
else y <= Y;
endmodule
THS. TRINH VU DANG NGUYEN
3.2 Second Verilog Template
module simple (Clock, Resetn, w, z);
input Clock, Resetn, w;
y: present state
output z; Y: next state
reg z;
reg [2:1] y, Y;
parameter [2:1] A = 2'b00, B = 2'b01, C = 2'b10; State assignment

// Define the next state combinational circuit


always @(w or y)
begin
case (y)
A: if (w) Y = B;
else Y = A;
B: if (w) Y = C;
Moore-type
else Y = A;
C: if (w) Y = C;
else Y = A;
default: Y = 2'bxx;
endcase
// Define output
z = (y == C);
end
// Define the sequential block y
always @(negedge Resetn or posedge Clock) Next state Y Output z
if (Resetn == 0)y <= A; w Flip-flops
else y <= Y;
circuit circuit
clock Resetn THS. TRINH VU DANG NGUYEN
endmodule
3.3 Third Verilog Template
module FSM_name (Clock, Resetn, input_signal, output_signal); y: present state
input Clock, Resetn, input_signal;
output output_signal;
Y: next state
reg [n:1] state; // don’t need state_present, STATE_NEXT;
parameter [n:1] STATE1 = 2'b00, STATE2 = 2'b01…. ;

// Define the sequential block 2 parallel blocks:


always @(negedge Resetn or posedge Clock) 1) always block:
if (Resetn == 0) state <= STATE1; sequential circuit for:
else
case (state)
next state
STATE1: if (input_signal) state <= …; and update
else state <= …; 2) assign block:
STATE2: if (input_signal) state <= …;
for output
else state <= …;
……
default: state <= n'bxx;
endcase
merge

// Define output
assign output_signal=….; y
Next state Y Output z
/*assign cannot be put inside w Flip-flops
the always block*/ circuit circuit
endmodule
clock Resetn

THS. TRINH VU DANG NGUYEN


3.3 Third Verilog Template
module simple (Clock, Resetn, w, z);
input Clock, Resetn, w;
output z;
reg [2:1] y;
parameter [2:1] A = 2'b00, B = 2'b01, C = 2'b10;
// Define the sequential block
always @(negedge Resetn or posedge Clock)
if (Resetn == 0) y <= A;
else
case (y)
A: if (w) y <= B;
else y <= A;
B: if (w) y <= C;
else y <= A;
C: if (w) y <= C; Moore-type
else y <= A;
default: y <= 2'bxx;
endcase

// Define output
assign z = (y == C); /*assign cannot be put inside
endmodule the always block*/

THS. TRINH VU DANG NGUYEN


3.4 Summary of Verilog for FSMs
o No standard way for writing code that represents an FSM.
o However, there are 3 templates we can use to code, based on state diagram.
o The 3 templates provide identical functionality, but may produce different circuits.
o The first two templates are recommended.
o Similar templates exist for Mealy FSMs

THS. TRINH VU DANG NGUYEN


3.5 Verilog For Mealy FSMs
o Similar to Moore FSMs
o The main difference between Mealy and Moore:
• For Moore, the output is defined independent of inputs, so the code
for output is separated from the code for state transitions, e.g. case
• For Mealy, the code for output is written within the case statement
that also defines the state transitions.
o Two parallel blocks:
• always @ (inputs or current_states) defines the next state and
output.
• alwasy @ (negedge resetn or posedge clock) defines flip-flops.

THS. TRINH VU DANG NGUYEN


3.5 Verilog template for Mealy FSMs

module FSM_name (Clock, Resetn, input_signal, output_signal);


input Clock, Resetn, input_signal; y: present state
output output_signal; Y: next state
reg [n:1] state_present, STATE_NEXT;
parameter [n:1] STATE1 = 2'b00, STATE2 = 2'b01…. ;
2 parallel blocks:
// Define the next state combinational circuit and outputs 1) always block:
always @(input_signal or state_present)
case (state_present) combinational circuit for
STATE1: if (input_signal) define output and next state; next state and output
else define output and next state; 2) always block:
STATE2: if (input_signal) define output and next state;
else define output and next state;
update states
……
default: define output and next state;
endcase

// Define the sequential block Y y


always @(negedge Resetn or posedge Clock) Next state Output z
w Flip-flops
if (Resetn == 0) y <= STATE1; circuit circuit
else y <= Y;
clock Resetn
endmodule

THS. TRINH VU DANG NGUYEN


3.5 Verilog template for Mealy FSMs
module mealy (Clock, Resetn, w, z);
input Clock, Resetn, w; 2 parallel blocks:
output z; 1) always block:
reg y, Y, z; combinational circuit for next state and output
parameter A = 0, B = 1; 2) always block:
// Define the next state and output update states
//combinational circuits
always @(w or y) // Define the sequential block
case (y) always @(negedge Resetn or posedge Clock)
A: if (w) if (Resetn == 0) y <= A;
begin else y <= Y;
z = 0; Y = B;
end endmodule
else // w = 0
begin
z = 0; Y = A; Reset
end state
B: if (w) w= 1⁄z= 0
begin
z = 1; Y = B;
end A B
else
begin w= 0⁄z= 0 w= 1⁄z= 1
z = 0; Y = A; w= 0⁄z= 0
end
endcase input output
Mealy-type THS. TRINH VU DANG NGUYEN
5
Phụ Lục Verilog

THS. TRINH VU DANG NGUYEN


T flip-flop
Q( t + 1 )
T
module tff(t, clk,q);
0 Q( t )
1 Q( t )
input t, clk;
(a) Truth table output q;
reg q;

T Q always @ (posedge clk)


Q
case(t)
0: q <= q;
(b) Graphical symbol 1: q <= ~q;
endcase
endmodule

116
Flip-flop with clear capability
module flipflop (D, Clock, Resetn, Q);
input D, Clock, Resetn;
output Q;
reg Q;

always @(negedge Resetn or posedge Clock)


if (!Resetn)
Q <= 0;
else
Q <= D;

endmodule

Asynchronous reset: by using sensitivity list and if-else


117
Flip-flop with clear capability
module flipflop (D, Clock, Clear, Q);
input D, Clock, Clear;
output Q;
reg Q;

always @(posedge Clock)


if (!Clear)
Q <= 0; C le a r
D Q Q
D

else
Q <= D;
C lo c k Q Q

endmodule

Synchronous reset: by using if-else


118
N-bit register
module regn (D, Clock, Resetn, Q);
parameter n = 16; D[n-1] Q[n-1]
input [n-1:0] D; D Q

input Clock, Resetn;


output [n-1:0] Q;
D Q
reg [n-1:0] Q;

always @(negedge Resetn or posedge Clock)


if (!Resetn) D[0]
Q <= 0; D Q Q[0]
else
Q <= D;
Clock

endmodule
Asynchronous reset: by using sensitivity list and if-else 119
N-bit register module
module regn (D, E, Clock, Q);
parameter n = 8;
input [n-1:0] D; D Q
input E, Clock;
output [n-1:0] Q; regn
reg [n-1:0] Q; Clock

always @(posedge Clock)


if (E) E
Q <= D;

endmodule

Synchronous enable: by using if-else


120
4-bit shift register
module shift4 (D, E, w, Clock, Q);
input [3:0] D; 4
input E, w, Clock; D Q[3]
output [3:0] Q; w
reg [3:0] Q;
Clock Q[0]
always @(posedge Clock)
if (E)
Q <= D; E
else
begin Comments:
Q[0] <= Q[1]; 1) This is a behavioral description
Q[1] <= Q[2]; 2) Only Clock is included in always list
Q[2] <= Q[3]; 3) Control signal E is used in if statement
Q[3] <= w;
end
endmodule

121
N-bit shift register
module shift4 (D, E, w, Clock, Q); module shiftn (D, E, w, Clock, Q);
input [3:0] D; parameter n = 16;
input E, w, Clock; input [n-1:0] D;
output [3:0] Q; input E, w, Clock;
output [n-1:0] Q;
reg [3:0] Q; reg [n-1:0] Q;
always @(posedge Clock) integer k;
if (E)
Q <= D; always @(posedge Clock)
else if (E)
begin Q <= D;
Q[0] <= Q[1]; else
Q[1] <= Q[2]; begin
Q[2] <= Q[3]; for (k = 0; k < n-1; k = k+1)
Q[k] <= Q[k+1];
Q[3] <= w; Q[n-1] <= w;
end end
endmodule endmodule

122
Up-counter
module upcount (Resetn, Clock, E, Q);
input Resetn, Clock, E;
output [3:0] Q;
reg [3:0] Q;

always @(negedge Resetn or posedge Clock)


if (!Resetn)
Q <= 0;
else if (E)
Q <= Q + 1;

endmodule

Comments: asynchronous reset; counting if enable (E) is high.


123
Up-counter with parallel load
module upcount (R, Resetn, Clock, E, L, Q);
input [3:0] R;
input Resetn, Clock, E, L;
output [3:0] Q;
reg [3:0] Q;

always @(negedge Resetn or posedge Clock)


if (!Resetn)
Q <= 0;
else if (L)
Q <= R;
else if (E)
Q <= Q + 1;
endmodule
124

You might also like