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

FDS (Only Verilog)

Chapter 10 discusses the CAD design flow for digital circuits, covering front-end tools like design entry, logic synthesis, and functional simulation, as well as back-end tools including physical design and timing simulation. It also introduces Verilog HDL, detailing structural modeling, syntax, modules, and ports, alongside examples like a full adder and a ripple-carry adder. Chapter 11 focuses on bus architecture, multiplexers, tri-state drivers, and behavioral modeling in Verilog, emphasizing the importance of managing data transfer and signal states in digital systems.

Uploaded by

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

FDS (Only Verilog)

Chapter 10 discusses the CAD design flow for digital circuits, covering front-end tools like design entry, logic synthesis, and functional simulation, as well as back-end tools including physical design and timing simulation. It also introduces Verilog HDL, detailing structural modeling, syntax, modules, and ports, alongside examples like a full adder and a ripple-carry adder. Chapter 11 focuses on bus architecture, multiplexers, tri-state drivers, and behavioral modeling in Verilog, emphasizing the importance of managing data transfer and signal states in digital systems.

Uploaded by

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

Chapter 10

Digital Logic and Verilog (PART V)


(W6.1)

10.1 CAD Design Flow


The CAD design process encompasses several critical steps, ensuring the accurate realization
of digital circuits.

Front End Tools:

– Design Entry: The journey begins with the design entry, where the initial con-
cept is articulated. This stage leverages intuition and experience, often utilizing
Schematic Capture for graphical representations or Hardware Description Lan-
guages (HDLs) like Verilog and VHDL for textual descriptions.
– Logic Synthesis: The design is then transformed into a logic gate structure,
where HDL codes are converted into networks of logic gates. This process not
only mirrors the intended circuit functionality through logic expressions but also
optimizes the design for speed, size, and power efficiency.
– Functional Simulation: This phase verifies the logical correctness of the design
by simulating logic functions. Assuming perfect gates, it generates timing wave-
forms for detailed analysis, ensuring the design operates as expected under ideal
conditions.

Back End Tools:

– Physical Design: Subsequently, the focus shifts to the physical layout, where
the logic expressions are mapped onto a chip using available components. This
involves the strategic placement of components and routing connections between
them.
– Timing Simulation: This step is crucial to ensure the design meets all timing
constraints, accounting for the physical realities of circuit implementation.
– Circuit Implementation: The final step is the circuit’s physical realization,
where the design is brought to life in hardware form.

75
CHAPTER 10. DIGITAL LOGIC AND VERILOG (PART V) (W6.1)

10.2 Verilog HDL


Personal Remark. this course will absolutely NOT suffize to make you a Verilog expert, please
take some time to practice in an empty project, just representing in both structural and behav-
ioral ways the circuits we’ve seen so far.

10.2.1 Structural Modeling with Logic Gates


In structural modeling, we use predefined modules (built-in representations of basic logic
gates) to construct complex circuits.
We use this logic gate instantiation statement to create a basic logic gate:
1 gate_name [instance_name] (out_port, in_port{, in_port});

[] indicates an optional parameter.


() indicates a required parameter.
{} indicates that additional parameters can be added.

With gate name as the type of gate :


(not limited to these...)

and nor
nand buf
xor not
or xnor

Examples
- AND Gate:
1 and and1 (out, in1, in2);

- OR Gate:
1 or or1 (out, in1, in2);

- NOT Gate:
1 not not1 (out, in);

- NAND Gate:
1 nand nand1 (out, in1, in2);

76
Notes by Ali EL AZDI

10.2.2 Verilog Syntax


In a Nutshell

Naming Rules:

Begin with a letter.


Include letters, digits, underscore ( ), and dollar sign ($).

Case Sensitivity:

Lowercase and uppercase are distinct (e.g., a 6= A).

Style Guidelines:

Syntax is flexible with white spaces and line breaks.


Prioritize readability with proper indentation.

Comments:

Initiated by double slashes (//).

10.2.3 Modules in Verilog


A circuit or subcircuit described in Verilog is encapsulated within a module. The module dec-
laration includes the module name and its ports, which are the input and output connections
to the module.
1 module module_name [(port_name{, port_name})];
2 [input declarations]
3 [output declarations]
4 [wire declarations]
5 [logic gate instantiations]
6 [module instantiations]
7 endmodule

(words in purple are reserved keywords, words after two slashes are comments)

10.2.4 Ports in Verilog


Ports are the input and output connections of a module. They are declared within the module
declaration They can be in the following directions : Port Types:

- input – for receiving signals.

- output – for sending signals.

- inout – for bi-directional signal flow.

Port Declaration:

- Syntax:
1 port\_direction data\_type [port\_size] port\_name;

- Implicit type: Unspecified types default to wire.

77
CHAPTER 10. DIGITAL LOGIC AND VERILOG (PART V) (W6.1)

- Vectors: Specify bit-width for multi-bit signals (e.g., [3:0] for 4 bits).

Examples:

input diff; // Single-bit input named diff


inout [15:0] data; // 16-bit bidirectional port named data
output [3:0] f; // 4-bit output named f

10.2.5 Example - Full adder in Verilog


1 // Structural modeling of a full-
adder
2 module fulladd (a, b, c_in, s, c_out)
;
3 // ----- port definitions -----
4 input a, b, c_in;
5 output s, c_out;
6 // ----- intermediate signals -----
7 wire w1, w2, w3;
8 // ----- design implementation -----
9 and And1 (w1, a, b);
10 and And2 (w2, a, c_in);
11 and And3 (w3, b, c_in);
12 or Or1 (c_out, w1, w2, w3);
13 xor Xor1 (s, a, b, c_in);
14 endmodule

Which can be simplified to :


1 module fulladd (a, b, c_in, s,
c_out);
2 input a, b, c_in;
3 output s, c_out;
4 and (w1, a, b);
5 and (w2, a, c_in);
6 and (w3, b, c_in);
7 or (c_out, w1, w2, w3);
8 xor (s, a, b, c_in);
9 endmodule

10.2.6 Subcircuits in Verilog


A Verilog module can be included as a subcircuit in another module.

Modules should be defined in the same source file, or the Verilog compiler must know
the locations of the modules.

Module instantiation syntax:

1 {module\_name instance\_name ( .port\_name (expression));}

Notes: ∗ module name and instance name are any valid identifiers.
∗ .port name specifies the subcircuit’s port to be connected.

78
Notes by Ali EL AZDI

∗ Omitting .port name is possible if port order is identical to the subcircuit’s


definition, but not recommended due to error-proneness.

10.2.7 Example - Ripple-Carry Adder in Verilog


A four-bit ripple-carry adder is composed of four full-adder stages with interconnections for
the carry bits.

Written in Verilog :
1 module adder4 (Cin, A, B, S, Cout);
2 // Port definitions
3 input Cin;
4 input [3:0] A, B; // 4-bit vectors
5 output [3:0] S; // 4-bit vector
6 output Cout;
7
8 // Intermediate signals
9 wire [3:1] C; // 3-bit vector for carry bits
10
11 // Design implementation using full-adder stages
12 fulladd stage0 (.c_in(Cin), .a(A[0]), .b(B[0]), .s(S[0]), .c_out(C[1]));
13 fulladd stage1 (.c_in(C[1]), .a(A[1]), .b(B[1]), .s(S[1]), .c_out(C[2]));
14 fulladd stage2 (.c_in(C[2]), .a(A[2]), .b(B[2]), .s(S[2]), .c_out(C[3]));
15 fulladd stage3 (.c_in(C[3]), .a(A[3]), .b(B[3]), .s(S[3]), .c_out(Cout));
16 endmodule

79
Chapter 11

Digital Logic and Verilog(PART


VI)(W6.2)

11.1 Bus Architecture

A bus is a communication system that trans-


fers data between components of a digital
device. It is designed to connect parts of the
motherboard or to link other hardware. In
essence:

• A bus allows sequential data transmis-


sion from multiple sources to various
destinations.

• Buses usually carry multiple bits simul-


taneously, typically more than one bit,
to transmit data.

Within Verilog design, multiple-bit wires are


termed as vectors, and single-bit wires are
called scalars. Illustration of an n-bit bus

11.1.1 Using Multiplexers (MUXes)

Multiplexers, or MUXes, direct signals from several input lines to a single output line. They
select which input to transmit based on control signals.

80
Notes by Ali EL AZDI

A multiplexer can manage multiple n-bit


data lines by using a select signal of m bits,
where m is the minimum number of bits
required to represent the number of inputs,
calculated as m = dlog2 (K)e.

11.1.2 Without Multiplexers


Buses enable communication between di↵erent modules. However, directly connecting two
outputs to one input can cause a short-circuit if they attempt to send conflicting signals.
Employing multiplexers or tri-state drivers prevents this by ensuring that only one signal
is transmitted at a time.

11.2 Tri-State Drivers


A tri-state driver has a data input w, output f , and an enable e input. When inactive, a
tri-state driver’s output enters a high-impedance state (Z), thus three possible states being
logical 0, logical 1, or Z.
Thus the following table:

e w f
0 0 Z
0 1 Z
1 0 0
1 1 1

11.2.1 Types of Tri-State Drivers


Enable active high Enable active low
with inverted f Enable active low
with inverted f

e w f e w f
e w f
0 0 0 0 0 1
0 0 Z
0 1 1 0 1 0
0 1 Z
1 0 Z 1 0 Z
1 0 1
1 1 Z 1 1 Z
1 1 0

81
CHAPTER 11. DIGITAL LOGIC AND VERILOG(PART VI)(W6.2)

11.3 Complete Verilog Built-In Gate List


Now we can complete the Verilog built-in gate list presented in the last chapter as follows :

and nor bufif0(f, w, e)


nand buf bufif1(f, w, e)
xor not notif0(f, w, e)
or xnor notif1(f, w, e)

82
Notes by Ali EL AZDI

11.4 Implementing a Bus with Tri-State Drivers

In digital systems, a bus with tri-


state drivers facilitates selective data
transfer between modules without
conflict.

Each module connects via a driver


that outputs high impedance to avoid
bus contention, controlled by unique
enable signals. (simplified: one signal
at a time)

11.5 Verilog Part 2.


11.5.1 Scalar Signal Values
Verilog supports one-bit signals (scalars), each signal can have one of the following values:

Value Meaning
0 Logic 0
1 Logic 1
x Unknown logic value or don’t care
z tri-state, high-impedance

11.5.2 Vector Signal Values


The value of a vector variable looks like this
1 [size][’radix]constant

size is the number of bits, radix is the base of the number, and constant is the value of the
number. Supported radices include:

Radix Meaning
d decimal default if no radix is specified
b binary
h hexadecimal
o octal

11.5.3 Parameters
Parameters are constants that can be used in the module. They are defined as follows:
1 parameter name = value;

eg.
1 parameter c = 8;

83
CHAPTER 11. DIGITAL LOGIC AND VERILOG(PART VI)(W6.2)

11.5.4 Nets
Nets are used to connect modules. There are two net types:
wires tri-states
1 wire [3:0] a; 1 tri z1

11.5.5 Behavioral Modeling in Verilog


Behavioral modeling in Verilog is one of the three modeling paradigms used in Verilog to
describe digital circuits at a high level. This approach allows designers to specify how circuits
should behave through procedural statements, similar to software programming. Simplified:
used when too hard to do in structural modeling.

11.5.6 Bit-wise Operators


Bit-wise operators in Verilog are used to perform operations on individual bits of a vector.
The following are the bit-wise operators available in Verilog:

Operator Description
& Bit-wise AND
— Bit-wise OR
ˆ Bit-wise XOR
˜ Bit-wise NOT

11.5.7 Example - Structural to Behavioral Modeling


Here’s a circuit we’ve modeled in structural modeling :

Structural

1 module my_circuit_structural (
2 input x1, x2, x3, x4,
3 output f
4 );
5 wire w1, w2, w3, w4, w5, w6, w7,
w8;
6 and (w1, x1, x3);
7 not (w2, x2);
8 not (w3, x3);
9 and (w4, x2, x4);
10 or (w5, x1, w3);
11 or (w6, w2, x4);
12 or (w7, w1, w4);
13 and (w8, w5, w6);
14 or (f, w7, w8);
15 endmodule

84
Notes by Ali EL AZDI

Behavioral

1 module my_circuit_behavioral (
2 input x1, x2, x3, x4,
3 output f
4 );
5 wire w7, w8;
6 assign w7 = (x1 & x3) | (x2 & x4);
7 assign w8 = (x1 | ˜x3) & (˜x2 | x4);
8 assign f = w7 | w8;
9 endmodule

11.5.8 Continuous Assignments in Verilog


Keyword: assign

Definition
Continuous assignments are used in Verilog for assigning values to wires. The assign state-
ment makes the left-hand side (LHS) of the assignment dynamically reflect any changes in the
right-hand side (RHS) immediately.

Properties
- Executes continuously: The assignment reacts to any change in the RHS variables and
updates the LHS accordingly.

- Operates in parallel: The execution order in the code does not a↵ect the simulation
behavior.

Example
Consider the case where we want to perform a logical OR operation between two signals, w7
and w8, and assign the result to signal f:
1 assign f = w7 | w8;

In this example, whenever the value of w7 or w8 changes, f is automatically recalculated to


reflect the new value.

85
CHAPTER 11. DIGITAL LOGIC AND VERILOG(PART VI)(W6.2)

11.5.9 Verilog Always Block


Keyword: always
The always block in Verilog is used for modeling combinational and sequential logic. It re-
acts to changes in input signals, ensuring that the block’s internal logic is evaluated whenever
necessary.

Structure

1 always @*
2 [begin]
3 [procedural assignment statements]
4 [if-else statements]
5 [case statements]
6 [while, repeat, and for loops]
7 [task and function calls]
8 [end]

In this block, the always keyword is followed by @*.

11.5.10 If-Else Statements


If an expression is true, the code within the begin-end block runs; multiple statements can be
grouped in such a block. Optional else if and else clauses, when used, connect to the closest
preceding if or else if statement.

Structure

1 if (expression1)
2 begin
3 statement;
4 end
5 else if (expression2)
6 begin
7 statement;
8 end
9 else
10 begin
11 statement;
12 end

86
Notes by Ali EL AZDI

11.5.11 Example - 2-to-1 MUX


Using what we’ve learned so far
1 module my_2to1mux ( input w1,
w2, s, output reg f );
2 always @*
3 begin
4 if (s == 0)
5 begin
6 f = w1;
7 end
8 else
9 begin
10 f = w2;
11 end
12 end
13 endmodule

11.5.12 Case Statement


Personal Remark. Switch in java
Syntax

1 case (expression)
2 alternative1:
3 begin
4 statements;
5 end
6 alternative2:
7 begin
8 statements;
9 end
10 default:
11 begin
12 statements;
13 end
14 endcase

Example - Full Adder 1 module fulladd (input x, y, Cin,


output reg s, Cout);
Using the truth table of a Full- 2 always @*
Adder, let’s use a case statement 3 begin
to implement it: 4 case ({x, y, Cin})
5 3’b000: {s, Cout} = ’b00;
x y Cin s Cout 6 3’b001: {s, Cout} = ’b10;
0 0 0 0 0 7 3’b010: {s, Cout} = ’b10;
8 3’b011: {s, Cout} = ’b01;
0 0 1 1 0
9 3’b100: {s, Cout} = ’b10;
0 1 0 1 0 10 3’b101: {s, Cout} = ’b01;
0 1 1 0 1 11 3’b110: {s, Cout} = ’b01;
1 0 0 1 0 12 3’b111: {s, Cout} = ’b11;
1 0 1 0 1 13 endcase
1 1 0 0 1 14 end
1 1 1 1 1 15 endmodule

87
Chapter 12

Digital Logic and Verilog(PART VII)


(W7.2)

12.1 Memory Elements


12.1.1 Introduction - Example Application: Alarm System
Control
Suppose we wish to control an alarm system. The system design involves a sensor, an alarm
control circuit, and an alarm indicator. Below is the functional description of the system:

Figure 12.1: Diagram of the Alarm System Control

- The sensor detects an undesirable event and sends a SET signal (logic high or 1) to the
alarm control circuit.

- The alarm control circuit activates the alarm when it receives the SET signal. The
ALARM ON signal becomes 1 (logic high), indicating that the alarm is active.

- The alarm remains active until a RESET signal (logic high or 1) is sent to the alarm
control circuit, turning o↵ the alarm (ALARM ON becomes 0).

- A memory element in the circuit ensures that the alarm remains active until it is explic-
itly reset, even if the SET signal goes back to low (0).

88
Notes by Ali EL AZDI

12.1.2 Combinational vs. Sequential Circuits


Personal Remark. Please take some time to actually identify the di↵erences between the two as
they will be crucial in understanding the rest of the course
Tip: C comes before S in the alphabet, we’ve seen combinational circuits before sequential
circuits. So you can think of combinational as what we’ve seen so far, and sequential as the
new circuit type
Previously, in combinational circuits, outputs only depended on the current inputs.
In sequential circuits, outputs are determined by both the current inputs and the circuit’s
past behavior, due to the inclusion of memory elements.

Combinational Circuits are memory-less; Sequential circuits have memory elements,


outputs only depend on the current in- outputs depend on both current inputs
puts. and past behavior.

Storage elements in a circuit hold logic signal values, defining the circuit’s state. When inputs
change, the circuit may maintain its current state or transition to a new state. Consequently, the
circuit evolves through various states over time based on input changes.

12.1.3 Basic Memory Element


Bistable Element
We’ve seen that two Not gates in a series doesn’t change the input signal, so, what if we con-
nect the output of the second Not gate to the input of the first Not gate?

Q Q
0 1
1 0

While this already allows the most basic form of memory, it’s not very practical, the given
value cannot be changed, and it’s not very reliable.

89
CHAPTER 12. DIGITAL LOGIC AND VERILOG(PART VII) (W7.2)

Set-Reset Latch with Reset Priority


The set-reset latch is a memory element that can store one bit of information. It has two
inputs: S (set) and R (reset). The latch retains its state until a new input is received.

Components of the Set-Reset Latch:

- Set Input (S): When S is high (1), the latch sets to 1.

- Reset Input (R): When R is high (1), the latch resets to 0.

- Q Output: The current state of the latch.

- Q-bar Output: The inverse of the current state of the latch.

What happens when both S and R are high?


R = 1, S = 1: This is generally considered an unwanted or invalid situation for SR latches
because it tries to set and reset the latch at the same time, leading to unpredictable behavior.
Some designs define this state specifically to avoid ambiguity.

S R R̄ · S Qa Qnext Qb,next
0 0 0 Qa Qa Q̄a
0 1 0 0 0 1
1 0 1 Qa 1 0
1 1 0 0 0 0

This is how the next state of the latch is calculated, the current state of the latch is Qa and
Qb and the next state is Qnext and Qb,next respectively.

Qa,next = R + Qb = R + S + Qa
= R · (S + Qa )
= R · S + R · Qa = Qnext
Qb = S + Qa

Set-Reset Latch with Set Priority


The set-reset latch with set priority is similar to the reset-priority latch, but with the priority
reversed. The latch sets to 0 when both S and R are high (1).

S R R̄ · Qa Qa,next Qb,next
0 0 Qa Qa Qa
0 1 0 0 1
1 0 0 1 0
1 1 0 1 1

Qnext = S + R̄ · Qa

90
Notes by Ali EL AZDI

12.2 Latches with a Control Signal


Gated latches use a control signal to determine when to change their state. When active, the
control signal allows the latch to update its state; when inactive, it prevents changes. This helps
avoid unwanted oscillations.

12.2.1 Gated D Latch

When the control signal C is high, the out-


put Q mirrors changes in input D. Oth-
erwise, Q remains constant, retaining its
previous value.

12.2.2 Flip-Flops
Personal Remark. Put simply, the first type requires actual C input to determine when to
update, while the other type updates Q in response to an event-driven signal, such as a clock
signal (refer to the following section about Clock signals for a clearer explanation).

D Flip-Flop
Flip-flops update outputs at specific times, unlike latches. A D flip-flop captures the input
from the D signal only during certain clock signal transitions, ensuring stable and predictable
outputs. Once the clock triggers (on a rising or falling edge), the output Q immediately
matches the input D and maintains this value, una↵ected by any further input changes, until
the next clock edge.

D Flip-Flop sensitive to the rising edge D Flip-Flop sensitive to the falling edge

12.3 Clock
Clocks are essential in digital systems for synchronization purposes. The timing of state
changes within the system is orchestrated by these clocks.

12.3.1 Clock Signal


A clock signal is a periodic waveform that oscillates between a high state and a low state. It
is characterized primarily by its frequency, which dictates how many cycles occur per second,
and its duty cycle, which describes the proportion of time the signal is in the high state within
a single cycle.

91
CHAPTER 12. DIGITAL LOGIC AND VERILOG(PART VII) (W7.2)

12.3.2 Waveform
The waveform of a clock signal can be described as follows:

• Period: The period of a clock signal is the duration of one complete cycle of the waveform
and is typically measured in seconds or fractions thereof (like nanoseconds, ns).
It is denoted by TCLK .

• Frequency: The frequency of a clock signal is defined as the number of complete cycles it
performs per second. Typical units of measurement are Hertz (Hz).
1
Calculated as f = TCLK , where TCLK is the period.

• Duty Cycle: The duty cycle is the percentage of the period during which the clock signal
Thigh
remains in the high state (often 50%). Calculated as D = TCLK ⇥ 100%.

The transition points of the clock signal, especially the rising edge, often trigger state changes
within the digital system, coordinating operations and ensuring the system functions correctly
and predictably.

12.4 Verilog Part 3.


12.4.1 Update to Always Block
Updates can take place one after the other, or concurrently, depending on the assignment used :
blocking (=) or nonblocking ().

Blocking Assignment
For example: Here, B is assigned the value of A, then C is assigned the value of B, and finally, D
is assigned the value of C. At the end, A = B = C = D. This is used to model combinational
logic (without memory).
1 always @ (...sensitivity list...)
2 begin
3 B = A;
4 C = B;
5 D = C;
6 end

Nonblocking Assignment
For example: Changes occur at the same time, so B is assigned the value of A, C is assigned the
old value of B, and D is assigned the old value of C. This is used to model sequential logic (with
memory).

92
Notes by Ali EL AZDI

1 always @ (...sensitivity list...)


2 begin
3 B <= A;
4 C <= B;
5 D <= C;
6 end

always(*) Blocks
(=) Block Statements should be used.
The always @* block is used to model combinational logic, where the output depends only on
the current input values. It is sensitive to any change in the input signals.
1 // Example: AND gate
2 always @ (*)
3 begin
4 C = A & B;
5 end

always@(posedge Clock) Blocks


() Nonblocking Statements should be used.
Used to describe sequential logic containing flip-flops
Note: Remember,  like the arrow in the Control Input symbol of a D Flip-Flop representation,
it’s a reminder that the assignment is non-blocking.

- always@(posedge Clock) – always at the rising clock edge

- always@(negedge Clock) – always at the falling clock edge

12.5 Behavioral Latch and Flip-Flop Models


Basic D Latch
The output may be a↵ected whenever inputs D or C change (hence the *) If input C is 0, we do
nothing, there is no else clause.
1 module Dlatch (
2 input D,
3 input C,
4 output reg Q
5 );
6 always @ (*)
7 begin
8 if (C == 1)
9 Q <= D;
10 end
11 endmodule

93
CHAPTER 12. DIGITAL LOGIC AND VERILOG(PART VII) (W7.2)

D Latch w/ Enable and Asynchronous Clear

A D Latch with Enable and Asynchronous Clear is a type of digital storage device used in
electronic circuits to store a single bit of data. It has a data input (D), a clock input (C), an
enable input (CE), and a clear input (CLR). The output (Q) reflects the input data (D) when
both the clock (C) and enable (CE) inputs are active (high). The asynchronous clear (CLR) has
the highest priority; when activated (high), it immediately resets the output (Q) to 0, regardless
of other input conditions. Thus the Verilog code for this is:

1 module Dlatch (input D, input C, input CE, input CLR,output reg Q);
2 always @ (*)
3 begin
4 if (CLR == 1)
5 Q <= 0;
6 else if ((C == 1) && (CE == 1))
7 Q <= D;
8 end
9 endmodule

Positive-Edge-Triggered D FF

D Flip-Flop with positive-edge-triggered clock input. The always block is executed on the positive
(rising) CLK edge Q gets set to D

1 module Dff (input D, input CLK, output reg Q);


2 always @ (posedge CLK)
3 begin
4 Q <= D;
5 end
6 endmodule

D FF (Positive-Edge-Triggered) with Asynchronous Clear

Works the same as before but the use of posedge here means that the always block is also
executed if the CLR signal is high immediately without waiting for the next clock edge.

1 module Dff (input D, input CLK, input CLR, output reg Q);
2 always @ (posedge CLK or posedge CLR)
3 begin
4 if (CLR == 1)
5 Q <= 0;
6 else
7 Q <= D;
8 end
9 endmodule

Note: It would be a mistake to omit posedge and execute the always block on any change in CLR.
On a 1-to-0 transition on CLR, the else clause would execute and set Q to D even though no
CLK edge had occurred

94
Notes by Ali EL AZDI

D FF with Asynchronous Clear and ⇠ Q Output


The exact same but with an additional output ⇠ Q which is the complementary of Q.
1 module Dff (input D, CLK, CLR, output
reg Q, QN);
2 always @ (posedge CLK or posedge
CLR)
3 begin
4 if (CLR == 1) begin
5 Q <= 0;
6 QN <= 1; // complementary
output
7 end
8 else begin
9 Q <= D;
10 QN <= ˜D; // complementary
output
11 end
12 end
13 endmodule

D FF with Asynchronous Clear and Synchronous Preset


A D Flip-Flop with Clock Enable and Synchronous Preset updates its output to the data input (D)
at each active clock edge (CE) if enabled, or sets the output to a preset value (S) synchronously
if the preset condition is active.
If neither S nor CE is active, the output retains its previous value.
1 module Dff (input D, input CLK, input S, input CE, output reg Q);
2 always @ (posedge CLK)
3 if (S == 1)
4 Q <= 1;
5 else if (CE == 1)
6 Q <= D;
7 endmodule

Keywords Summary
Now what we’ve seen is just a composition of the following keywords, here’s a summary of them:
Asynchronous Clear: Allows the immediate resetting of the latch or flip-flop output to a low state (0),
regardless of the clock or other control signals’ states.
Enable: An additional control input that allows the latch to either accept new data when high (enabled)
or maintain its current state when low (disabled).
Positive-Edge Triggered: Indicates that the flip-flop updates its output only at the rising edge of
the clock signal. This specificity in timing helps to synchronize the data flow in digital systems,
reducing ambiguity and ensuring stability.
Synchronous Preset: Similar to asynchronous clear, but the preset operation occurs in sync with the
clock. This feature sets the output to a high state (1) during the clock’s active edge.
Complementary Output: Provides an additional output that is the logical inverse of the main output.
This feature simplifies the design of circuits that require the inverse logic state, reducing the need
for external inverting components.

95
CHAPTER 12. DIGITAL LOGIC AND VERILOG(PART VII) (W7.2)

12.6 Practical notes


For e↵ective sequential systems design, it is crucial to avoid latches due to their susceptibility to
glitches, potential for output oscillation, and level sensitivity, which can result in multiple output
changes within a single clock period.

Instead, use only D flip-flops and combinational logic. Implement separate always blocks,
one set for simple D flip-flops and another for potentially complex combinational logic.

Latches (hold of the last value due to bad timing, and if the last value is the initial one, it
must be defined) can inadvertently arise in combinational circuits. To prevent this, ensure all
variables in always@(*) blocks are assigned initial default values, ensuring consistent logic
states before proceeding to specific assignments.

In sequential logic, always employ nonblocking assignments using the <= operator in always
blocks to ensure simulation consistency across multiple blocks, as this method evaluates all
right-hand sides before assigning values to the left-hand sides.

96
Chapter 13

Digital Logic and Verilog(PART VIII)


(W8.1)

13.1 Finite State Machines


Circuits containing both sequential and combinational logic are known as state machines. 2n
states can be represented by n-bit binary numbers (nothing new). The number of states being
finite we thus call such circuits finite state machines (FSMs)

There are two types of FSMs:

- Mealy Machine: The output depends on the current state and the current input.

- Moore Machine: The output depends only on the current state.

All state transitions are made in sync with clock edges (rising or falling). Personal Remark:
Mnemothecnics: the double o in Moore: Only Output State. (uhm couldn’t find anything better)

97
CHAPTER 13. DIGITAL LOGIC AND VERILOG(PART VIII) (W8.1)

13.1.1 Mealy State Machine


In a Mealy state machine, the output is a function of both the current state and the current
input.

- The state memory is a set of n flip-flops that store the current state all connected to the
same clock (thus updating simultaneously once per clock period).

- The next state is a function of inputs and the current state


eg. Next state = f(current state, input)

- The output is a function of the current state and inputs


eg. Output = g(current state, input)

In a more detailed view:

Note: The sensitivity list of the state machine may be ajusted as we’ve seen

98
Notes by Ali EL AZDI

13.1.2 Moore State Machine


Same, but without the input dependency in the output. In a Moore state machine, the output is a
function of the current state only.

- The state memory is a set of n flip-flops that store the current state all connected to the
same clock (thus updating simultaneously once per clock period).

- The next state is a function of inputs and the current state


eg. Next state = f(current state, input)

- (Di↵erence is here) The output is a function of the current state only


eg. Output = g(current state)

In a more detailed view:

Note: The sensitivity list of the state machine may be ajusted as we’ve seen

99
CHAPTER 13. DIGITAL LOGIC AND VERILOG(PART VIII) (W8.1)

13.2 State Machine Analysis


Here we’ll be looking at how he can analyze a state machine (a circuit containing both sequential
and combinational logic) to determine its behavior.

Algorithm:
Three steps :

Step 1: We determine the next-state and output functions eg. f() and g()

Step 2: Use f() and g() to contruct a state/output table that shows the
entirety of the next state and the output of the circuit for all possible inputs
and states.

Step 3 (Optional): Draw the state diagram of the state machine using the
state/output table.

Step 3 (Optional): The state diagram is the simplest conceptual method to describe the
behavior of a sequential circuit. It is a graph representing circuit states as nodes and the
transitions between states as directed edges.

• Nodes: Represent the circuit states.

– Annotated with state names.


– In Moore FSMs, nodes are also annotated with output values.

• Edges: Represent the transitions between states.

– Annotated with signals causing state transitions.


– In Mealy FSMs, edges are also annotated with output values.

Example 1
Let’s analyze the state machine below:

As this machine Only Outputs State, it is a Moore state machine.

100
Notes by Ali EL AZDI

Step 1: Determine the next-state and output functions.


Let Q1 and Q2 be the current state, and Q⇤1 and Q⇤2 be the next state. The output is z.
Q⇤1 = D1 = f1 (x, Q1 , Q2 ) = Q1 · Q2
Q⇤2 = D2 = f2 (x, Q1 , Q2 ) = x + Q2
z = g(x, Q1 , Q2 ) = Q1 + Q2

Excitation
State variables Outputs
D2D1
x
Q2 Q1 z
0 1
0 0 10 10 1
0 1 10 10 1
1 0 01 11 0
1 1 10 10 1

Step 2: Construct a state/output table.


Let A, B, C, and D represent the states 00, 01, 10, and 11, respectively.

Current State, S Next state, S* Outputs


x
S z
0 1
A C C 1
B C C 1
C B D 0
D A C 1

Step 3: Draw the state diagram.


Written in Verilog:
1 module fsm_example1 (input x,
input CLK, output reg z);
2 reg [2:1] D, Q;
3
4 // Next-state logic
5 always @ (*) begin
6 D[1] = ˜Q[1] & Q[2];
7 D[2] = x | ˜Q[2];
8 end
9
10 // State memory
11 always @ (posedge CLK) begin
12 Q <= D;
13 end
14
15 // Output logic
16 always @ (*) begin
17 z = Q[1] | ˜Q[2];
18 end
19 endmodule

101
CHAPTER 13. DIGITAL LOGIC AND VERILOG(PART VIII) (W8.1)

Example 2
Let’s analyze the state machine below:

As this machine Only Outputs State, it is a Moore state machine.

Step 1: Determine the next-state and output functions.


Let Q0 , Q1 , Q2 the current state, and Q⇤0 , Q⇤1 , Q⇤2 be the next state. The output is z.
Q⇤0 = D0 = f0 (EN, Q0 , Q1 , Q2 ) = Q0 EN
Q⇤1 = D1 = f1 (EN, Q0 , Q1 , Q2 ) = Q1 (Q0 , EN )
Q⇤2 = D2 = f2 (EN, Q0 , Q1 , Q2 ) = Q2 (Q0 Q1 EN )
z = gi (Qi ) = Qi , 0  i  2

Excitation
State variables Outputs
D2D1
x
Q2 Q1 Q0 z
0 1
0 0 0 000 001 1
0 0 1 001 010 0
0 1 0 010 011 1
0 1 1 011 100 0
1 0 0 100 101 1
1 0 1 101 110 0
1 1 0 110 111 1
1 1 1 111 000 0

102
Notes by Ali EL AZDI

Step 2: Construct a state/output table.


Let A, B, C, D, E, F, G, and H represent the states 000, 001, 010, 011, 100, 101, 110, and
111, respectively.

Current State, S Next state, S* Outputs


EN
S z 2 z1 z0
0 1
A A B 0 0 1
B B C 0 1 0
C C D 0 1 1
D D E 1 0 0
E E F 1 0 1
F F G 1 1 0
G G H 1 1 1
H H A 0 0 0

Step 3: Draw the state diagram.


1 module fsm_example2 ( input EN, input
CLK, output reg [2:0] z);
2 reg [2:0] D, Q;
3 // Next-state logic
4 always @ (*) begin
5 D[0] = Q[0] ˆ EN;
6 D[1] = Q[1] ˆ (Q[0] & EN);
7 D[2] = Q[2] ˆ (Q[1] & Q[0] & EN);
8 end
9 // State memory
10 always @ (posedge CLK) begin
11 Q <= D;
12 end
13 // Output logic
14 always @ (*) begin
15 z = Q;
16 end
17 endmodule

103
CHAPTER 13. DIGITAL LOGIC AND VERILOG(PART VIII) (W8.1)

13.3 State Machine Synthesis


FSM Design Algorithm
x Identify FSM inputs and outputs.

x Draw the state diagram.

x Contruct the state/output table.

– Select state encodings (binary vectors)


– Rewrite state table with state encodings
– Write logic expressions for next state

x Construct output table

– Select output encodings (binary vectors)


– Write logic expressions for output

x Construct the equivalent logic circuit (drawing, Verilog)

Example
Consider that we need to design a trafic light controller Let TA , TB : Signals from the trafic
sensors; active when there is traffic LA , LB : Signals for controlling traffic lights

Identify FSM inputs and outputs:


Two one-bit inputs from the traffic sensors: TA , TB

Multiple bits outputs(three states: red, yellow, green): LA , LB

CLK, system clock

CLR, asynchronous reset for clearing the state memory

104
Notes by Ali EL AZDI

Draw the state diagram:

Construct the state/output table:

Current State, S Inputs Next State, S*


S TA TB S*
S0 1 X S0
S0 0 X S1
S1 X X S2
S2 X 1 S2
S2 X 0 S3
S3 X X S0
X stands for 0/1 (i.e., both options), this simplifies the table and avoids redundancy.

Select state encodings


There are four states, thus 2 bits to encode all states
State Encoding
S0 00
S1 01
S2 10
S3 11
Note: Choice of encoding impacts implementation; in practice we let tools infer best encoding
(AICC II)
Rewrite state table, write logic expressions for next state:
Current State, S Inputs Next State, S*
Q1 Q0 TA TB D1 D0
0 0 1 X 0 0
0 0 0 X 0 1
0 1 X X 1 0
1 0 X 1 1 0
1 0 X 0 1 1
1 1 X X 0 0
Using SOP expressions for the next state :

Q⇤1 = D1 = Q1 Q0 + Q1 Q0 + Q1 Q0 = Q0 Q1
Q⇤0 = D0 = Q1 Q0 TA + Q1 Q0 TB

105
CHAPTER 13. DIGITAL LOGIC AND VERILOG(PART VIII) (W8.1)

Construct output table; select output encodings:

It’s a Moore FSM as it Only Outputs State

Three di↵erent outputs, hence two bits required to represent them

- LA : Two bits (LA1 , LA0 )


- LB : Two bits (LB1 , LB0 )

For the encoding given in the table:


If LA is green: LA1 = 0, LA0 = 0;

If LB is yellow: LB1 = 0, LB0 = 1;

...
Construct output table; write logic
expressions
Output Encoding Current State, S Outputs
GREEN 00 Q1 Q0 LA1 LA0 LB1 LB2
YELLOW 01 0 0 0 0 1 0
RED 10 0 1 0 1 1 0
1 0 1 0 0 0
1 1 1 0 0 1

Thus the Output logic expressions are: LA1 = Q1 , LA0 = Q1 Q0 , LB1 = Q1


Written in Verilog:

1 module traffic_light_ctrl (input TA, TB, CLR, CLK, output reg [1:0] LA, LB)
;
2 reg [1:0] D, Q;
3 // Next-state logic
4 always @ (*) begin
5 D[1] = (˜Q[1] & Q[0]) | (Q[1] & ˜Q[0]);
6 D[0] = (˜Q[1] & ˜Q[0] & ˜TA)
7 | (Q[1] & ˜Q[0] & ˜TB);
8 end
9 // State memory
10 always @ (posedge CLK or posedge CLR)
11 begin
12 if (CLR == 1)
13 Q <= 0;
14 else
15 Q <= D;
16 end
17 // Output logic
18 always @ (*) begin
19 LA[1] = Q[1]; LA[0] = ˜Q[1] & Q[0];
20 LB[1] = ˜Q[1]; LB[0] = Q[1] & Q[0];
21 end
22 endmodule

106
Chapter 14

Digital logic and Verilog, Part IX


(W8.2)

14.1 Sequential Circuits


14.1.1 Registers

One flip-flop stores one bit of


information; thus, for n bits we
need n flip-flops.

n-bit structures consisting of


flip-flops are commonly referred
to as registers (with 2n dis-
tinct states).

Note:

- Clock (CLK) is common


to all flip-flops.
- Reset (CLR) is common
to all flip-flops.

107
CHAPTER 14. DIGITAL LOGIC AND VERILOG, PART IX (W8.2)

14.1.2 Registers (Verilog)


1 module regn (D, CLK, CLR, Q);
2 parameter n = 16; // 16 as an example
3 input [n-1:0] D;
4 input CLR, CLK;
5 output reg [n-1:0] Q;
6 always @ (posedge CLK or posedge CLR)
7 begin
8 if (CLR == 1)
9 Q <= 0;
10 else
11 Q <= D;
12 end
13 endmodule

14.2 Shift Registers


14.2.1 Serial Input, Serial Output Shift Register
Personal Remark: You probably thought, What’s the di↵erence between this and the classic
shifting using MUX we saw in 8.5.1?
A shift register shifts data one bit per clock cycle using flip-flops, while a MUX shift can shift
data by multiple positions in a single clock cycle using multiplexers. Simply put, Shift registers
are more efficient for simple, sequential bit shifting operations, while MUX shifts are better for
high-speed, multi-bit shifting in complex digital circuits.

Shift registers shift their n-bit value one bit to the left or right.

– Take 1-bit input (serial) and, sometimes, n-bit input (parallel).


– Produce 1-bit output (serial) or n-bit output (parallel).

These are used in various applications, such as:


Serial-to-parallel conversion, data storage, arithmetic, frequency division.

108
Notes by Ali EL AZDI

This visually shows the shi↵ting at each clock cycle. (The number to be shifted is the one on
the first column of the table), the one to be outputted is the one on the last column.

TCLK IN Q3 Q2 Q1 Q0 (OUT)
t0 1 0 0 0 0
t1 0 1 0 0 0
t2 1 0 1 0 0
t3 1 1 0 1 0
t4 1 1 1 0 1
t5 0 1 1 1 0
t6 0 0 1 1 1
t7 0 0 0 1 1

14.2.2 Parallel Input, Parallel Output Shift Register


Faster than last one, allows shi↵ting multiple bits at once
Parallel input, parallel output
shift registers shift their n-
bit value one bit to the left or
right.

– n-bit input D (parallel).


– 1 bit input IN (serial).
– n-bit output (parallel).

The timing diagram for this shift register, numbers in base 16 represent the parallel input and
output (each number is actually a 4-bit number input/output to D1,D2,D3,D4)

109
CHAPTER 14. DIGITAL LOGIC AND VERILOG, PART IX (W8.2)

14.3 Shift Registers (Verilog)


Section 14.3 covers this part in details.

14.3.1 Serial input/output Shift Registers


1 module shiftn (IN, CLR, CLK,
OUT);
2 parameter n = 4; // 4-bit
shifter
3 input IN, CLR, CLK;
4 output OUT;
5 reg [n-1:0] Q; // internal
6 always @ (posedge CLK or
posedge CLR)
7 begin
8 if (CLR == 1) Q <= 0;
9 else Q <= {IN, Q[n
-1:1]};
10 end
11 assign OUT = Q[0];
12 endmodule

14.3.2 Parallel input/output Shift Registers


1 module shiftn (D, IN, SEL, CLR
, CLK, Q);
2 parameter n = 4; // 4-bit
reg
3 input [n-1:0] D;
4 input IN, SEL, CLR, CLK;
5 output reg [n-1:0] Q;
6 integer k; // loop iterator
7 always @ (posedge CLK or
posedge CLR) begin
8 if (CLR == 1) Q <= 0;
9 else if (SEL == 1) Q <= D;
10 else begin
11 for (k = 0; k < n-1; k =
k+1) // for loop
12 begin
13 Q[k] <= Q[k+1];
14 end
15 Q[n-1] <= IN;
16 end
17 end
18 endmodule

110
Notes by Ali EL AZDI

14.4 Counters
Simple circuits that increment or decrement their value by 1, often used in various applications
such as counting occurrences of events or as timers, can be realized as add/sub circuits, though
that approach is generally considered overkill.

Example - Counter Up with an Enable Signal

The inputs of FF are defined


as:
D 0 = Q0 EN
D 1 = Q1 (Q0 EN )
D 2 = Q2 (Q0 Q1 EN )
D 3 = Q3 (Q0 Q1 Q2 EN )

In an n-bit counter case:

Di = Qi (Q0 Q1 · · · Qi 2 Qi 1 EN )

Modulo 2n counter:

– Every 2n clock cycles, the


output is zero
With the corresponding timing diagram:

111
CHAPTER 14. DIGITAL LOGIC AND VERILOG, PART IX (W8.2)

Example - Counter with Parallel-Load Capability

It is often necessary to start count-


ing with initial value 0, but some-
times it is desirable to start with a
di↵erent value.

– Parallel-load capability allows


that.

In the circuit to the right:

– LOAD = 0: circuit can count


– LOAD = 1: new value D is
loaded

Example - Modulo m (m < 2n ) Counter


To create a modulo m (m < 2n )
counter (for example, m = 10):

– Start from the counter with


parallel-load capability.
– Set load active when the count
reaches m 1 to restart count-
ing from zero the next clock
cycle.

112
Notes by Ali EL AZDI

14.5 Counters (Verilog)


Section 14.5 covers this part in details.

14.5.1 Counter Up with an Enable Signal

1 module upcount (EN, CLR, CLK,


Q);
2 parameter n = 4; // 4-bit
counter
3 input EN, CLR, CLK;
4 output reg [n-1:0] Q;
5 always @ (posedge CLK or
posedge CLR)
6 begin
7 if (CLR == 1) Q <= 0;
8 else if (EN == 1) Q <= Q +
1;
9 end
10 endmodule

14.5.2 Counter with Parallel-Load Capability

1 module upcount (D, EN, LOAD,


CLR, CLK, Q);
2 parameter n = 4; // 4-bit
counter
3 input [n-1:0] D;
4 input EN, LOAD, CLR, CLK;
5 output reg [n-1:0] Q;
6 always @ (posedge CLK or
posedge CLR)
7 begin
8 if (CLR == 1) Q <= 0;
9 else if (LOAD == 1) Q <= D
;
10 else if (EN == 1) Q <= Q +
1;
11 end
12 endmodule

113
CHAPTER 14. DIGITAL LOGIC AND VERILOG, PART IX (W8.2)

14.6 Verilog Part 4.


14.6.1 For Loop
The initial index is evaluated once, before the
first loop iteration (e.g., k = 0)

In each loop iteration, the begin-end block is


performed, and then the increment statement is
evaluated (eg. k = k + 1) 1 for (initial index; terminal
index; increment)
Finally, the terminal index condition is checked 2 begin
3 statements;
– If true, another loop iteration is performed, 4 end
otherwise the loop terminates
– Contrary to testing, for synthesis, the ter-
minal index condition has to compare the
loop index to a constant value (e.g., k <
8)

14.6.2 Logical Operators


Logical operators in Verilog are used in conditional expressions, treating operands as true or
false to produce an output of 1 (true) or 0 (false). Ordered in terms of Precedence:

Operator Description
! logical not
== logical equality
!= logical inequality
&& logical and
|| logical or

14.6.3 Relational Operators


Operator Description
a < b a less than b
a > b a greater than b
a <= b a less than or equal to b
a >= b a greater than or equal to b

These operators have the same precedence level.


If operands are of unequal bit lengths, the smaller operand shall be zero-extended (if unsigned)
or sign-extended (if signed) to the size of the larger one. Equal precedence.

14.6.4 Equality Operators in Verilog


Equality operators compare operands bit for bit. The result is 0 if the comparison fails and 1
otherwise.

114
Notes by Ali EL AZDI

Operator Description Details


a == b equality a is equal to b, the result can be 0, 1, or unknown (x or z)
a != b inequality a is not equal to b, the result can be 0, 1, or unknown (x or z)
a === b case equality a is equal to b, including unknown(x) or high-impedance(z) states
a !=== b case inequality a is not equal to b, including unknown(x) and high-impedance(z) states

These equality operators have the same precedence level, which is lower than that of relational
operators.

115
Chapter 15

Digital logic and Verilog (Part X)


(W9.1-W10.1)

15.1 Flip-flop Timing Constraints and Parameters


15.1.1 Synchronous System Design
In practical circuits, the outputs of sequential logic elements (registers) connect to
the inputs of other sequential logic elements, typically with some combinational
logic between FFs, introducing delays, and for correct circuit operation, timing
constraints must be met.

D Flip-Flop Input Timing Constraints

The signal on the input D of a D Flip-


Flop (DFF) must be stable around the
active clock edge (the edge that cap-
tures the signal).

The input D must remain stable during:

– Setup time: the period before the


active clock edge.
– Hold time: the period after the
active clock edge.

If the input timing constraints are not


satisfied, the DFF will not operate cor-
rectly.

Violating these timing constraints leads


to a condition called metastability.

116
Notes by Ali EL AZDI

D Flip-Flop Output Timing Parameters


Remember, Q, the output, CLK, the clock sync

Timing Intervals:

– tccQ (earliest change): Shown as the blue


dashed line on the diagram, indicating the
earliest time Q starts to change after the
clock edge.
– tpcQ (latest change): Shown as the green
dashed line, indicating the latest time Q
finishes changing after the clock edge.
– The region between these two dashed lines
represents the uncertainty interval where the
output Q is in transition, and this time is
collectively referred to as tcQ .

15.1.2 Meeting FF Timing Constraints

Sequential logic elements’ outputs connect to inputs of other sequential logic elements.
For correct operation, all FFoutput-to-FFinput paths must meet timing constraints.

The value at input D2 must be stable:

– At least tsetup before the active clock edge.


– At least thold after the active clock edge.

Longest and shortest delay paths are most impor-


tant.

Setup-Time Constraints

To ensure correct operation, setup-time con-


straints must be met. This involves the longest
possible delay paths:

The total delay should be less than the


clock period.

Thus, tsetup + tcQ,max + tcomb,max  TCLK

tcQ,max : Longest clock-to-Q delay

tcomb,max : Longest path delay through


combinational logic

117
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

Hold-Time Constraints
Hold-time constraints ensure stability immedi-
ately after the clock edge:

The total delay should be more than the


hold time.

Formula: tcQ,min + tcomb,min thold

tcQ,min : Shortest clock-to-Q delay

tcomb,min : Shortest path delay through


combinational logic

Typically, thold ⇡ 0 in real circuits.

15.1.3 Timing Analysis of a Simple Circuit


Personal Remark: Read the parameters then read the Hold-Time Violations part to better
understand what we’re trying to achive
Given the following flip-flop (FF)
timing parameters:

- Setup time, tsetup = 0.6 ns

- Hold time, thold = 0.4 ns

- Clock-to-Q delay,
tCQ : 0.8 ns  tCQ  1.0 ns

and the delay of the NOT gate,


tN OT = 1.1 ns.

Maximum Clock Frequency


To find the maximum clock frequency fmax for which the circuit will operate properly, we consider
the worst-case delay path:

1. Starts when data is loaded into the FF on the rising clock edge.

2. Propagates to the Q output after tCQ .

3. Propagates through the NOT gate with delay tN OT .

4. Ends at the input D, where it must meet the setup requirement.

Blue path in the upper image


Thus, the shortest allowed clock period Tmin is given by:

Tmin = tsetup + tCQ,max + tN OT = 0.6 ns + 1.0 ns + 1.1 ns = 2.7 ns

And the maximum operating frequency fmax is:

1 1
fmax = = ⇡ 370.37 MHz
Tmin 2.7 ns

118
Notes by Ali EL AZDI

Hold-Time Violations
To check for hold-time violations, we examine the shortest path between the rising clock edge
and the change of input D:

tmin = tCQ,min + tN OT = 0.8 ns + 1.1 ns = 1.9 ns

Hold-time constraints are satisfied if:

tmin thold

In this circuit, the hold-time constraints are satisfied as:

1.9 ns 0.4 ns

Therefore, the circuit does not su↵er from hold-time violations.

15.1.4 Timing Analysis of a Counter

Given the same FF timing parame-


ters as in the previous example:

Setup time, tsetup = 0.6 ns

Hold time, thold = 0.4 ns

Clock-to-Q delay,
tCQ : 0.8 ns  tCQ  1.0 ns

With gate delays:

AND gate delay, tAN D = 1.2 ns

XOR gate delay, tXOR = 1.3 ns

Maximum Operating Frequency


To find the maximum operating frequency fmax , we consider the longest path in the circuit:

Paths from output Q0 to the inputs of FFs:

t(Q0 , Di ) = tCQ + i · tAN D + tXOR , 0i3

The longest path is t(Q0 , D3 ) = tCQ,max +3·tAN D +tXOR = 1.0 ns+3·1.2 ns+1.3 ns = 5.9 ns

The shortest clock period that satisfies the setup-time requirements is:

Tmin = tsetup + tmax = 0.6 ns + 5.9 ns = 6.5 ns

Thus, the maximum operating frequency fmax is:


1 1
fmax = = ⇡ 153.84 MHz
Tmin 6.5 ns

119
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

Hold-Time Violations
To check for hold-time violations, we examine the shortest paths between the rising clock edge
and the change of one of the FF inputs:

Shortest path is t(Qi , Di ) = tCQ + tXOR , 0i3

Minimum delay tmin = tCQ,min + tXOR = 0.8 ns + 1.3 ns = 2.1 ns

Hold-time requirements are satisfied if:

tmin thold

In this circuit, the hold-time requirements are satisfied as:

2.1 ns 0.4 ns

Therefore, the circuit does not su↵er from hold-time violations.

15.2 Metastability

Metastability occurs in a D flip-flop


when the data input D is not stable
around the active clock edge.
This causes the output to initially be
stuck at an intermediate voltage level
before eventually settling to a logic 0
or 1 in an unpredictable manner.

15.3 Synchronizer (Shift Register)


Metastability arises from asyn-
chronous input signals and can be
mitigated by using a shift register in
the signal path.

FF1’s output may enter


metastability.

A sufficiently long clock period


allows FF1’s output to stabilize
to 0 or 1 before the next clock
edge.

FF2 then operates correctly,


preventing metastability from
propagating.

120
Notes by Ali EL AZDI

For this part, I took some liberties in the way I organized the ideas presented
by the professor as I found that presenting the same idea twice, with then without
clock skew, was quite lengthy and redundant. Of course, feel free to take a look at
the Digital Logic and Verilog X (extended), if you feel like the professor’s approach
was better.

15.4 Life of D: Lasting One Clock Cycle


The signal ‘D‘ undergoes a lifecycle within a digital system that repeats every clock cycle. This
lifecycle can be described as follows:
1. Born as Q of the Source Flip-Flop
(FF): The signal D starts its journey as
the output (Q) of a source flip-flop.

2. Journey through Combinational


Logic: After being emitted from the
source flip-flop, ‘D‘ travels through var-
ious combinational logic components.
tCQ + tcomb

3. Arrives at the Destination FF: The


signal ‘D‘ reaches the input of the desti-
nation flip-flop. tarrival = tCQ + tcomb

4. Waits to be Captured on Clock


Edge: At the destination flip-flop, ‘D‘
waits for the next clock edge.

5. Gets Captured on the Clock Edge:


When the clock edge arrives, the desti-
nation flip-flop captures the signal D.
tcapture = tarrival + tsetup

6. Waits to be Replaced: After being


captured, ‘D‘ stays as the output of the
destination flip-flop until it is replaced
by a new signal. tcycle = tCQ + tcomb +
tsetup + thold
This cycle repeats every clock cycle, ensuring the continuous flow of data through the digital
system.

121
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

For convinience, the circuit diagram:

15.4.1 Born as Q of the Source Flip-Flop (FF)


The signal D starts its journey as the
output (Q) of a source flip-flop. The tran-
sition from the input D to the output Q
involves a clock-to-Q delay, tCQ , which
can vary between tCQ,min and tCQ,max .

The output Q changes after the


clock-to-Q delay.

The clock-to-Q delay can range


from tCQ,min to tCQ,max .

Updating the output of the source FF


(QS ) takes some variable clock-to-Q delay.

15.4.2 Journey through Combinational Logic


After being emitted from the source flip-
flop, ‘D‘ travels through various combina-
tional logic components.
This part of the journey involves process-
ing and transformation of the signal.
Time taken: tCQ + tcomb .

Starts as QS - D starts the journey as


QS .
Ends as DD - D ends the journey as DD ,
the input of the destination flip-flop.
Duration- The journey duration is tcomb .

15.4.3 Arrives at the Destination FF


The signal ‘D‘ reaches the input of the
destination flip-flop. The arrival time of
the signal can be represented as tarrival =
tCQ + tcomb .

Arrival Time: tarrival = tCQ + tcomb

122
Notes by Ali EL AZDI

15.4.4 Waits to be Captured on Clock Edge


At the destination flip-flop, ‘D‘ waits for the next
clock edge. This waiting period is crucial as the
signal is prepared to be synchronized with the sys-
tem’s clock.

Stable During Wait: During the ”wait”,


DD should be stable.

Minimum Wait Time: The wait must be


at least as long as the setup time tsetup for
the destination FF to capture D correctly.

15.4.5 Gets Captured on the Clock Edge


When the clock edge arrives, the destination flip-
flop captures the signal D. The capture time can
be calculated as tcapture = tarrival + tsetup .

Capture Time: tcapture = tarrival + tsetup

Process: The destination FF takes the value


on DD and works on memorizing it and pass-
ing it to the output QD .

15.4.6 Waits to be Replaced


After being captured, ‘D‘ stays as the output of the
destination flip-flop until it is replaced by a new
signal in the next clock cycle. The total cycle time
is given by tcycle = tCQ + tcomb + tsetup + thold .

Hold Time: The ”wait” must be at least as


long as the hold time thold for the destination
FF to capture DD correctly.

Cycle Time: tcycle = tCQ +tcomb +tsetup +thold

This cycle repeats every clock cycle, ensuring the


continuous flow of data through the digital system.

123
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

15.5 Clock Skew


In real circuits, the clock signal may not arrive at all FFs at the same time because of the
variations in the delay of the wires that carry it.
This variation in the arrival time of the clock signal between di↵erent flip-flops is called clock
skew, and it can lead to timing errors and reduced performance in a circuit.

Clock skew is defined as the di↵erence in arrival times of the clock signal at di↵erent flip-flops:

tskew = D S

with i being the arrival time of the clock signal at F Fi .

15.5.1 Clock Delays


Clock arriving to the flip-flops is delayed with respect to the clock source

Positive Clock Skew

Positive clock skew between CLKD and CLKS


means that the rising edge of CLKD is delayed
(late) with respect to the rising edge of CLKS .
tskew = D S >0

Additional impact of positive clock skew on


timing and circuit performance.

124
Notes by Ali EL AZDI

Negative Clock Skew

Negative clock skew between CLKD and


CLKS means that the rising edge of CLKD is
advanced (early) with respect to the rising
edge of CLKS . tskew = D S <0

Additional impact of negative clock skew on


timing and circuit performance.

15.6 Life of D: Lasting One Clock Cycle (with Clock


Skew)

The signal ‘D‘ undergoes a lifecycle within a digital system that repeats every clock cycle. This
lifecycle can be described as follows: Personal Remark: Basically what you should retain from
this section
1. Born as Q of the Source Flip-Flop
(FF): The signal D starts as the output
(Q) of a source flip-flop.

2. Journey through Combinational


Logic: ‘D‘ travels through combinational
logic. tCQ + tcomb

3. Arrives at the Destination FF: ‘D‘


reaches the destination flip-flop input.
tarrival = tCQ + tcomb

4. Waits to be Captured on Clock Edge:


‘D‘ waits for the next clock edge. Clock
skew a↵ects this wait time.

5. Gets Captured on the Clock Edge:


The destination flip-flop captures ‘D‘.
tcapture = tarrival + tsetup ± tskew

6. Waits to be Replaced: ‘D‘ stays as the


output until replaced by a new signal.
tcycle = tCQ + tcomb + tsetup + thold ± tskew

This cycle, adjusted for clock skew, ensures the continuous flow of data through the digital
system but may a↵ect timing and performance.

125
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

15.7 Timing Constraints in the Presence of Clock


Skew
To ensure proper timing in the presence of clock skew, both setup-time and hold-time constraints
must be met.

15.7.1 Setup-Time Constraint


The setup-time constraint must satisfy:

TCLK + D ( S + tCQ + tcomb ) tsetup

Rewritten for the worst-case scenario:

tCQ,max + tcomb,max + tsetup ( D S)  TCLK

15.7.2 Hold-Time Constraint


The hold-time constraint must satisfy:

tCQ + tcomb + S D thold

Rewritten for the worst-case scenario:

tCQ,min + tcomb,min ( D S) thold

126
Notes by Ali EL AZDI

15.7.3 Implications of Clock Skew on the Max Operating Fre-


quency
- Recall:
1
tCQ,max + tcomb,max + tsetup ( D S)  TCLK =
fCLK
- Substituting tskew = D S:

1
tCQ,max + tcomb,max + tsetup tskew  TCLK =
fCLK
1 1
tCQ,max + tcomb,max + tsetup tskew = tskew =
fmax,skew=0 fmax
- Positive skew improves the max frequency:
1 1
> ) fmax > fmax,skew=0
fmax,skew=0 fmax

- Negative skew worsens the max frequency:


1 1
< ) fmax < fmax,skew=0
fmax,skew=0 fmax

What ifs...
- Q1: What if the circuit cannot work correctly at the desired frequency due to
unsatisfied setup-time constraints?

1
tCQ,max + tcomb,max + tsetup tskew  TCLK =
fCLK
A1: Redesign the combinational logic to reduce the combinational path delay; try to
increase the clock skew. In practice, we let computer-aided design tools do this for us.

- Implications of Clock Skew on the Max Operating Frequency


Recall:
1
tCQ,max + tcomb,max + tsetup ( D S)  TCLK =
fCLK
Substituting tskew = D S:

1
tCQ,max + tcomb,max + tsetup tskew  TCLK =
fCLK
1 1
tCQ,max + tcomb,max + tsetup tskew = tskew =
fmax,skew=0 fmax
Positive skew improves the max frequency:
1 1
> ) fmax > fmax,skew=0
fmax,skew=0 fmax

Negative skew worsens the max frequency:


1 1
< ) fmax < fmax,skew=0
fmax,skew=0 fmax

127
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

- Q2: What if the circuit cannot work correctly due to unsatisfied hold-time
constraints?

tCQ,min + tcomb,min tskew thold

A2: Insert bu↵ers on the short combinational paths to increase their delay; try to reduce
the clock skew. In practice, we let computer-aided design tools do this for us.

- Implications of Clock Skew on Meeting the Hold-Time Constraints

Recall:
tCQ,min + tcomb,min ( D S) thold

Substituting tskew = D S:

tCQ,min + tcomb,min tskew thold

Basically...

Positive skew makes meeting hold-time constraints more difficult

Negative clock skew makes meeting hold-time constraints easier

15.7.4 Timing Analysis with a Clock Skew


Algorithm for Finding fmax

Personal Remark: Important!!

1 - Identify all Q-to-D paths

2 - For every such path

(a) Compute its longest combinational delay


(b) Find the shortest clock period that satisfies the path’s setup-time constraint

* Remember to include clock delays in the expressions

3 - Find the shortest clock period TCLK that satisfies the setup-time constraints of all those
paths
1
4 - Compute fmax = TCLK

128
Notes by Ali EL AZDI

15.7.5 Example Analysis with Clock Skew

FF timing parameters

tsetup = 0.6 ns; thold = 0.4 ns

0.8 ns  tcQ  1 ns

and gate delays tAND = 1.2 ns and tXOR =


1.3 ns
Assume clock delays:

0 =0 1 =0 2 =0 3 = 2 ns

(a) Find the max operating frequency fmax


(b) Are there hold-time violations in this circuit?

Note: For simplicity, we will assume that EN is available at the rising clock edge.

Step 1 - Identify all Q-to-D paths

We already computed delays of all


paths (see earlier example); let us
focus on only the paths a↵ected by
clock delays

As clock at FF3 is delayed, the Q-


to-D paths starting or ending at
FF3 are the only ones a↵ected

- Q0 to D3
- Q1 to D3
- Q2 to D3
- Q3 to D3

129
CHAPTER 15. DIGITAL LOGIC AND VERILOG (PART X) (W9.1-W10.1)

Step 2a - For all paths, find the longest combinational path delay

- Q0 to D3:
tcomb = 3 ⇥ tAND + tXOR = 3 ⇥ 1.2 +
1.3 = 4.9 ns

- Q1 to D3:
tcomb = 2 ⇥ tAND + tXOR = 2 ⇥ 1.2 +
1.3 = 3.7 ns

- Q2 to D3:
tcomb = tAND + tXOR = 1.2 + 1.3 =
2.5 ns

- Q3 to D3:
tcomb = tXOR = 1.3 ns

Step 2b - Find the shortest clock period that satisfies the path’s setup-time
constraint
Remember to include clock skew in the expressions

tcQ,max + tcomb, max + tsetup ( D S)  TCLK

- Q0 to D3: 1 + 4.9 + 0.6 (2 0) = 4.5 ns

- Q1 to D3: 1 + 3.7 + 0.6 (2 0) = 3.3 ns

- Q2 to D3: 1 + 2.5 + 0.6 (2 0) = 2.1 ns

- Q3 to D3: 1 + 1.3 + 0.6 (2 2) = 2.9 ns

Step 3 - Find the shortest period that satisfies all paths


Clock period that satisfies all paths involving FF3:

max(4.5, 3.3, 2.1, 2.9) = 4.5 ns

Clock period that satisfies other paths is determined by the path with the longest combi-
national delay:

- Q0 to D2: tcomb = 2 ⇥ tAND + tXOR = 2 ⇥ 1.2 + 1.3 = 3.7 ns

Q0 to D2 : 1 + 3.7 + 0.6 + (0 0) = 5.3 ns

Finally, the shortest clock period that satisfies all paths

TCLK = max(4.5, 5.3) = 5.3 ns

130
Notes by Ali EL AZDI

Step 4 - Compute the max operating frequency


Thus the max operating frequency is:
1
fmax = ⇡ 188 MHz
TCLK ns

Algorithm for Checking Hold-Time Violations


Personal Remark: Again, Important!!

1 Identify all Q-to-D paths

2 For every such path

– Compute its shortest combinational delay


– Verify if hold-time constraint is satisfied
∗ Remember to include clock delays in the expressions

Step 1 - Identify all Q-to-D paths


We already verified hold-time constraints for all
paths (see earlier example);
Therefore, we now focus only on the paths in-
volving FF3, because clock at FF3 is delayed.

Step 2a - Find min combinational


path delay
- Q0 to D3:
tcomb = 3 ⇥ tAND + tXOR = 3 ⇥ 1.2 + 1.3 = 4.9 ns
- Q1 to D3:
tcomb = 2 ⇥ tAND + tXOR = 2 ⇥ 1.2 + 1.3 = 3.7 ns
- Q2 to D3:
tcomb = tAND + tXOR = 1.2 + 1.3 = 2.5 ns
- Q3 to D3:
tcomb = tXOR = 1.3 ns

Step 2b - Given the clock delay to the source FF, verify if hold-time constraint
is satisfied
tcQ,min + tcomb,min ( D S) thold
- Q0 to D3: 0.8 + 4.7 (2 0) =
3.5 ns > 0.4 ns

- Q1 to D3: 0.8 + 3.7 (2 0) =


2.5 ns > 0.4 ns Conclusion
All relevant paths satisfy hold-time
- Q2 to D3: 0.8 + 2.5 (2 0) = constraints.
1.3 ns > 0.4 ns

- Q3 to D3: 0.8 + 1.3 (2 2) =


2.1 ns > 0.4 ns

131
Chapter 16

Digital logic and Verilog, Part XI


(W10.2)

16.1 n to 2n Binary Decoders

A decoder is a logic circuit that


takes an n-bit binary input and
produces a 2n -bit output, where
only one bit is logic 1 and the rest
are logic 0.

Decoding the input: The output


bit at the index corresponding to
the decimal equivalent m of the n-
bit input is set to logic 1; all other
output bits are logic 0.

Decoder outputs are one-hot en-


coded, meaning only one bit is set to
1 (“hot”).

Quick Example for n = 2:

- Input: 00 (binary) ! Output: 0001 (the 1 is in the 0th position)


- Input: 01 (binary) ! Output: 0010 (the 1 is in the 1st position)
- Input: 10 (binary) ! Output: 0100 (the 1 is in the 2nd position)
- Input: 11 (binary) ! Output: 1000 (the 1 is in the 3rd position)

132
Notes by Ali EL AZDI

Example - 2-to-4 Binary Decoder


A (binary) decoder with n = 2 inputs and
2n = 4 outputs
The input (w1 w0 ) corresponds to binary num-
bers

– (00)2 = (0)10 ; (01)2 = (1)10 ; (10)2 =


(2)10 ; (11)2 = (3)10

Only one bit in the output vector


(y3 , y2 , y1 , y0 ) is set

– (w1 w0 ) = (00)2 = (0)10 ! y0 = 1


– (w1 w0 ) = (01)2 = (1)10 ! y1 = 1
– (w1 w0 ) = (10)2 = (2)10 ! y2 = 1
– (w1 w0 ) = (11)2 = (3)10 ! y3 = 1

w1 w0 y0 y1 y2 y3
0 0 1 0 0 0
0 1 0 1 0 0
1 0 0 0 1 0
1 1 0 0 0 1

y0 = w 1 w 0
y1 = w 1 w 0
y2 = w 1 w 0
y3 = w 1 w 0

2-to-4 Binary Decoder with an Enable


If the decoder is disabled, En = 0, then
no output will be set

En w1 w0 y0 y1 y2 y3
1 0 0 1 0 0 0
1 0 1 0 1 0 0
1 1 0 0 0 1 0
1 1 1 0 0 0 1
0 X X 0 0 0 0

y0 = En · w1 · w0
y1 = En · w1 · w0
y2 = En · w1 · w0
y3 = En · w1 · w0

133
CHAPTER 16. DIGITAL LOGIC AND VERILOG, PART XI (W10.2)

2-to-4 Binary Decoder with an Enable (Verilog)


Personal Remark: Obviously, like in Java, the ’ ?’ operator is used for one line conditional
statements.
1 module two_to_four_dec(W, En, Y);
2 input [1:0] W;
3 input En;
4 output [3:0] Y;
5 assign Y[0] = En ? (W == 2’b00)
: 0;
6 assign Y[1] = En ? (W == 2’b01)
: 0;
7 assign Y[2] = En ? (W == 2’b10)
: 0;
8 assign Y[3] = En ? (W == 2’b11)
: 0;
9 endmodule

4-to-16 Decoder with an Enable


A 4-to-16 decoder is constructed using a 2-to-
4 decoder (DEC1) at the root and four 2-to-4
decoders (DEC2, DEC3, DEC4, DEC5) in the
branches:

- Inputs: 4 binary digits (w3 w2 w1 w0 ) and an


enable signal (En).

- w3 w2 are fed into DEC1.

- DEC1 produces four outputs; each output is


fed into a 2-to-4 decoder.

- DEC1 outputs enable DEC2, DEC3, DEC4,


DEC5.

- w1 w0 are fed into the enabled branch decoder.

(w3 w2 w1 w0 , En) = (1011, 1)


OU TDEC1[2] = 1,
EnDEC4 = 1,
OU TDEC4[3] = y11 = 1

16.2 Memory
Personal Remark: Didn’t think the history of memory was worth mentioning (Slides 16-17,
Chapter XI) Memory types may vary in terms of:

- Capacity: how many bytes can be stored


- Density: how many bits per unit area (silicon)
- Speed: how much time it takes to read from it or write to it

134
Notes by Ali EL AZDI

- Writable or read-only
- Volatile or not: loses contents once the power supply is removed or not
(Out of Scope and Personal) For example, you might be aware of the di↵erence between RAM
and ROM. Random Access Memory (RAM) is volatile, meaning it loses its data when the power
is turned o↵, and is often used for fast runtime access. On the other hand, Read-Only Memory
(ROM) is non-volatile, meaning it retains its data even when the power is turned o↵, and is
typically used to store firmware or permanent software that does not need to be modified.

16.2.1 Abstract View of Memory

A two-dimensional array of 1-bit


memory elements (e.g., DFFs,
latches, capacitors)

One memory element mem[i],


where i is the row index in a two-
dimensional array of bits, includes
all bits in that row and is referred
to as one data word.

In memory terminology, instead


of saying the index, we say the
address of the data word

16.2.2 Word Sizes


Data word sizes and common terminology:

– 8 bits = one byte (Byte, B)


– 16 bits (also called half-word)
– 32 bits, 64 bits

Memory capacity is the total number of data bytes it can store (important)

– (Number of words) ⇥ (word width in bytes)

Number of words = 2N , where N is the number of bits of the address

16.2.3 Memory Capacity


Recall : memory capacity is the total number of data bytes it can store

Memory units (Wiki link)

– Kilobyte (KiB) = 210 B


– Megabyte (MiB) = 220 B
– Gigabyte (GiB) = 230 B
– Terabyte (TiB) = 240 B

135
CHAPTER 16. DIGITAL LOGIC AND VERILOG, PART XI (W10.2)

16.2.4 Access Protocol


Many variants exist, di↵ering in control
signals, their polarity, number of inputs
and outputs, width of inputs and outputs,
etc.
In this lecture, we consider the following
simple memory access protocol:

Synchronous write: on the rising


clock edge, if write enable (we) is
active, memory write takes place:
mem[addr] = data in

Asynchronous read: at all


times, memory read takes place:
data out = mem[addr]

16.2.5 Example - 16 x 8 Memory


Write

- Nawidth = log2 (16) = 4

- Ndwidth = 8

- addr = (0100)2 = (4)10

- data in = (B7)16

- we = 1

Memory read takes place and old


mem[4] appears at data out port
Memory write takes place and data in

overwrites mem[4]; new value of


mem[4] = (B7)16

136
Notes by Ali EL AZDI

Read

- Nawidth = log2 (16) = 4

- Ndwidth = 8

- addr = (0110)2 = (6)10

- we = 0
Memory read takes place and
mem[6] appears at data out port:
data out = mem[6] = (14)16
Memory write is not taking place

16.2.6 Memory as an Array of DFFs

- Addressing: 2-bit address (addr[1:0]) selects one of 4 rows via 2-to-4 decoder.

- Write Enable: we enables writing when active.

- Clock: clk synchronizes writing on rising edge.

- Data Input: data in[3:0] provides 4-bit data to write.

- Memory Cells: Flip-flops store data; enabled by decoder output.

- Data Output: 4-to-1 MUX selects data from addressed row to data out[3:0].

- The outputs of the address decoder, which enable one entire row of the memory array, are
called word lines

- The wires that carry data (input, output, or sometimes a shared in/out bus) are called bit
lines

137
CHAPTER 16. DIGITAL LOGIC AND VERILOG, PART XI (W10.2)

16.3 Verilog Part 5.


16.3.1 Arrays
Two dimensional arrays
In Verilog, we can declare two-dimensional arrays An array mem of Ndw data words, where
each word has Ndb bits, is declared as :

1 reg [Ndb-1:0] mem [Ndw-1:0];

16.3.2 Memory Module


A memory module can be defined as such :
1 module mem (addr, data_in, we, clk
, data_out);
2 parameter Nawidth = 2; //
arbitrary default
3 parameter Ndwidth = 4; //
arbitrary default
4 input we, clk; // write enable
and clock
5 input [Nawidth-1:0] addr;
6 input [Ndwidth-1:0] data_in;
7 output [Ndwidth-1:0] data_out;
8
9 // memory array
10 reg [Ndwidth-1:0] mem [2**
Nawidth-1:0];
11 always @(posedge clk) begin
12 if (we) begin
13 mem[addr] <= data_in;
14 end
15 end
16 assign data_out = mem[addr];
17 endmodule

16.3.3 Parameterized Verilog Modules


Verilog parameters can be put to good use, to allow instantiated modules to accept inputs and
outputs of arbitrary width
Basically allows to create a module that can be used for di↵erent word sizes.

1 module majority(I0, I1, I2, OUT);


2 parameter WIDTH = 1; // default
parameter value
3 input [WIDTH-1:0] I0, I1, I2;
4 output [WIDTH-1:0] OUT;
5 assign OUT = (I0 & I1) | (I0 &
I2) | (I1 & I2);
6 endmodule

Allowing for example, to instantiate using parameter 4, 8 (1 if not specified) :

138
Notes by Ali EL AZDI

1 // Instantiating majority module;


2 // Overriding the default value of WIDTH = 1;
3 // New value: WIDTH = 4;
4 majority #(.WIDTH(4)) U1 (.I0(A), .I1(B), .I2(C), .OUT(D));
5 // Instantiating majority module;
6 // Overriding the default value of WIDTH = 1;
7 // New value: WIDTH = 8;
8 majority #(.WIDTH(8)) U2 (.I0(X), .I1(Y), .I2(Z), .OUT(W));

16.3.4 Verilog Conditional Operator


Personal Remark: Like in java
1 A ? B : C

- Conditional operator ?: select one of the two alternate expressions (B, C) depending on
the value of a logical expression (A)

- If the logical expression (A) is true, it returns the first alternative (B)

- Otherwise, it returns the second alternative (C)

139
Chapter 17

Digital Logic and Verilog - Examples -


FSM (W10.2)

This is a small collection of examples of Finite State Machines (FSMs) and their implementation
in Verilog.
Personal Remark: Knowing what a Moore and Mealy machine is, is important to understand
this part of the course.

17.1 Moore FSM, with Verilog Implementation


Description of the Machine

- States are A, B, Z, each repre-


Current State S Next state Snext Output sented by at least 2 bits.
w
S z - Input is 1-bit input w
0 1
A A B 0 - Output is 1-bit z
B A C 0
C A C 1 - Reset input is Asynchronous,
power-on reset, active high

140
Notes by Ali EL AZDI

1 module fsm_Moore (input w, CLK, Reset, output reg z);


2 reg [1:0] S_next, S;
3 parameter A = 2’b00, B = 2’b01, C = 2’b10; // states
4 // Next-state logic
5 always @ (*) begin
6 case (S)
7 A: if (w == 0) S_next = A;
8 else S_next = B;
9 B: if (w == 0) S_next = A;
10 else S_next = C;
11 C: if (w == 0) S_next = A;
12 else S_next = C;
13 default: S_next = 2’bxx;
14 endcase
15 end
16 // State memory
17 always @ (posedge CLK or posedge Reset) begin
18 if (Reset == 1) S <= A;
19 else S <= S_next;
20 end
21 // Output logic
22 always @ (*) begin
23 z = (S == C);
24 end
25 endmodule

17.2 Mealy FSM, with Verilog Implementation


Description of the Machine

- States are A, B, represented


Current State S Input Next state Snext Output by at least 1 bit.
S w Snext z
A 0 A 0
- Input is 1-bit input w
A 1 B 0
- Output is 1-bit z
B 0 A 0
B 1 B 1 - Asynchronous, power-on re-
set, active high

141
CHAPTER 17. DIGITAL LOGIC AND VERILOG - EXAMPLES - FSM (W10.2)

1 module fsm_Mealy (input w, CLK, Reset, output reg z);


2 reg S_next, S;
3 parameter A = 1’b0, B = 1’b1; // states
4 // Next-state logic
5 always @ (*) begin
6 case (S)
7 A: if (w == 0) S_next = A;
8 else S_next = B;
9 B: if (w == 0) S_next = A;
10 else S_next = B;
11 default: S_next = 1’bx;
12 endcase
13 end
14 // State memory
15 always @ (posedge CLK or posedge Reset) begin
16 if (Reset == 1) S <= A;
17 else S <= S_next;
18 end
19 // Output logic
20 always @ (*) begin
21 z = 0;
22 if ((S == B) && (w == 1)) z = 1’b1;
23 end
24 endmodule

142
Chapter 18

Digital Logic and Verilog (Part XII)


(W11.1)

This part of the course might seem a litttttle bit more advanced, as it applies the last few chapters
at a higher level.
You do need to recall two things, what a Tri-State Driver is (only allows current to flow when
the enable signal is active) and what a Bus with Tri-State drivers is, basically allows multiple
modules(things) to be connected to a single ”bus”, again, current of the bus only flows when the
enable signal is active.
Also, don’t expect understanding the thinking behind going from an Idea to an Actual Verilog
program without having done the exercices

18.1 Swapping of two Registers


Here, we will be considering a system that will allow to swap two registers using one temporary
register.
Our first attempt will be using a bus with tri-state drivers, and the second attempt will be
using a bus with mux.

18.1.1 Using a Bus with Tri-State Drivers (Verilog)

We have the following FSM


States:

IDLE: No swapping
R2TOR3: First copy
R1TOR2: Second copy
R3TOR1: Third copy

With the following algorithm for swapping:

1 - Swap starts → Copy data from R2 to R3


2 - Copy data from R1 to R2
3 - Copy contents of R3 to R1 → Swap ends

143
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

And an asynchronous power-on reset

Translating this in Verilog gives us,


1 module control (clk, reset, swap, R1in, R1out, R2in, R2out, R3in, R3out,
done);
2 input clk, reset, swap;
3 output reg R1in, R1out, R2in, R2out, R3in, R3out, done;
4 parameter IDLE = 2’b00, R2TOR3 = 2’b01, R1TOR2 = 2’b10, R3TOR1 = 2’b11;
5 reg [1:0] S_next, S;
6 // Next-state logic
7 always @ (*) begin
8 S_next = IDLE; // default
9 case (S)
10 IDLE: if (swap) S_next = R2TOR3;
11 else S_next = IDLE;
12 R2TOR3: S_next = R1TOR2;
13 R1TOR2: S_next = R3TOR1;
14 R3TOR1: S_next = IDLE;
15 default: S_next = IDLE;
16 endcase
17 end
18 // State memory
19 always @ (posedge clk or posedge reset) begin
20 if (reset) S <= IDLE;
21 else S <= S_next;
22 end
23 // Output logic
24 always @ (*) begin
25 R1in = (S == R3TOR1);
26 R1out = (S == R1TOR2);
27 R2in = (S == R1TOR2);
28 R2out = (S == R2TOR3);
29 R3in = (S == R2TOR3);
30 R3out = (S == R3TOR1);
31 done = (S == R3TOR1);
32 end
33 endmodule

We may also define :


An n-bit register module:
1 module regn (D, clk, reset, en,
Q); A Tri-State driver bus module:
2 parameter n = 8; // default
1 module bustri (w, en, f);
3 input [n-1:0] D;
2 parameter n = 8; // default
4 input clk, reset, en;
3 input [n-1:0] w;
5 output reg [n-1:0] Q;
4 input en;
6 always @ (posedge clk or
5 output [n-1:0] f;
posedge reset) begin
6 assign f = en ? w : ’bz;
7 if (reset) Q <= 0;
7 endmodule
8 else if (en) Q <= D;
9 end
10 endmodule

144
Notes by Ali EL AZDI

Now using the FSM controller, the bus and the reg, we can defined the swapping module as
such:
1 module regswap (clk, reset, swap);
2 parameter width = 8;
3 input clk, reset, swap;
4 wire wR1in, wR1out, wR2in, wR2out, wR3in, wR3out, wdone;
5 wire [width-1:0] wR1, wR2, wR3, wBus;
6
7 // Instantiate controller module
8 control controller_module ( .clk (clk), .reset (reset), .swap (swap),
9 .R1in (wR1in), .R1out (wR1out), .R2in (wR2in), .R2out (wR2out),
10 .R3in (wR3in), .R3out (wR3out), .done (wdone));
11
12 // Instantiate registers
13 regn #(.n (width)) R1 (.D (wBus), .clk (clk), .reset (reset), .en (
wR1in), .Q (wR1));
14 regn #(.n (width)) R2 (.D (wBus), .clk (clk), .reset (reset), .en (
wR2in), .Q (wR2));
15 regn #(.n (width)) R3 (.D (wBus), .clk (clk), .reset (reset), .en (
wR3in), .Q (wR3));
16
17 // Bus with tri-state drivers
18 bustri #(.n (width)) bustri1 (.w (wR1), .en (wR1out), .f (wBus));
19 bustri #(.n (width)) bustri2 (.w (wR2), .en (wR2out), .f (wBus));
20 bustri #(.n (width)) bustri3 (.w (wR3), .en (wR3out), .f (wBus));
21 endmodule

18.1.2 Using a Bus with MUXes (Verilog)

We have the following FSM


States:

IDLE: No swapping
R2TOR3: First copy
R1TOR2: Second copy
R3TOR1: Third copy

With the following algorithm for swapping:

1 - Swap starts → Copy data from R2 to R3


2 - Copy data from R1 to R2
3 - Copy contents of R3 to R1 → Swap ends

And an asynchronous power-on reset

145
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

Translating this in Verilog gives us,


1 module controlbusmux (clk, reset, swap, R1in, R2in, R3in, done, sel);
2 input clk, reset, swap;
3 output reg R1in, R2in, R3in, done;
4 output reg [1:0] sel;
5 parameter IDLE = 2’b00, R2TOR3 = 2’b01, R1TOR2 = 2’b10, R3TOR1 = 2’b11;
6 reg [1:0] S_next, S;
7 // Next-state logic
8 always @ (*) begin
9 S_next = IDLE;
10 case (S)
11 IDLE: if (swap) S_next = R2TOR3;
12 else S_next = IDLE;
13 R2TOR3: S_next = R1TOR2;
14 R1TOR2: S_next = R3TOR1;
15 R3TOR1: S_next = IDLE;
16 default: S_next = IDLE;
17 endcase
18 end
19 // State memory
20 always @ (posedge clk or posedge reset) begin
21 if (reset) S <= IDLE;
22 else S <= S_next;
23 end
24 // Output logic
25 always @ (*) begin
26 R1in = (S == R3TOR1);
27 R2in = (S == R1TOR2);
28 R3in = (S == R2TOR3);
29 done = (S == R3TOR1);
30 sel = S;
31 end
32 endmodule

146
Notes by Ali EL AZDI

Giving us the following implementation for reg swpping with a bus of MUXes :

1 module regswapbusmux (clk, reset, swap);


2 parameter width = 8;
3 parameter IDLE = 2’b00, R2TOR3 = 2’b01;
4 parameter R1TOR2 = 2’b10, R3TOR1 = 2’b11;
5 input clk, reset, swap;
6 wire wR1in, wR2in, wR3in, wdone;
7 wire [width-1:0] wR1, wR2, wR3;
8 wire [1:0] wsel;
9 reg [width-1:0] wBus;
10 // Instantiate controller module
11 controlbusmux controller_module ( .clk (clk), .reset (reset), .swap (
swap),
12 .R1in (wR1in), .R2in (wR2in), .R3in (wR3in),
13 .done (wdone), .sel (wsel));
14 // Instantiate registers
15 regn #(.n (width)) R1 (.D (wBus), .clk (clk), .reset (reset), .en (
wR1in), .Q (wR1));
16 regn #(.n (width)) R2 (.D (wBus), .clk (clk), .reset (reset), .en (
wR2in), .Q (wR2));
17 regn #(.n (width)) R3 (.D (wBus), .clk (clk), .reset (reset), .en (
wR3in), .Q (wR3));
18 // Bus with a multiplexer
19 always @ (*) begin
20 wBus = wR1;
21 case (wsel)
22 IDLE: wBus = wR1;
23 R2TOR3: wBus = wR2;
24 R1TOR2: wBus = wR1;
25 R3TOR1: wBus = wR3;
26 default: wBus = wR1;
27 endcase
28 end
29 endmodule

18.2 Alternative ways to impelment Adders


A Full Adder in behavioral Verilog, can be modelled as such:

1 module fulladd (a, b, c_in, s,


c_out);
2 input a, b, c_in;
3 output s, c_out;
4 assign s = a ˆ b ˆ c_in;
5 assign c_out = (a & b) | (a &
c_in) | (b & c_in);
6 endmodule

147
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

18.2.1 Ripple Carry Adder Using a For Loop (Verilog)


To implement a Ripple-Carry Adder, we set the next carry to the Cout of the current stage, and
calculate the current sum as before.
1 module ripplecarry (Cin, A, B, S,
Cout);
2 parameter n = 32;
3 input Cin;
4 input [n-1:0] A, B;
5 output reg [n-1:0] S;
6 output reg Cout;
7 reg [n:0] C; // internal wires
8 integer k; // loop iterator, an
integer
9 always @(*) begin
10 C[0] = Cin;
11 for (k = 0; k < n; k = k+1)
begin
12 S[k] = A[k] ˆ B[k] ˆ C[k];
13 C[k+1] = (A[k] & B[k]) | (A[k]
& C[k]) | (B[k] & C[k]);
14 end
15 Cout = C[n];
16 end
17 endmodule

18.2.2 Generate Construct (Verilog)


The Verilog generate construct allows module instantiation within for loops and if-else
statements. Key points include:

- If a for loop is included in the generate block, the loop index variable must be of type
genvar.

- A genvar is an integer variable that:

Can only have values 0.


Can only be used inside generate blocks.

- The generate construct enables combining for loops with module instantiations e↵ec-
tively.

148
Notes by Ali EL AZDI

18.2.3 Ripple-Carry Adder with a generate Construct (Verilog)

1 module ripplecarrygenerate (Cin, A, B, S, Cout);


2 parameter n = 32;
3 input Cin;
4 input [n-1:0] A, B;
5 output [n-1:0] S; // must match the type of fulladd port .s
6 output Cout; // must match the type of fulladd port c_out
7 genvar g; // generate loop iterator, must have genvar type
8 wire [n:0] C; // must match the type of fulladd ports .c_in, c_out
9 assign C[0] = Cin;
10 // generate block
11 generate // optional keyword, helps readability
12 for (g = 0; g < n; g = g + 1) begin
13 fulladd stage (.a (A[g]), .b (B[g]), .c_in (C[g]), .s (S[g]), .c_out (C[g
+ 1]));
14 end
15 endgenerate // optional keyword, helps readability
16 assign Cout = C[n];
17 endmodule

18.3 Serial Adders


Serial Adders are adders that add bits serially, one bit at a time, if speed is not prority it’s a cost
e↵ective way to add numbers.

18.3.1 Circuit

- Shift-right registers output one bit


of a and b at a time.

- A down-counter (timer) counts the


number of cycles needed for addi-
tion, corresponding to the number
of bit pairs to add.

- The INIT signal loads new values


into all shift registers and reinitial-
izes the timer.

18.3.2 Serial Adder Mealy FSM

A Mealy FSM Serial Adder follows the following algorithm:

149
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

- Initialize the shift registers and the timer The Adder FSM has the following states:
(INIT input) - S0 = 0
- Load (in parallel) vectors A and B in their - S1 = 1
respective shift registers With S0 and S1 representing the carry
- Initialize the timer generated by the sum of the previous bits
- Clear the contents of the sum register (all We get the following State/output tables:
zeros)
- In each clock cycle

* Add a pair of bits (one bit of A and


one bit of B) using the Adder FSM
* Shift the resulting sum bit into the
Sum register
* Shift the vectors A and B to prepare
the next pair of bits
* Decrement the counter

- Stop when the timer finished counting

18.3.3 Serial Adder Mealy FSM (Verilog)


1 module serialadderfsm (input a, b, init, reset, clk,output reg sum);
2 parameter n = 8;
3 parameter S0 = 1’b0, S1 = 1’b1;
4 reg S_next, S;
5 always @(*) begin
6 S_next = S0;
7 case (S)
8 S0: begin
9 if (init) S_next = S0;
10 else if (a & b) S_next = S1;
11 else S_next = S0;
12 end
13 S1: begin
14 if (init) S_next = S0;
15 else if (˜a & ˜b) S_next = S0;
16 else S_next = S1;
17 end
18 default: S_next = S0;
19 endcase
20 end
21 // State memory, Power-on asynchronous reset
22 always @ (posedge clk or posedge reset) begin
23 if (reset) S <= S0;
24 else S <= S_next;
25 end
26 // Output logic
27 always @(*) begin
28 if (S == S0) sum = a ˆ b;
29 else sum = ˜(a ˆ b);
30 end
31 endmodule

150
Notes by Ali EL AZDI

18.4 From Verilg to Circuits

We have been writing Verilog models from their circuit drawing or their description and function-
ality, we will now be doing the inverse, given a Verilog model we will turn the model back to its
circuit and explain its functionality.
Enough with the talking, here’s the Verilog program we will be looking at:

1 module guesswhat (clk, resetn, la, s, Data, B, done);


2 parameter n = 8;
3 input clk, resetn, la, s;
4 input [n-1:0] Data;
5 output reg [3:0] B;
6 output reg done;
7
8 parameter S1 = 2’b00, S2 = 2’b01, S3 = 2’b10;
9 integer k;
10 reg [n-1:0] A;
11 wire z;
12 reg [1:0] S_next, S;
13 reg ea, eb, lb;
14
15 // State transition logic
16 always @(*) begin
17 S_next = S1;
18 case (S)
19 S1: if (!s) S_next = S1;
20 else S_next = S2;
21 S2: if (z == 0) S_next = S2;
22 else S_next = S3;
23 S3: if (s) S_next = S3;
24 else S_next = S1;
25 default: S_next = 2’bxx;
26 endcase
27 end
28
29 // Output control logic
30 always @(*) begin
31 ea = 0;
32 lb = 0;
33 eb = 0;
34 done = 0;
35 case (S)
36 S1: lb = 1;
37 S2: begin
38 ea = 1;
39 if (A[0]) eb = 1;
40 else eb = 0;
41 end
42 S3: done = 1;
43 endcase
44 end

151
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

1 // State register
2 always @(posedge clk or negedge resetn) begin
3 if (!resetn) S <= S1;
4 else S <= S_next;
5 end
6
7 // Output B register
8 always @(posedge clk or negedge resetn) begin
9 if (!resetn) B <= 0;
10 else if (lb) B <= 0;
11 else if (eb) B <= B + 1;
12 end
13

14 // Register A logic
15 always @(posedge clk or negedge resetn) begin
16 if (!resetn) A <= 0;
17 else if (la) A <= Data;
18 else if (ea) begin
19 for (k = n - 1; k > 0; k = k - 1) begin
20 A[k-1] <= A[k];
21 end
22 A[n-1] <= 1’b0;
23 end
24 end
25

26 // Zero detect logic


27 assign z = ˜| A;
28 endmodule
29 // END

Now, we can analyse this step by step, starting with the guesswhat declaration:
1 module guesswhat (clk, resetn, la,
s, Data, B, done); Step 1: Start by analyzing the module
2 parameter n = 8;
interfaces, parameters, and internal signals
3 input clk, resetn, la, s;
4 input [n-1:0] Data;
(wires) and variables (reg, integer).
5 output reg [3:0] B;
- The output, B, has a width di↵erent
6 output reg done;
7 parameter S1 = 2’b00, S2 = 2’b01, from the Data input.
S3 = 2’b10;
- S1,S2,S3, are likely states of an FSM
8 integer k;
9 reg [n-1:0] A; - integer k is likely a loop iterator
10 wire z;
11 reg [1:0] S_next, S; - and A is a register of the same width
12 reg ea, eb, lb; as Data input
13 //continues...

152
Notes by Ali EL AZDI

Next State Logic

Step 2: We analyze the Next State Logic,


which is likely part of an FSM.

- The FSM has three states, S1, S2, and


1 //... S3.
2 always @(*) begin
3 S_next = S1; - The FSM transitions are based on the
4 case (S) values of the input signals s and z.
5 S1: if (!s) S_next = S1;
6 else S_next = S2; Giving use the following state diagram
7 S2: if (z == 0) S_next = S2;
8 else S_next = S3;
9 S3: if (s) S_next = S3;
10 else S_next = S1;
11 default: S_next = 2’bxx;
12 endcase
13 end
14 // continues...

FSM Output Logic

1 //...
2 always @(*) begin
3 ea = 0; The FSM Output Logic will likelt look
4 lb = 0; like this:
5 eb = 0;
6 done = 0;
7 case (S)
8 S1: lb = 1;
9 S2: begin
10 ea = 1;
11 if (A[0]) eb = 1;
12 else eb = 0;
13 end
14 S3: done = 1; - S1: lb = 1, others zero.
15 endcase - S2 : ea = 1, eb = A[0], others zero.
16 end - S3 : done = 1, others zero.
17 // continues...

153
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

Sequential Circuits
FSM State Register
- negedge in the sensitivity list:
resetn is an asynchronous reset active low,
1 // ... external signal.
2 always @(posedge clk or negedge - State after power-on reset: S1;
resetn) begin Hence, S1 is the default state.
3 if (!resetn) S <= S1;
4 else S <= S_next;
5 end
6 // continues...

1 // ... B is the output of a counter


2 always @(posedge clk or negedge
resetn) begin - 1b clears it (loads all zeros)
3 if (!resetn) B <= 0;
4 else if (lb) B <= 0; * In S1 state
5 else if (eb) B <= B + 1;
6 end - eb enables it (allows counting)
7 // continues...
* In S2 state, if A[0] is 1

- B + 1: up counter

Shift register A

1 // ... - resetn: asynchronous reset


2 always @(posedge clk or negedge
resetn) begin – Active low, external signal
3 if (!resetn) A <= 0;
4 else if (la) A <= Data; - la initializes it (loads Data)
5 else if (ea) begin
6 for (k = n - 1; k >0; k = k – la is an external signal
- 1) begin – Data is also external
7 A[k-1] <= A[k];
8 end - for loop performs shift right
9 A[n-1] <= 1’b0;
10 end – Most significant bits cleared (re-
11 end placed by 1’b0)
12 // continues...
- ea enables shift right

– In state S2, while up-counter B


is enabled too

Combinational Logic

Now that we have a broad idea of the circuit, we need to understand when it stops

154
Notes by Ali EL AZDI

1 //...
The last assignment in the module,
2 assign z = ˜| A; z =⇠ |A, uses the Verilog reduction NOR
3 endmodule operator, which sets z to 1 when all bits
4 // END of vector A (the output of the shift regis-
ter) are zero.
All of this leads us to the following circuit:

18.5 Verilog Reduction Operators


Reduction operators in Verilog are unary operators that perform bitwise operations across all
bits of a vector operand to produce a single-bit result.

Operator Description
& reduction and
⇠& reduction nand
| reduction or
⇠| reduction nor
ˆ reduction xor
⇠ˆ reduction xnor

155
CHAPTER 18. DIGITAL LOGIC AND VERILOG (PART XII) (W11.1)

Examples
Consider the vector A = 80 b10101111:

- Example 1: z = &A
z = (((((((1 & 1) & 1) & 1) & 0) & 1) & 0) & 1) = 0

- Example 2: z = ⇠ˆA
z = ⇠(((((((1 ˆ 1) ˆ 1) ˆ 1) ˆ 0) ˆ 1) ˆ 0) ˆ 1) = 1

156

You might also like