# INTRODUCTION TO VERILOG
### Computer-Aided Design (CAD)
+ Hardware Description Language
+ Behavioral description
+ Specifies only the general working of the design at a flow-chart or algorithmic level w/o associating to any specific physical parts, components, or implementations.
+ Structural description
+ Specifies components or specific implementations of components associated w/ the design.
---
### Hardware Description Languages
+ HDLs
+ model: behavioral, dataflow, structural
+ types
+ VHDL
+ more elegant for simulation of very large systems at a higher level of abstration
+ Verilog
---
### Verilog Description of Combinational Circuits
+ model combinational circuit
+ concurrent statements: continuous assignments
+ statement are always ready to execute
+ Evaluated any time and every time **a signal on the right side of the statement changes**.
+ Execute repeatedly
+ example
+ 
+ ```verilog=
assign #5 C = A && B;
assign #5 E = C || D;
```
+ Some Verilog syntax (rules):
+ case sensitive
+ Signal names and other Verilog identifiers may contain letters, numbers, the underscore character (_), and the dollar sign ($).
+ Numbers or net values are represented as:
+ (number of bit's)(base)(value) e.g. 3'b110
+ Data Types:
+ reg(register)
+ can store information just like registers.
+ initial value of a reg is x (unknown)
+ 在給他新值前都會保留之前的
+ Can be used in modeling combinational and sequential logic.
+ wire
+ acts as real wires in circuit designs
+ cannot hold a value
+ initial value of a wire is z (high impedance.)
+ Can be used in modeling combinational logic only and must be driven by something.
+ input and inout ports can be only net (or wire) data type.
---
### Verilog Modules
+ Module Declaration
+ 
+ Verilog Program Structure
+ A module may contain other module instances that describe the operation of the module.
+ Positional association: listing the ports in order
+ Full Adder
+ 
+ ```verilog=
module FullAdder(X, Y, Cin, Cout, Sum);
output Cout, Sum;
input X, Y, Cin;
assign #10 Sum = X ^ Y ^ Cin;
assign #10 Cout = (X && Y) || (X && Cin) || (X && Cin);
endmodule
```
+ 4-bit Binary Adder
+ 
+ ```verilog=
module Adder4 (S, Co, A, B, Ci);
output [3:0] S; // 4-bit vector
output Co;
input [3:0] A, B;
input Ci;
wire [3:1] C; // an internal signal
// instantiate four copies of the FullAdder
// X Y Cin Cout Sum
FullAdder FA0 (A[0], B[0], Ci, C[1], S[0]);
FullAdder FA1 (A[1], B[1], C[1], C[2], S[1]);
FullAdder FA2 (A[2], B[2], C[2], C[3], S[2]);
FullAdder FA3 (A[3], B[3], C[3], Co, S[3]);
endmodule
```
+ Simulator
+ Use of “inout” Mode
+ The output mode can also be used as an input in a statement inside the same module.(The code will compile, simulate, or synthesize in most tools even though D is declared only as an output.)
+ inout has to be used for a variable if it has to be used as input and output by other modules.
+ 
+ **input and inout ports can be only net (or wire) wire) data type**.
---
### Verilog Assignments
+ Verilog Assignments
+ Continuous assignments:
+ used to assign values for combinational logic circuits
+ constant reaction to input changes.
+ Procedural assignments:
+ used to model registers and finite state machines
+ selective activity conditional on clock, edge-triggered devices, sequence of operations.
+ Continuous Assignments
+ Explicit continuous assignments:
+ uses the assign keyword after the net is separately declared.
+ Implicit continuous assignments:
+ assign the value in declaration without using the assign keyword.
+ e.g wire = D = E && F;
---
### Procedural Assignments
+ Procedural assignments
+ initial blocks:
+ execute only once at time zero
+ always blocks:
+ loop to execute over and over again when a specific event occurs, starts at time zero
+ ```verilog=
always @(sensitivity-list)
begin
sequential-statements
end
```
+ statements between begin and end are executed sequentially rather than concurrently.
+ **Sensitivity list**:
+ **"or"**, **","** used to specify more than one element in the sensitivity list.
+ **“*”** of use cause the always block to execute whenever any signal changes.
+ variables on the left-hand side element of an = or <= in an always block should be defined as reg data type.
+ Assignment operator **“=”**:
+ outside an always block, indicates concurrent execution.
+ in an always block, becomes sequential statements executed in the order it is written.
+ **Always statements can be used for modeling combinational logic and sequential logic**.
+ for comb Use the always @* statement.
+ 以防任一input signal omitted from the sensitivity list, cause confusion
+ example (因為D有在ALWAYS BLOCK裡所以還要在一DECLARE他是reg不然預設是wire)
+ 
+ Sequential Statements
+ Blocking assignment:(有順序)
+ must complete the evaluation of the right-hand side of a statement before the next statements in a sequential block are executed.
+ Uses the “=” operator
+ combinational logic.
+ Non-blocking assignment:(同時右邊一排傳入左邊)
+ allows several assignment evaluations to be assessed at the same time.
+ Uses the “<=” operator
+ sequential logic
+ Do not mix blocking and non-blocking assignments in the same always block.
+ Default Verilog HDL data value set: a 4-value system
+ 0: represents a logic zero, or a false condition
+ 1: represents a logic one, or a true condition
+ x: represents an unknown logic value
+ z: represents a high-impedance state (a tristated value)
+ **Guidelines of Blocking & Nonblocking Assignments**
:::info
+ Use continuous assignments assign to model simple combinational logic.
+ Use always @ (*) and blocking assignments to model more complicated combinational logic where the always statement is helpful.
+ Use always @ (posedge clk) and nonblocking assignments to model synchronous sequential
+ Do not make assignments to the same signal in more than one always statement or continuous assignment statement.
:::
---
### Modeling Flip-Flops Using Always Block
+ If Statement
+ sequential statements that can be used within an always or initial block
+ Can not be used as concurrent statements outside of an always block.
+ J-K Flip-Flop (Q+ = JQ' + K'Q)
+ 
+ ```verilog=
module JKFF (SN, RN, J, K, CLK, Q, QN);
input SN, RN, J, K, CLK;
output Q, QN;
reg Qint;
always @(negedge CLK or RN or SN)
begin
if (~RN)
#8 Qint <= 0;
else if (~SN)
#8 Qint <= 1;
else
Qint <= #10 ((J && ~Qint) || (~K && Qint));
end
assign Q = Qint;
assign QN = ~Qint;
endmodule
```
---
### Always Blocks Using Event Control Statements
+ Always Blocks Using Event Control Statements
+ If a sensitivity list is omitted at the always keyword, **delays or time-controlled events must be specified inside the block**.
+ 
+ Time-controlled events: wait or event control statements
+ An always block cannot have both sensitivity list and wait statements.
+ Wait Statement
+ The wait statement is used as a level-sensitive event control.
+ 
---
+ **Differentiate Compile error, Similate wrong, Synthesis not desired**
+ important notes
+ begin與end可視為C語言中的大括號,用來界定block的程式範圍。與C語言相同之處在於,若只有一行程式內容時,begin與end一樣可以省略不寫。
+ case1(will compile but will not simulate correctly.)
+ 
+ 只有sum算在if statement
+ carry在if的外面 所以不管怎麼樣都會執行
+ 可能有 undesire latch
+ correction:
+ 加 begin end 包住 sum 跟 carry
+ Latches can be avoided by adding **else clause** or by **initializing sum and carry to 0 at the beginning of the always statement**.
+ case2(will not even compile.)
+ 
+ compiler到else 的時候不會知道她前面有if
+ correction:
+ 加 begin end 包住 sum 跟 carry
+ After the correction, both simultiton and synthesis will work correctly.
---
### Delays in Verilog
+ Delays in Verilog
+ Initial Delay 慣性延遲模型
+ only propagate signals to an output after the input signals have remained unchanged (been stable) for a time period equal to or greater than the propagation delay of the model. **If the time between two input changes is shorter than a procedural assignment delay, a continuous assignment delay, or gate delay, a previously scheduled but unrealized output event is replaced with a newly scheduled output event**.
+ The inertial delay for combinational blocks can be expressed in the following three ways:
+ 
+ Transport delay
+ propagate all signals to an output after any input signals
+ The delay value is specified on the right-hand side of the statement, called intra-assignment delay.
+ Can not be done w/ continuous assign statements
+ example
+ 
+ Net Delay
+ the time it takes from any driver on the net to change value to the time when the net value is updated and propagated further.
+ example1
+ 
+ c1由於input a沒有穩定30ns的值因此到第40ns才正常作用 經過30ns inertial才show出值
+ c2剛好input 有一個20ns穩定的值 在10ns正常作用 經過20ns inertial + 10ns net delay show 出值
+ example2
+ 
+ Notice
+ delays are relevant only for simulation.
+ pulse rejection associated w/ inertial delay can inhibit many output changes.
+ In simulation w/ basic gates and simple ckts, one should make sure that test sequences that you apply are wider than the inertial delays of the modeled devices.
---
### Compilation, Simulation, and Synthesis of Verilog Code
+ Scheduling of Nonblocking ( <= ) Assignment
+ If two non-blocking updates are made to the same variable in the same time step, the **2nd one dominates** by the end of the time step.
+ 
+ Simulation w/ Multiple Processes(Initial or Always Blocks)
+ model contains more than one process, all processes **execute concurrently** w/ other processes.
+ If there are concurrent statements outside always statements, they also execute concurrently.
+ Verilog Simulator
+ Verilog simulator: event-driven simulation
+ **A change in signal is called an event**.
+ Simulation of Inertial Delays
+ Each input change causes the simulator to schedule a change, which is scheduled to occur after the specified delay; **however, if another input change happens before the specified delay has elapsed, the first change is dequeued from the simulation driver queue**.
+ Only pulses wider than the specified inertial delay appear at the output.
+ Synthesis
+ translates the Verilog code to a circuit description that specifies the needed components and the connections b/t the components. (netlist)
+ The synthesizer output can then be used to implement the digital system using specific hardware, such as a CPLD or an FPGA or as an ASIC.
---
### Verilog Data Types and Operators
+ Net Data Types
+ types
+ wire
+ tri (tristate)
+ wand(wired and)
+ wor (wired or)
+ Represent physical connections b/t structural entities
+ value is determined by the values of its drivers, such as a continuous assignment or a gate.
+ Variable Data Types
+ types
+ reg
+ time
+ interger
+ real
+ real number constants and real variable data types for floating-point number
+ real-time
+ An assignment statement in a procedure acts as a trigger that changes the value in the data storage element.
+ Definitions of Data Types
+ vectors: wire or reg data types can be declared as vectors (multiple bits) ([range1 : range2])
+ Predefined Verilog Operators
+ 
+ 
+ 
+ 
+ example
+ 
+ Operator Precedence
+ are applied from left to right in an expression.
+ ff
+ Concatenate operator: { }
+ Concatenate operator can be used on the left side of an assignment.
+ E.g.: {Carry, SUM} = A + B;
+ Equality and inequality operators:
+ Logical equality and inequality: == and !=
+ due to unknown or high-impedance bits in the operands, the relation is ambiguous, then the result shall be a 1-bit unknown value (x).
+ Case equality and inequality: === and !==
+ Bits that are x or z shall be included in the comparison and shall match for the result to be considered equal. The result shall always be a known value, either 1 or 0.
+ Shift operators:
+ If the register is **unsigned**, arithmetic and logic shifts do the same operation.(if signed you have to declare)
+ arithmetic shift
+ shift-right: the empty pos of most significant bit is filled with a copy od original MSB
+ shift-left: the empty pos of the last siginificant is filled with a zero
+ example
+ 
---
### Simple Synthesis Examples
+ Simulation and Synthesis Results in Different Outputs
+ **Even if Verilog code gives the correct result when simulated, it may not result in hardware that works correctly when synthesized**.
+ cases:
+ 
+ 
+ 
+ 
+ Notice
:::info
+ For every assignment statement in an always statement, a signal on the left side of the assignment will cause creation of a register or flip-flop.
+ If you do not want to create unnecessary flip- flops, do not put the signal assignments in a clocked always statement.
+ If clock is omitted in the sensitivity list of an always statement, the synthesizer may produce latches instead of flip-flops.
:::
---
### Verilog Models for Multiplexers
+ Multiplexer, MUX: a combinational circuit
+ conditional operator with assign statement.
+ case statement or if-else statement within an always statement.
+ 2-to-1 MUX: F = A'I0 + AI1
+ ```verilog=
//Modeled as a single concurrent signal assignment statement:
assign F = (~A && I0) || (A && I1);
//Modeled by a conditional signal assignment statement:
assign F = (A) ? I1 : I0;
```
+ 4-to-1 MUX: F = A'B'I0 + A'BI1 + AB'I2 + ABI3
+ ```verilog=
//Modeled using a case statement within an always block:
always @ (Sel or I0 or I1 or I2 or I3)
case (Sel)
2’b00 : F = I0;
2’b01 : F = I1;
2’b10 : F = I2;
2’b11 : F = I3;
endcase
//Modeled using an if-else statement within an always block:
always @ (Sel or I0 or I1 or I2 or I3)
begin
if (Sel == 2’b00) F = I0;
else if (Sel == 2’b01) F = I1;
else if (Sel == 2’b10) F = I2;
else if (Sel == 2’b11) F = I3;
end
```
+ Using Conditional Operator
+ assign signal_name = condition ? expression_T : expression_F;
+ If condition is true, signal_name is set equal to the value of expression_T; otherwise, signal_name is set equal to the value of expression_F.
+ Using of Case Statement in an Always Block
+ All possible values of the expression must be included in the choices.
+ If all values are not explicitly given, a default clause is required in the case statement.
+ Writing Synthesizable Verilog for Combinational Hardware
:::info
+ If possible use concurrent assignments (e.g. assign) to design combinational logic.
+ When procedural assignments (always blocks) are used for combinational logic, use blocking assignments (“=”).
+ use always@* to avoid accidental omission of inputs from sensitivity lists.
:::
---
### Modeling Registers and Counters Using Verilog Always Statements
+ a Cyclic Shift Register
+ 
+ 
+ case to show difference assignment of blocking and non-blocking
+ 
+ 
+ Left Shift Register w/ Sync Clear & Load
+ 
+ 
+ Note: Verilog Synthesizer
:::info
+ A Verilog synthesizer cannot synthesize delays.
+ Clauses of the form “# time” will be ignored by most synthesizers.
+ Initial blocks and initial values for signals specified in port and signal declarations are usually ignored by synthesis tools.
+ A reset signal should be provided if the hardware must be set to a specific initial state.
:::
+ **Unwanted latches**
+ Verilog signals retain their current values until they are changed.
+ This can result in the creation of unwanted latches when the Verilog code is synthesized.
+ latch creates a variety of timing problems and unexpected behavior.
+ example
+ 
+ **Avoiding unwanted latches**
+ Assign a value to combinational signals in every possible execution path in an always block intended to create combinational hardware.
+ One should include an else clause in every if statement or explicitly include all possible cases of the inputs.
+ For if then else statements and case statements, have all cases specified, or initialize at the beginning of the always statement.
+ Initialize at the beginning of the always statement.
+ example of Avoiding Unwanted Latches
+ 
---
### Behavioral and Structural Verilog

+ Multiple levels of abstraction of Verilog:
+ Behavioral model:
+ Describes the ckt or system at a high level of abstraction w/o implying any particular structure
+ Specifies only the overall behavior.
+ Data flow (Register Transfer Language, RTL) model:
+ Data path and control signals are specified.
+ System is described in terms of the data transfer b/t registers.
+ Structural model: at a low level of abstraction
+ Components used and the structure of the interconnection b/t the components are clearly specified.
+ May be detailed enough to specify use of particular gates and flip-flops.
+ Modeling a Sequential Machine
+ 
+ Three approaches for modeling a sequential machine:
+ Behavioral model:
+ (a)use two always blocks to represent the two parts of the circuit:
+ One always block models the **combinational part of the ckt and generates the next state information and outputs**.
+ The other always block models the state register and **updates the state at the appropriate edge of the clock**.
+ (b)use a single always block instead of two always blocks.
+ The state register is updated directly to the proper next state value on the appropriate edge of the clock in the always block.
+ Use conditional assignment statements to compute the outputs out of the always block.
+ Data flow model:
+ based on the **next state and output equations** derived for the circuit.
+ Structural model: describing the gates and flip- flops in the ckt
+ When primitive components are required, each of thesecomponents can be defined in a separate Verilog module, or by using the built-in primitives defined in Verilog.
+ The component modules must be included in the same file as the main Verilog description or they must be inserted as separate files in a Verilog project.
+ example
+ a Mealy Seq Ckt for BCD to Excess-3 Code Converter
+ 
+ <Approach 1a> Behavioral Model
+ 
+ <Approach 1b> Behavioral level
+ 
+ <Approach 2> Data Flow Model
+ 
+ <Approach 3> Structural Model
+ 
+ 
+ Synthesis
+ Synthesis with integers:
+ Integers are generally treated as 32-bit quantities.
+ **While writing synthesizable code, use the appropriate number of bits for your variables** (**bit數如果確定是多少最好直接宣告好**)
+ One should use integers only where they are not explicitly synthesized, e.g., looping variables.
+ If integers are used for state variables in the state machine, some synthesis tools may be able to figure out the number of bits actually required by the state variable, but some may generate 32-bit registers..
+ pros and cons of different modeling
+ Structural model:
+ has more control over the generated circuitry
+ takes a lot more effort to produce a structural model.
+ Behavioral model:
+ can achieve quick time to market.
---
### Constants
+ Three different ways to define constant values:
+ == \`define==: compiler directive, used to define a number or an expression for a **meaningful string**
+ E.g. `define wordsize 16 reg [1:`wordsize] data;
+ parameter: used to define constants that should not be changed.
+ E.g.s: parameter msb = 15; // defines msb as a constant value 15
+ E.g.s: parameter [31:0] decim = 1'b1; //value converted to 32 bits
+ localparam: similar to parameter; used to define constants that should not be changed.
+ Parameters:
+ used to define constant values in a module
+ used to customize the module instances
+ uses of parameters: specify delays and width of variables
+ Do not belong to either the variable or the net group.
+ Module parameters can be modified at compilation time, but is illegal to modify their values at run time.
---
### Arrays
+ Arrays in Verilog can be used while modeling the repetition.
+ Verilog arrays can be used to create **memory arrays** and specify the values to be stored in these arrays.
+ declare the array upper and lower bound.
+ Array can be created of various data types.
+ Declaring Array Bounds
+ Two positions to declare the array bounds:
+ declared b/t the variable type (reg or net) and the variable name
+ e.g. reg [7:0] eight_bit_register;
+ e.g. eight_bit_register = 8’b00000001; // initialize
+ **declared after the name of the array**
+ e.g. reg rega [1:n]; // an array of n 1-bit registers
+ e.g. reg [1:n] regb; // an n-bit register
+ Matrices
+ matrixA [0:3][0:2] = {{ 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9},{10, 11, 12}};
+ Look-Up Table Method
+ The array construct together with parameter can be used to create look-up tables which can be used to create combinational circuits using the ROM or Look-Up Table (LUT) method.
+ 
---
### Loops in Verilog
+ Loops:
+ A loop statement is a sequential statement.
+ Kinds of loop statements: for, while, repeat
+ Forever Loop (Infinite Loop)
+ Can be useful in hardware modeling where a device works continuously until the power is off
+ ```verilog=
begin
clk = 1’b0;
forever #10 clk = ~clk;
end
```
+ For Loops
+ ```verilog=
reg [7:0] eight_bit_register_array [15:0];
for (i=0; i<16; i=i+1)
begin
eight_bit_register_array[i] = 8’b00000000;
end
```
+ While Loops
+ A condition is tested before each iteration.
+ It is used mainly for simulation.
+ Repeat Loops
+ repeats the sequential statement(s) for specified times.
+ ```verilog=
repeat ( 8 )
begin
x = x + 1;
y = y + 2;
end
```
---
### Testing a Verilog Model
+ Test bench:
+ a piece of Verilog code that can provide input combinations to test a Verilog model for the system under test.
+ System Tasks for Observing Outputs
+ $display: outputs/prints values exactly where it is executed and adds a new line character to the end of its output.
+ $write: works the same as $display, but does not add a new line character to the end of its output.
+ $strobe: displays at the very end of the current simulation time unit.
+ $monitor: displays every time one of its parameters changes.
---
+ Testing a 4-bit Binary Adder
+ 
+ 
+ 
+ 
### A Few Things to Remember
+ Purposes of Writing Verilog
+ To design hardware (i.e., to model and synthesize hardware)
+ To model hardware (i.e., to create simulation models that are not necessarily synthesizable)
+ To verify hardware (i.e., to test designs)
+ Designing Hardware
+ Important guidelines of writing Verilog code for designing, i.e., modeling and synthesizing, hardware:
:::info
+ Do not use initial blocks.
+ Initial blocks are usually ignored during synthesis.
+ Do not use delays (either delayed assignment or delayed evaluation).
+ Delays are ignored during synthesis.
+ If possible, use concurrent assignments (assign) to design combinational logic.
+ It is possible to use procedural assignments (always blocks) to design either combinational logic or sequential logic.
+ When procedural assignments (always blocks) are used for combinational logic, use blocking assignments “=“.
+ When procedural assignments (always block) are used for sequential logic, use non-blocking assignments “<=“.
+ Do not mix blocking and non-blocking statements in an always block.
+ Do not make assignments to the same variable from more than one always block.
+ Avoid unwanted latches by assigning a value to combinational output signals in every possible execution path in the always block.
:::
+ Modeling Hardware
+ Important guidelines of writing Verilog for modeling, i.e., creating simulation models which are not necessarily synthesizable, hardware:
:::info
+ If delays are not to be modeled, use blocking assignments “=“ for combinational logic and non-blocking assignments “<=“ for sequential logic.
+ In **blocking assignments** with no delay specification, the new values are assigned **immediately without any delta delays**.
+ In **non-blocking** assignments with no delay specification, the change is scheduled to occur **after a delta time**.
+ To model combinational logic with inertial delays, use delayed evaluation blocking statements.
+ E.g.: #10 A = B;
+ To model combinational logic with transport delays, use delayed assignment non-blocking assignments.
+ E.g.: A <= #10 B;
+ This has to be inside an always statement.
+ To model sequential logic with delays, use delayed assignment non-blocking assignments.
+ E.g.: A <= #10 B;
+ This has to be inside an always statement.
+ Use inertial delays if pulse-rejection behavior is required.
:::
+ Verifying Hardware
+ Verification models and test benches mostly use initial blocks w/ blocking assignments and delayed assignments.
+ Although all types of assignment statements can be used in verification models, use blocking assignments if possible.
+ When delays are used, pay attention to inertial behavior.
+ Use initial blocks to hard code test stimulus values.
+ Use parameters for creating constants so test benches can easily be modified.
[reference link]https://hom-wang.gitbooks.io/verilog-hdl/content/Chapter_01.html
###### tags: `Digital System Design` `verilog`