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

5-HDL Coding and Test Bench Check-05!06!2024

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

5-HDL Coding and Test Bench Check-05!06!2024

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

BECE102L Digital Systems Design

Module: 2
Lexical Conventions, Ports and Modules, Operators, Dataflow Modelling, Gate Level
Modelling, Behavioural Modeling, Test Bench

Dr. Rohit Mathur


Assistant Professor Sr. Grade 1
School of Electronics Engineering
Importance of HDLs

❖ HDL is an acronym of Hardware Description Language.


❖ Two most commonly used HDLs:
▪ Verilog HDL (also called Verilog for short)
▪ VHDL (Very high-speed integrated circuits HDL)
❖ Features of HDLs:
▪ Design can be described at a very abstract level.
▪ Functional verification can be done early in the design cycle.
▪ Designing with HDLs is analogous to computer programming.

ECE Digital Logic Design


Popularity of Verilog HDL

❖ It is a general-purpose, easy to learn, and easy to


use HDL language.
❖ It allows different levels of abstraction to be mixed
in the same model.
❖ It is supported by all logic synthesis tools.
❖ It provides a powerful Programming Language
Interface (PLI).
▪ Allow us to develop our own CAD tools such as delay
calculator.
ECE Digital Logic Design
HDL-Based Design Flow

Front-end design

Back-end design

ECE Digital Logic Design


Modules – Hardware Module Concept

❖ The basic unit of a digital system is a module.


❖ Each module consists of:
▪ a core circuit (called internal or body) --- performs the required
function
▪ an interface (called ports) --- carries out the required
communication between
the core circuit
and outside.

ECE Digital Logic Design


Modules – Verilog HDL modules

❖ module --- The basic building block in Verilog HDL.


▪ It can be an element or a collection of lower-level design
blocks.

ECE Digital Logic Design


Lexical Conventions

❖ Verilog HDL uses almost the same lexical conventions as C


language.
▪ Identifiers consists of alphanumeric characters, _, and $.
• Verilog is a case-sensitive language just like C.
▪ White space: blank space (\b), tabs (\t), and new line (\n).
▪ Comments:
• // indicates that the remaining of the line is a comment.
• /* ….*/ indicates what in between them are comments.
▪ Sized number: <size>`<base format><number>
• 4`b1001 --- a 4-bit binary number
• 16`habcd --- a 16-bit hexadecimal number
ECE Digital Logic Design
Lexical Conventions

▪ Unsized number: `<base format><number>


• 2007 --- a 32-bit decimal number by default
• `habc --- a 32-bit hexadecimal number
▪ x or z values: x denotes an unknown value; z denotes a high impedance value.
▪ Negative number: -<size>`<base format><number>
• -4`b1001 --- a 4-bit binary number
• -16`habcd --- a 16-bit hexadecimal number
▪ ”_” and “?”
• 16`b0101_1001_1110_0000
• 8`b01??_11?? --- equivalent to a 8`b01zz_11zz

ECE Digital Logic Design


Lexical Conventions

▪ String: “Back to School and Have a Nice Semester”

❖ Coding style:
▪ Use lowercase letters for all signal names, variable names, and
port names.
▪ Use uppercase letters for names of constants and user-defined
types.
▪ Use meaningful names for signals, ports, functions, and
parameters.
ECE Digital Logic Design
The Value Set

❖ In Verilog HDL
▪ 0 and 1 represent logic values low and high, respectively.
▪ z indicates the high-impedance condition of a node or net.
▪ x indicates an unknown value of a net or node.

ECE Digital Logic Design


Data Types

❖ Verilog HDL has two classes of data types.


▪ Nets mean any hardware connection points.
▪ Variables represent any data storage elements.

ECE Digital Logic Design


Data Types

❖ A net variable
▪ can be referenced anywhere in a module.
▪ must be driven by a primitive, continuous assignment, force …
release, or module port.
❖ A variable
▪ can be referenced anywhere in a module.
▪ can be assigned value only within a procedural statement, task,
or function.
▪ cannot be an input or inout port in a module.
ECE Digital Logic Design
Module Modeling Styles

❖ Structural style
▪ Gate level comprises a set of interconnected gate primitives.
▪ Switch level consists of a set of interconnected switch
primitives.
❖ Dataflow style
▪ specifies the dataflow (i.e., data dependence) between
registers.
▪ is specified as a set of continuous assignment statements.

ECE Digital Logic Design


Module Modeling Styles

❖ Behavioral or algorithmic style


▪ is described in terms of the desired design algorithm
▪ is without concerning the hardware implementation details.
▪ can be described in any high-level programming language.
❖ Mixed style
▪ is the mixing use of above three modeling styles.
▪ is commonly used in modeling large designs.
❖ In industry, RTL (register-transfer level) means
▪ RTL = synthesizable behavioral + dataflow constructs
ECE Digital Logic Design
Port Declaration

❖ Port Declaration
▪ input: input ports.
▪ output: output ports.
▪ inout: bidirectional ports
❖ Port Connection Rules
▪ Named association
▪ Positional association

ECE Digital Logic Design


Port Declaration

ECE Digital Logic Design


ECE Digital Logic Design
Full adder

Sum = A̅BC
̅ in+A̅BCin+AB̅C̅in+ABCin =
(AB̅+A̅B)C̅in+(AB+A̅B)̅ Cin = (A⨁B)C̅in+(¯(A⨁B))Cin =
A⨁B⨁Cin

Cout = A̅BCin+AB̅Cin+ABC̅in+ABCin = AB+(A⨁B)Cin =


AB+ACin+BCin

ECE Digital Logic Design


Full adder

Ref https://de-iitr.vlabs.ac.in/exp/half-full-adder/theory.html

ECE Digital Logic Design


Structural modeling

// gate-level hierarchical description of 4-bit adder


// gate-level description of half adder
module half_adder (x, y, s, c);
input x, y;
output s, c;
// half adder body
// instantiate primitive gates
xor (s,x,y);
and (c,x,y);
endmodule

ECE Digital Logic Design


Structural modeling

// gate-level description of full adder


module full_adder (x, y, cin, s, cout);
input x, y, cin;
output s, cout;
wire s1, c1, c2; // outputs of both half adders
// full adder body
// instantiate the half adder
half_adder ha_1 (x, y, s1, c1);
half_adder ha_2 (cin, s1, s, c2);
or (cout, c1, c2);
endmodule

ECE Digital Logic Design


Structural modeling

// gate-level description of 4-bit adder


module four_bit_adder (x, y, c_in, sum, c_out);
input [3:0] x, y;
input c_in;
output [3:0] sum;
output c_out;
wire c1, c2, c3; // intermediate carries
// four_bit adder body
// instantiate the full adder
full_adder fa_1 (x[0], y[0], c_in, sum[0], c1);
full_adder fa_2 (x[1], y[1], c1, sum[1], c2);
full_adder fa_3 (x[2], y[2], c2, sum[2], c3);
full_adder fa_4 (x[3], y[3], c3, sum[3], c_out);
endmodule
ECE Digital Logic Design
Hierarchical Design

ECE Digital Logic Design


Dataflow Modeling

module full_adder_dataflow(x, y, c_in, sum, c_out);


// I/O port declarations
input x, y, c_in;
output sum, c_out;
// specify the function of a full adder
assign #5 {c_out, sum} = x + y + c_in;
endmodule

ECE Digital Logic Design


Behavioral Modeling

module full_adder_behavioral(x, y, c_in, sum, c_out);


// I/O port declarations
input x, y, c_in;
output sum, c_out;
reg sum, c_out;
// sum and c_out need to be
declared as reg types.
// specify the function of a full adder
always @(x, y, c_in)
// can also use always @(*) or always@(x
or y or c_in)
#5 {c_out, sum} = x + y + c_in;
endmodule
ECE Digital Logic Design
Mixed-Style Modeling

module full_adder_mixed_style(x, y, c_in, s, c_out);


// I/O port declarations
input x, y, c_in;
output s, c_out;
reg c_out;
wire s1, c1, c2;
// structural modeling of HA 1.
xor xor_ha1 (s1, x, y);
and and_ha1(c1, x, y);
// dataflow modeling of HA 2.
assign s = c_in ^ s1;
assign c2 = c_in & s1;
// behavioral modeling of output OR gate.
always @(c1, c2) // can also use always @(*)
c_out = c1 | c2;
endmodule
ECE Digital Logic Design
Basic Simulation Constructs

ECE Digital Logic Design


System Tasks for Simulation

❖ $display displays values of variables, string, or expressions


▪ $display(ep1, ep2, …, epn);
ep1, ep2, …, epn: quoted strings, variables, expressions.
❖ $monitor monitors a signal when its value changes.
▪ $monitor(ep1, ep2, …, epn);
❖ $monitoton enables monitoring operation.
❖ $monitotoff disables monitoring operation.
❖ $stop suspends the simulation.
❖ $finish terminates the simulation.

ECE Digital Logic Design


Time Scale for Simulations

❖ Time scale compiler directive


`timescale time_unit / time_precision
▪ The time_precision must not exceed the time_unit.
▪ For instance, with a timescale 1 ns/1 ps, the delay specification
#15 corresponds to 15 ns.
▪ It uses the same time unit in both behavioral and gate-level
modeling.
▪ For FPGA designs, it is suggested to use ns as the time unit.

ECE Digital Logic Design


Modeling and Simulation Example --- A 4-bit adder

// Gate-level description of 4-bit adder


module four_bit_adder (x, y, c_in, sum, c_out);
input [3:0] x, y;
input c_in;
output [3:0] sum;
output c_out;
wire C1,C2,C3; // Intermediate carries
// -- four_bit adder body–
// Instantiate the full adder
full_adder fa_1 (x[0],y[0],c_in,sum[0],C1);
full_adder fa_2 (x[1],y[1],C1,sum[1],C2);
full_adder fa_3 (x[2],y[2],C2,sum[2],C3);
full_adder fa_4 (x[3],y[3],C3,sum[3],c_out);
endmodule

ECE Digital Logic Design


Modeling and Simulation Example --- A 4-bit adder

After dissolving one full adder.


ECE Digital Logic Design
Modeling and Simulation Example --- A Test Bench

`timescale 1 ns / 100 ps // time unit is in ns.


module four_bit_adder_tb;
//Internal signals declarations:
reg [3:0] x;
reg [3:0] y;
reg c_in;
wire [3:0] sum;
wire c_out;
// Unit Under Test port map
four_bit_adder UUT (.x(x), .y(y), .c_in(c_in), .sum(sum), .c_out(c_out));
reg [7:0] i;
initial begin // for use in post-map and post-par simulations.
// $sdf_annotate ("four_bit_adder_map.sdf", four_bit_adder);
// $sdf_annotate ("four_bit_adder_timesim.sdf", four_bit_adder);
end
ECE Digital Logic Design
Modeling and Simulation Example --- A Test Bench

initial
for (i = 0; i <= 255; i = i + 1) begin
x[3:0] = i[7:4]; y[3:0] = i[3:0]; c_in =1'b0;
#20 ; end
initial #6000 $finish;
initial
$monitor($realtime,“ns %h %h %h %h", x, y, c_in, {c_out, sum});
endmodule

ECE Digital Logic Design


Modeling and Simulation Example --- Simulation Results
0ns 0 0 0 00 # 280ns 0 e 0 0e
# 20ns 0 1 0 01 # 300ns 0 f 0 0f
# 40ns 0 2 0 02 # 320ns 1 0 0 01
# 60ns 0 3 0 03 # 340ns 1 1 0 02
# 80ns 0 4 0 04 # 360ns 1 2 0 03
# 100ns 0 5 0 05 # 380ns 1 3 0 04
# 120ns 0 6 0 06 # 400ns 1 4 0 05
# 140ns 0 7 0 07 # 420ns 1 5 0 06
# 160ns 0 8 0 08 # 440ns 1 6 0 07
# 180ns 0 9 0 09 # 460ns 1 7 0 08
# 200ns 0 a 0 0a # 480ns 1 8 0 09
# 220ns 0 b 0 0b # 500ns 1 9 0 0a
# 240ns 0 c 0 0c # 520ns 1 a 0 0b
# 260ns 0 d 0 0d # 540ns 1 b 0 0c

ECE Digital Logic Design


Modeling and Simulation Example --- Simulation Results

ECE Digital Logic Design


VIT
UNIVERSIT
Y
- Verilog
()

Verilog HDL
Dataflow Modeling
Objectives
After completing this lecture, you will be able to:
❖ Describe what is the dataflow modeling
❖ Describe how to use continuous assignments
❖ Describe how to specify delays in continuous assignments
❖ Describe the data types allowed in Verilog HDL
❖ Describe the operation of the operators used in Verilog HDL
❖ Describe the operands may be used associated with a
specified operator
Slides are adopted from Digital System Designs and Practices Using Verilog HDL and FPGAs , John Wiley
Verilog
Why Dataflow ?
❖ Rationale of dataflow: any digital system can be constructed
by interconnecting registers and a combinational logic put
between them for performing the necessary functions.
▪ Dataflow provides a powerful way to implement a
design.
▪ Logic synthesis tools can be used to create a gate-level
circuit from a dataflow design description.
▪ RTL (register transfer level) is a combination of dataflow
and behavioral modeling.
Verilog
Continuous Assignments
❖ Continuous assignment: the most basic statement of dataflow
modeling.
▪ It is used to drive a value onto a net.
▪ It is always active.
▪ Any logic function can be realized with continuous
assignments.
▪ It can only update values of net data types such as wire,
triand, etc.

Verilog
Continuous Assignments
❖ A continuous assignment begins with the keyword assign.
assign net_lvalue = expression;
assign net1 = expr1,
net2 = expr2,
...,
netn = exprn;
▪ net_lvalue is a scalar or vector net, or their concatenation.
▪ RHS operands can be variables or nets or function calls.
▪ Registers or nets can be scalar or vectors.
▪ Delay values can be specified.
Verilog
Continuous Assignments
❖ An implicit continuous assignment
▪ is the shortcut of declaring a net first and then writing a
continuous assignment on the net.
▪ is always active.
▪ can only have one implicit declaration assignment per
net.
wire out; // regular continuous assignment
assign out = in1 & in2;

wire out = in1 & in2; // implicit continuous assignment


Verilog
Continuous Assignments
❖ An implicit net declaration
▪ is a feature of Verilog HDL.
▪ will be inferred for a signal name when it is used to the
left of a continuous assignment.
wire in1, in2;
assign out = in1 & in2;

Note that: out is not declared as a wire, but an implicit


wire declaration for out is done by the simulator.

Verilog
Delays
❖ Three ways of specifying delays
▪ Regular assignment delay
▪ Implicit continuous assignment delay
▪ Net declaration delay
❖ Regular assignment delays
▪ The delay value is specified after the keyword assign.
▪ The inertial delay model is used (default model).
wire in1, in2, out;
assign #10 out = in1 & in2;
Verilog
Delays
❖ Implicit continuous assignment delays
▪ An implicit continuous assignment is used to specify both
the delay and assignment on the net.
▪ The inertial delay model is used (default model).
// implicit continuous assignment delay
wire #10 out = in1 & in2;

// regular assignment delay


wire out;
assign #10 out = in1 & in2;
Verilog
Delays
❖ Net declaration delays
▪ A net can be declared associated with a delay value.
▪ Net declaration delays can also be used in gate-level
modeling.
// net delays
wire #10 out;
assign out = in1 & in2;

// regular assignment delay


wire out;
assign #10 out = in1 & in2;
Verilog
The Basis of Dataflow Modeling
❖ The essence of dataflow modeling is
expression = operators + operands
▪ Operands can be any one of allowed data types.
▪ Operators act on the operands to product desired results.
Operands:
- constants - time
- integers - bit-select
- real numbers - part-select
- nets - memories
- registers - function calls
Verilog
Operators

Verilog
Precedence of Operators

Verilog
Operands
❖ The operands in an expression can be any of:
▪ constants,
▪ parameters,
▪ nets,
▪ variables (reg, integer, time, real, realtime),
▪ bit-select,
▪ part-select,
▪ array element, and
▪ function calls
Verilog
Constants
❖ Three types of constant in Verilog HDL are
▪ integer,
▪ real, and
▪ string
❖ Integer constant
▪ simple decimal form
-123 // is decimal -123
12345 // is decimal 12345
▪ base format notation
16’habcd // a 16-bit hexadecimal number
2006 // unsized number--a 32-bit decimal number
4’sb1001 // a 4-bit signed number, it represents -7.

Verilog
Constants
❖ Real constant
▪ decimal notation
1.5 //
.3 // illegal ---
1294.872 //
▪ scientific notation
15E12
32E-6
26.176_45_e-12
❖ String constant
▪ A string is a sequence of characters enclosed by double quotes ("").
▪ It may not be split into multiple lines.
▪ One character is represented as an 8-bit ASCII code.

Verilog
Data Types
❖ Two classes of data types:
▪ nets: Nets mean any hardware connection points.
▪ variables: Variables represent any data storage elements.
❖ Variable data types
▪ reg
▪ integer
▪ time
▪ real
▪ realtime

Verilog
Variable Data Types
❖ A reg variable
▪ holds a value between assignments.
▪ may be used to model hardware registers.
▪ need not actually represent a hardware storage element.

reg a, b; // reg a, and b are 1-bit reg


reg [7:0] data_a; // an 8-bit reg, the msb is bit 7
reg [0:7] data_b; // an 8-bit reg, the msb is bit 0
reg signed [7:0] d; // d is an 8-bit signed reg

Verilog
The integer Variable
❖ The integer variable
▪ contains integer values.
▪ has at least 32 bits.
▪ is treated as a signed reg variable with the lsb being bit 0.
integer i,j; // declare two integer variables
integer data[7:0]; // array of integer

Verilog
The time Variable
❖ The time variable
▪ is used for storing and manipulating simulation time
quantities.
▪ is typically used in conjunction with the $time system
task.
▪ holds only unsigned value and is at least 64 bits, with the
lsb being bit 0.
time events; // hold one time value
time current_time; // hold one time value

Verilog
The real and realtime Variables
❖ The real and realtime variables
▪ cannot use range declaration and
▪ their initial values are defaulted to zero (0.0).
real events; // declare a real variable
realtime current_time; // hold current time as real

Verilog
Vectors
❖ A vector (multiple bit width) describes a bundle of signals as
a basic unit.
▪ [high:low] or [low:high]
▪ The leftmost bit is the MSB.
▪ Both nets and reg data types can be declared as vectors.
❖ The default is 1-bit vector or called scalar.

Verilog
Bit-Select and Part-Select
❖ Bit-Select and Part-Select
▪ integer and time can also be accessed by bit-select or
part-select.
▪ real and realtime are not allowed to be accessed by bit-
select or part-select.
▪ Constant part select: data_bus[3:0], bus[3]
▪ Variable part select:
[<starting_bit>+:width]: data_bus[8+:8]
[<starting_bit>-:width]: data_bus[15-:8]
Verilog
Array and Memory Elements
❖ Array and Memory Elements
▪ all net and variable data types are allowed to be declared
as multi-dimensional arrays.
▪ an array element can be a scalar or a vector if the element
is a net or reg data type.
wire a[3:0]; // a scalar wire array of 4 elements
reg d[7:0]; // a scalar reg array of 8 elements
wire [7:0] x[3:0]; // an 8-bit wire array of 4 elements
reg [31:0] y[15:0]; // a 32-bit reg array of 16 elements
integer states [3:0]; // an integer array of 4 elements
time current[5:0]; // a time array of 6 elements
Verilog
The Memory
❖ Memory
▪ Memory is used to model a read-only memory (ROM), a random
access memory (RAM), and a register file.
▪ Reference to a memory may be made to a whole word or a portion of
a word of memory.
reg [3:0] mema [7:0]; // 1-d array of 4-bit vector
reg [7:0] memb [3:0][3:0]; // 2-d array of 8-bit vector
wire sum [7:0][3:0]; // 2-d array of scalar wire

mema[4][3] // the 3rd bit of 4th element


mema[5][7:4] // the higher four bits of 5th element
memb[3][1][1:0] // the lower two bits of [3][1]th element
sum[5][0] // [5][0]th element

Verilog
Bitwise Operators
❖ Bitwise operators
▪ They perform a bit-by-bit operation on two operands.
▪ A z is treated as x in bit-wise operation.
▪ The shorter operand is zero-extended to match the length
of the longer operand.

Verilog
An Example --- A 4-to-1 MUX
module mux41_dataflow(i0, i1, i2, i3, s1, s0, out);
// Port declarations
input i0, i1, i2, i3;
input s1, s0;
output out;
// Using basic and, or , not logic operators.
assign out = (~s1 & ~s0 & i0) |
(~s1 & s0 & i1) |
(s1 & ~s0 & i2) |
(s1 & s0 & i3) ;
endmodule

Verilog
Arithmetic Operators
❖ Arithmetic operators
▪ If any operand bit has a value x, then the result is x.
▪ The operators + and – can also used as unary operators to represent signed
numbers.
▪ Modulus operators produce the remainder from the division of two numbers.
▪ In Verilog HDL, 2’s complement is used to represent negative numbers.

Verilog
Concatenation and Replication Operators
❖ Concatenation operators
▪ The operands must be sized.
▪ Operands can be scalar nets or registers, vector nets or
registers, bit-select, part-select, or sized constants.
▪ Example: y = {a, b[0], c[1]};
❖ Replication operators
▪ They specify how many times to replicate the number
inside the braces.
▪ Example: y = {a, 4{b[0]}, c[1]};
Verilog
An Example --- A 4-bit Full Adder

module four_bit_adder(x, y, c_in, sum, c_out);


// I/O port declarations
input [3:0] x, y; // declare as a 4-bit array
input c_in;
output [3:0] sum; // declare as a 4-bit array
output c_out;

// Specify the function of a 4-bit adder.


assign {c_out, sum} = x + y + c_in;
endmodule

Verilog
Another Example --- A 4-bit two’s complement adder
module twos_adder(x, y, c_in, sum, c_out);
// I/O port declarations
input [3:0] x, y; // declare as a 4-bit array
input c_in;
output [3:0] sum; // declare as a 4-bit array
output c_out;
wire [3:0] t; // outputs of xor gates

// Specify the function of a two's complement adder


assign t = y ^ {4{c_in}};
assign {c_out, sum} = x + t + c_in;
endmodule

Verilog
Reduction Operators
❖ Reduction operators
▪ perform only on one vector operand.
▪ carry out a bit-wise operation on a single vector operand and
yield a 1-bit result.
▪ work bit by bit from right to left.

Verilog
Reduction Operators --- A 9-Bit Parity Generator
module parity_gen_9b_reduction(x, ep,op);
// I/O port declarations
input [8:0] x;
output ep, op;
// dataflow modeling using reduction operator
assign ep = ^x; // even parity generator
assign op = ~ep; // odd parity generator
endmodule

Verilog
Reduction Operators --- An All-Bit-Zero/One detector
module all_bit_01_detector_reduction(x, zero,one);
// I/O port declarations
input [7:0] x;
output zero, one;
// dataflow modeling
assign zero = ~(|x); // all-bit zero detector
assign one = &x; // all-bit one detector
endmodule

Verilog
Logical Operators
❖ Logical operators
▪ They always evaluate to a 1-bit value, 0, 1, or x.
▪ If any operand bit is x or z, it is equivalent to x and
treated as a false condition by simulators.

Verilog
Relational Operators
❖ Relational operators
▪ They return logical value 1 if the expression is true and 0
if the expression is false.
▪ The expression takes a value x if there are any unknown
(x) or z bits in the operands.

Verilog
Equality Operators
❖ Equality operators
▪ compare the two operands bit by bit, with zero filling if the operands
are of unequal length.
▪ return logical value 1 if the expression is true and 0 if the expression
is false.
❖ The operators (==, !=) yield an x if either operand has x or z in its bits.
❖ The operators (===, !==) yield a 1 if the two operands match exactly and
0 if the two
operands not match
exactly.

Verilog
Relational Operators --- A 4-b Magnitude Comparator

module four_bit_comparator(Iagtb, Iaeqb, Ialtb, a, b, Oagtb, Oaeqb, Oaltb);


// I/O port declarations
input [3:0] a, b;
input Iagtb, Iaeqb, Ialtb;
output Oagtb, Oaeqb, Oaltb;
// dataflow modeling using relation operators
assign Oaeqb = (a == b) && (Iaeqb == 1); // equality
assign Oagtb = (a > b) || ((a == b)&& (Iagtb == 1)); // greater than
assign Oaltb = (a < b) || ((a == b)&& (Ialtb == 1)); // less than
endmodule

Verilog
Shift Operators
❖ Logical shift operators
▪ >> operator: logical right shift
▪ << operator: logical left shift
▪ The vacant bit positions are filled with zeros.
❖ Arithmetic shift operators
▪ >>> operator: arithmetic right shift
• The vacant bit positions are filled with the MSBs (sign bits).
▪ <<< operator: arithmetic left shift
• The vacant bit positions are filled with zeros.

Verilog
Shift Operators
// example to illustrate logic and arithmetic shifts
module arithmetic_shift(x,y,z);
input signed [3:0] x;
output [3:0] y;
output signed [3:0] z;
assign y = x >> 1; // logical right shift
assign z = x >>> 1; // arithmetic right shift
endmodule

Note that: net variables x and z must be declared with the keyword signed.
Replaced net variable with unsigned net (i.e., remove the keyword signed)
and see what happens.

Verilog
The Conditional Operator
❖ Conditional Operator
Usage: condition_expr ? true_expr: false_expr;
▪ The condition_expr is evaluated first.
▪ If the result is true then the true_expr is executed; otherwise
the false_expr is evaluated.
if (condition_expr) true_expr;
else false_expr;
▪ a 2-to-1 multiplexer
assign out = selection ? in_1: in_0;
Verilog
The Conditional Operator --- A 4-to-1 MUX
module mux4_to_1_cond (i0, i1, i2, i3, s1, s0, out);
// Port declarations from the I/O diagram
input i0, i1, i2, i3;
input s1, s0;
output out;
// Using conditional operator (?:)
assign out = s1 ? ( s0 ? i3 : i2) : (s0 ? i1 : i0) ;
endmodule

Verilog
Loop Constructs
❖ Loop constructs control the execution of a statement zero, one, or more
times.
❖ Loop constructs
▪ can appear only inside an initial or always block.
▪ may contain delay expressions.
❖ Four types
▪ while loop executes a statement until an expression becomes false.
▪ for loop repeatedly executes a statement.
▪ repeat loop executes a statement a fixed number of times.
▪ forever loop continuously executes a statement.

ECE DLD Digital Logic Design


The while Loop Structure
❖ A while loop
▪ executes until the condition is false.
▪ shall not be executed at all if the condition_expr starts out
false.
while (condition_expr) statement;

while (count < 12) count <= count + 1;


while (count <= 100 && flag) begin
// put statements wanted to be carried out here.
end

ECE DLD Digital Logic Design


The while Loop Structure
// an example illustrating how to count the zeros in a byte.
module zero_count_while (data, out);
input [7:0] data;
output reg [3:0] out; //output declared as register
integer i;
always @(data) begin
out = 0; i = 0;
while (i <= 7) begin // simple condition
if (data[i] == 0) out = out + 1; // may be replaced with out = out + ~data[i].
i = i + 1; end
end
endmodule

Note that: If we replace the blocking assignments by nonblocking assignments, the


resulting program will not work properly. Why ? Try it! Explain it.

ECE DLD Digital Logic Design


The while Loop Structure
// an example illustrating how to count the trailing zeros in a byte.
module trailing_zero_while (data, out);
input [7:0] data;
output reg [3:0] out; // output declared as register
integer i; // loop counter
always @(data) begin
out = 0; i = 0;
while (data[i] == 0 && i <= 7) begin // complex condition
out = out + 1;
i = i + 1;
end
end
endmodule

Note that: Please distinguish the difference between this example and the previous one.

ECE DLD Digital Logic Design


The for Loop Structure
❖ A for loop is used to perform a counting loop. It
▪ behaves like the for statement in C programming language.
for (init_expr; condition_expr; update_expr) statement;

▪ is equivalent to
init_expr;
while (condition_expr) begin
statement;
update_expr;
end
ECE DLD Digital Logic Design
The for Loop Structure
// an example illustrating how to count the zeros in a byte.
module zero_count_for (data, out);
input [7:0] data;
output reg [3:0] out; // output declared as register
integer i;
always @(data) begin
out = 0;
for (i = 0; i <= 7; i = i + 1) // simple condition
if (data[i] == 0)
out = out + 1; // may be replaced with out = out + ~data[i].
end
endmodule

Note that: If we replace the blocking assignments by nonblocking assignments, the


resulting program will not work properly. Why ? Try it! Explain it.
ECE DLD Digital Logic Design
The for Loop Structure

// an example illustrating how to count the trailing zeros in a byte.


module trailing_zero_for (data, out);
input [7:0] data;
output reg [3:0] out; // output declared as register
integer i; // loop counter
always @(data) begin
out = 0;
for (i = 0; data[i] == 0 && i <= 7; i = i + 1) // complex condition
out = out + 1;
end
endmodule

Note that: Please distinguish the difference between this example and the
previous one.
ECE DLD Digital Logic Design
The repeat Loop Structure
❖ A repeat loop performs a loop a fixed number of times.
repeat (counter_expr) statement;

▪ counter_expr can be a constant, a variable or a signal


value.
▪ counter_expr is evaluated only once before starting the
execution of statement (loop).

ECE DLD Digital Logic Design


The repeat Loop Structure
▪ Examples:
i = 0;
repeat (32) begin
state[i] = 0; // initialize to zeros
i = i + 1; // next item
end
repeat (cycles) begin // cycles must be evaluated to a number
@(posedge clock) buffer[i] <= data; // before entering the loop.
i <= i + 1; // next item
end

ECE DLD Digital Logic Design


The forever Loop Structure
❖ A forever loop continuously performs a loop until the $finish
task is encountered. It
▪ is equivalent to a while loop with an always true
expression such as while (1).
forever statement;
▪ can be exited by the use of disable statement.

ECE DLD Digital Logic Design


The forever Loop Structure
▪ The forever statement example
initial begin
clock <= 0;
forever begin
#10 clock <= 1;
#5 clock <= 0;
end
end
▪ The forever statement is usually used with timing control statements.
reg clock, x, y;
initial
forever @(posedge clock) x <= y;

ECE DLD Digital Logic Design


Objectives
After completing this lecture, you will be able to:
❖ Understand the features of timing controls
❖ Understand the features of selection constructs
❖ Understand the features of loop constructs

ECE
Coding Style for Blocking / Nonblocking Assignments
❖ Coding style: In the always block
▪ Use nonblocking operators (<=) when it is a piece of
sequential logic;
• Otherwise, the result of RTL behavioral may be inconsistent with
that of gate-level.
▪ Use blocking operators (=) when it is a piece of
combinational logic.

ECE
Timing Controls
❖ Timing controls specify the simulation time at which procedural statements will
be executed.
❖ In Verilog HDL, if there are no timing control statements, the simulation time
will not advance.
❖ Timing Controls
▪ Delay timing control
• Regular delay control
• Intra assignment delay control
▪ Event timing control
• Edge-triggered event control
o Named event control
o Event or control
• Level-sensitive event control

ECE
Regular Delay Control
❖ Regular delay control
▪ A non-zero delay is specified to the left of a procedural
assignment.
▪ It defers the execution of the entire statement.
reg x, y;
integer count;
// The “<=” operators in the following statements can be replaced with “=”
// without affecting the results.
#25 y <= ~x; // execute at time 25
#15 count <= count + 1; // execute at time 40

ECE
Intra-Assignment Delay Control
❖ Intra-assignment delay control
▪ A non-zero delay is specified to the right of the
assignment operator.
▪ It defers the assignment to the left-hand-side variable.
y = #25 ~x; // evaluate at time 0 but assign to y at time 25
count = #15 count + 1; // evaluate at time 0 but assign to count at time 40

y <= #25 ~x; // evaluate at time 0 but assign to y at time 25


count <= #15 count + 1; // evaluate at time 0 but assign to count at time 15

ECE
Event Timing Control
❖ Event Timing Control
▪ An event is the change in the value on a variable or a net.
▪ The execution of a procedural statement can be
synchronized with an event.
❖ Two types of event control
▪ Edge-triggered event control
• Named event control
• Event or control
▪ Level-sensitive event control
ECE
Edge-Triggered Event Control
❖ Edge-triggered event control
▪ The symbol @ is used to specify such event control.
• @(posedge clock): at the positive edge
• @(negedge clock): at the negative edge

always @(posedge clock) begin


reg1 <= #25 in_1; // intra-assignment delay control
reg2 <= @(negedge clock) in_2 ^ in_3; // edge-triggered event control
reg3 <= in_1; // no delay control
end

ECE
Named Event Control
❖ A named event
▪ is declared with the keyword event.
▪ does not hold any data.
▪ is triggered by the symbol ->.
▪ is recognized by the symbol @.
event received_data; // declare an event received_data
// trigger event received_data
always @(posedge clock) if (last_byte) -> received_data;
always @(received_data) begin ….. end // execute event-dependent operations

ECE
Event or Control
❖ Event or control
▪ uses the keyword or to specify multiple triggers.
▪ can be replaced by the “,”.
▪ can use @* or @(*) to mean a change on any signal.

always @(posedge clock or negative reset_n) // event or control


begin
if (!reset_n) q <= 1`b0; // asynchronous reset.
else q <= d;
end

ECE
Level-Sensitive Event Control
❖ Level-sensitive event control
▪ uses the keyword wait.

always
wait (count_enable) count = count –1 ;

always
wait (count_enable) #10 count = count –1 ;

ECE
Selection Constructs
❖ Selection structures
▪ make a selection according to the given condition.
❖ Two types
▪ if…else statement
▪ case statement
❖ if…else statement syntax
▪ if statement only
▪ if and one else statement
▪ nested if-else-if statement
❖ The else part is always associated to the closest previous if that lacks an else.

ECE
Selection Constructs

if (<expression>) true_statement ;

if (<expression>) true_statement; else false_statement;

if (<expression1>) true_statement1;
else if (<expression2>) true_statement2;
else false_statement;

ECE
Selection Constructs
module mux4_to_1_ifelse (i0, i1, i2, i3, s1, s0, out);
// port declarations
input i0, i1, i2, i3;
input s1, s0;
output reg out;
// using conditional operator if else statement
always @(*)
// triggered for all signals used in the if else statement
if (s1) begin
if (s0) out = i3; else out = i2; end
else begin
if (s0) out = i1; else out = i0; end
endmodule

ECE
A Simple 4-bit Counter
module counter (clock, clear, qout);
input clock, clear;
output reg [3:0] qout;
// the body of the 4-bit counter.
always @(negedge clock or posedge clear)
begin
if (clear)
qout <= 4'd0;
else
qout <= (qout + 1) ; // qout = (qout + 1) % 16;
end
endmodule

ECE
Selection Constructs
❖ case statement: a multiway selection.
▪ compares the expression to the alternatives in the order they are written.
▪ compares 0, 1, x, and z values in the expression and the alternative bit for
bit.
▪ executes the default statement if no matches are made.
▪ fills zeros to match the unequal bit widths between the expression and the
alternative.
▪ is acted like a multiplexer.
❖ The default statement is optional and at most one default statement can be placed
inside one case statement.
❖ A block statement must be grouped by begin and end.

ECE
A 4-to-1 MUX Example
// a 4-to-1 multiplexer using case statement
module mux_4x1_case (I0, I1, I2, I3, S, Y);
input I0, I1, I2, I3;
input [1:0] S; // declare S as a two-bit selection signal.
output reg Y;
always @(I0 or I1 or I2 or I3 or S) // It can use always @(*).
case (S)
2'b00: Y = I0;
2'b01: Y = I1;
2'b10: Y = I2;
2'b11: Y = I3;
endcase
endmodule

ECE
A 4-to-1 MUX Example
// a 4-to-1 multiplexer using case and default statements.
module mux4_to_1_case_default (i0, i1, i2, i3, s1, s0, out);
input i0, i1, i2, i3, s1, s0;
output reg out; //output declared as register
always @(s1 or s0 or i0 or i1 or i2 or i3)
case ({s1, s0}) // concatenate s1 and s0 as a two-bit selection signals
2'b00: out = i0;
2'b01: out = i1;
2'b10: out = i2;
2'b11: out = i3;
default: out = 1'bx; // using default to include all other possible cases.
endcase
endmodule

ECE
Selection Constructs
❖ casex and casez statements
▪ are used to perform a multiway selection like that of case
statement.
▪ compare only non-x or z positions in the case expression
and the case alternatives.
❖ casez treats all z values as don’t cares.
❖ casex treats all x and z values as don’t cares.

ECE
Selection Constructs
// an example illustrating how to count the trailing zeros in a nibble.
module trailing_zero_4b (data, out);
input [3:0] data;
output reg [2:0] out; //output declared as register
always @(data)
casex (data) // treat both x and z as don’t care conditions.
4'bxxx1: out = 0;
4'bxx10: out = 1;
4'bx100: out = 2;
4'b1000: out = 3;
4'b0000: out = 4;
default: out = 3'b111; //using default to include all other possible cases.
endcase
endmodule
ECE

You might also like