0% found this document useful (0 votes)
45 views27 pages

Verilog Notes

The document outlines various Verilog design styles, including dataflow, behavioral modeling, and structural modeling, along with their syntax and examples. It also discusses the representation of logic values, the use of operators, and the implementation of case statements for multi-way branching. Additionally, it emphasizes the importance of using 'wire' and 'reg' types appropriately in Verilog.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views27 pages

Verilog Notes

The document outlines various Verilog design styles, including dataflow, behavioral modeling, and structural modeling, along with their syntax and examples. It also discusses the representation of logic values, the use of operators, and the implementation of case statements for multi-way branching. Additionally, it emphasizes the importance of using 'wire' and 'reg' types appropriately in Verilog.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Verilog design styles

25 May 2025 08:56

1) Dataflow design style


It is used when we know the boolean expression
Eg of dataflow

{i1,i2}- concatination opertator - contatinates the input i1 and i2 and assigns them to result[3:2]
In verilog the lsb to sg goes from right to left (ie)
[msb:lsb]

2) Behavioral modelling
Used in sequential logic (flip flops)
Use of always block
1. To model repetitive activity in a digital design. Ex. clock generation.

2. To implement combinational and sequential elements in digital circuits

From <https://vlsiverify.com/verilog/behavioral-modeling/>

Uses a always l statement


Syntax
always
<single statement>

always @(<sensitivity_list>)
<single statement>

always @(<sensitivity_list>) begin


<statement 1>
<statement 2>
<statement 3>
...
...
End
Sensitivity list
The sensitivity list can be a single or multiple signals placed within parentheses () after @ operator. Based on the change in any signal value, it allows executing the always
block.(basically when the input changes the always block gets executed )
If the sensitivity list includes all inputs, then only ‘*’ is used to represent all inputs instead of writing all inputs.

From <https://vlsiverify.com/verilog/behavioral-modeling/>

Example of behavioral code with always statement

New Section 1 Page 1


We put the out as reg bcz we need the out to keep in storing the value until the data changes again like if the present output is 1 then it needs to keep on storing 1 until the next
clock cycle (or next input change )

3) Structural Modelling
In this type we instantiate blocks (those blocks can be made up of behavioral or dataflow modelling )
Instantiation
Example

Alll the models in the instantiation shd be in order

Another way to instantiate module_name instance_name (.port_name(signal), ...);


dff my_dff1 (.clk(clk), .d(d), .q(q)); // instance created (example)

Structual modelling of a 2:1 mux

CIRCUIT DIAGRAM

New Section 1 Page 2


Code

Gate declaration ex
Xor xor1(op,a,b);

FULL ADDER USING 2 HALF ADDER IN VERILOG

Circ dig

New Section 1 Page 3


TYPES OF LOGIC IN VERILOG
4) 0 can represent
Logic zero
Strong zero
False - if statements
If(s) executes when s-1
Else-executes when s=0
Low state

5) 1 can represent
Logic one
Strong one
true - if statements
If(s) executes when s-1
Else-executes when s=0
High state

6) X- unknown
We don’t know what the op will be
Conflict- there are multiple values (ie the fin might be floating so we don’t know if it’s a one or zero )
Metastability - the clock and the input change at the same time so there might be a uncertainity in the output -(no proper setup and hold time )
Uninitialized- lets take a d flip flop with positve edge rising ( what is the value of the flip flop b4 the rising edge of the clock)

New Section 1 Page 4


7) Z- high impedence state

No output is being driven

SIZED NUMBERS IN VERILOG


Syntax:
[size]'[base_format][number]

From <https://www.chipverify.com/verilog/verilog-syntax>

3'b010; // size is 3, base format is binary ('b), and the number is 010 (indicates value 2 in binary)
3'd2; // size is 3, base format is decimal ('d) and the number is 2 (specified in decimals)
8'h70; // size is 8, base format is hexadecimal ('h) and the number is 0x70 (in hex) to represent decimal 112
9'h1FA; // size is 9, base format is hexadecimal ('h) and the number is 0x1FA (in hex) to represent decimal 506
4'hA = 4'd10 = 4'b1010 = 4'o12 // Decimal 10 can be represented in any of the four formats
8'd234 = 8'D234 // Legal to use either lower case or upper case for base format
32'hFACE_47B2; // Underscore (_) can be used to separate 16 bit numbers for readability

From <https://www.chipverify.com/verilog/verilog-syntax>

16'hcafe; // lowercase letters Valid


16'hCAFE; // uppercase letters Valid
32'h1D40_CAFE; // underscore can be used as separator between 4 letters Valid

From <https://www.chipverify.com/verilog/verilog-syntax>

UNSIZED AND NEGATIVE NUMBERS :

The negative numbers are converted into 2s complement and then they are stored
Eg:
x=-6'd3;// the 2's complement of 3 is calculated and then stored in X

For behavioral modeliing see this :


https://chatgpt.com/share/68543c05-2a28-8011-a004-1e9531ba4ce2

New Section 1 Page 5


2s complement and gates
25 May 2025 11:58

If the last digit is one (1) you need to extend the sign bit to how much ever value you need to preserve the sign
For example, here is an eight-bit two's complement representation of some integer:
1001 0110
and here is the 16-bit two's complement representation of the same integer:
1111 1111 1001 0110

From <https://chortle.ccsu.edu/assemblytutorial/zAppendixH/appH_12.html>

Even though u are extending the bit you need to preserve the sign (1)

Gates and BIT MASKING


And- && (&-bitwise)
Or- ||- logical (|-bitwise)
Not-~
Xor-^

New Section 1 Page 6


XOR: Logical or Bitwise?
XOR is a bitwise operator in Verilog.
There is no "logical XOR" operator in Verilog — only bitwise XOR.
reg [3:0] a = 4'b1101;
reg [3:0] b = 4'b1010;
reg [3:0] result;

assign result = a ^ b; // Bitwise XOR


Result:
• a = 1101
• b = 1010
• a ^ b = 0111 ← XOR done bit by bit

❗ ! vs ~ in Verilog
Operator Meaning Works On Result
! Logical NOT 1-bit value 1-bit (0 or 1)
~ Bitwise NOT Bit-vector (or int) Bitwise inverted
But if you want to XOR two 4-bit values as if they are booleans (i.e., non-zero = true), you can reduce them down to 1-bit:
Example: 4-bit logical XOR behavior

reg [3:0] a = 4'b0000;


reg [3:0] b = 4'b1010;
wire logical_xor;
assign logical_xor = ((|a) || (|b)) && !((|a) && (|b)); // behaves like logical XOR
Explanation:
• |a → reduction OR → checks if any bit of a is 1
• Result is 1-bit (true/false)
• Works just like logical XOR

But if you want to XOR two 4-bit values as if they are booleans (i.e., non-zero = true), you can reduce them down to 1-bit:
Example: 4-bit logical XOR behavior

reg [3:0] a = 4'b0000;


reg [3:0] b = 4'b1010;
wire logical_xor;
assign logical_xor = ((|a) || (|b)) && !((|a) && (|b)); // behaves like logical XOR
Explanation:
• |a → reduction OR → checks if any bit of a is 1
• Result is 1-bit (true/false)
• Works just like logical XOR

New Section 1 Page 7


Masking of bits and when to use wire and reg
25 May 2025 13:14

WHEN TO USE WIRE AND REG


Wire is most commonly used when you are connecting the output of a device to another device (eg op
of a and gate to a or gate)
Or when u want to temporarily asssign some value
Reg
It is used when you want to store the value (used in behavioral statements,flip flops )

New Section 1 Page 8


New Section 1 Page 9
Operators (except logical)
25 May 2025 13:26

Arithmetic operators
1) + it is used to add any 2 numbers and store the result
a=3'b101;
b=3'b110;
c=a+b;
Note that c must be 3 bits to store the value of a+b;
Also if a extra term results becasuse of the carry operator, like if the sum of the last 2 terms turns out to be one then,the re will be an extra bit, that bit will get truncated
unless c is a 4 bit term

2) Subraction operator
Subracts numbers and stores the result
Eg: (same values frm b4)
c=a-b(takes the 2c complement of b and it is added with A and stored in C

3) Multiplication operator
c=a*b;
The multiplied value is stored in x

4) Division operator
c=a/b;
Forms a barrel shifter hardware
Eg
y=27/8 8=2^3
27=11011;
After division 27 becomes
00011; you shift means u remove the last 3 terms and then put the remaining terms in there;
And replace the terms with zero

//removing last 3 terms


11011-->11000
//putting the remaining terms there
11000-->00011
To learn more see this
https://www.chipverify.com/verilog/verilog-operators

New Section 1 Page 10


16 June 2025 21:09

$ moniter- executes whenever the inputs(a,b,cin changes)

REPEAT Statement:
You're on the right track! Let's break everything down step-by-step to clarify repeat, the bit-widths, and why a and b have 16 values while cin only has 2.

repeat(n) in Verilog
Think of Verilog's repeat(n) as:
repeat(n) begin
// code block
end
This simply repeats the code block n times, no automatic variable increment like a for loop. It is not the same as a Python for i in range(n) in terms of variable scope — it just repeats, nothing more.
So if you want to increment something like a = a + 1, you must explicitly write it inside the block, as you see in your image.

What’s Happening in Your Code


Here's a breakdown:
initial begin
a = 0; b = 0; cin = 0; // starting values
repeat(16) begin // outer loop (a)
#10 a = a + 1;
repeat(16) begin // middle loop (b)
#10 b = b + 1;
repeat(2) begin // inner loop (cin)
#10 cin = ~cin; // flip 0<->1
end
end
end
end

Why a and b have 16 values


You mentioned that a and b are 4-bit wide. That’s very important.
A 4-bit number can represent values from:
0000 to 1111 (in binary)
= 0 to 15 (in decimal)
=> Total = 16 values
That’s why:
• a goes from 0 to 15
• b goes from 0 to 15
Each repeat(16) simulates one of those 16 possible values.
Why cin has only 2 values
cin is a 1-bit input, so:
0 or 1
=> Only 2 values
And inside the inner-most loop, you flip its value using cin = ~cin, so:
• cin = 0 becomes 1
• cin = 1 becomes 0
Hence, 2 iterations (repeat(2)), just enough to test both possibilities.

Total Combinations Being Tested


Let’s calculate how many test cases the simulation will run:
• 16 values for a
• 16 values for b

New Section 1 Page 11


• 16 values for b
• 2 values for cin
So total test combinations:
16 × 16 × 2 = 512 different combinations
Each one will be simulated with a delay of #10, and results printed using $monitor.

✅ Summary Notes
Concept Explanation
repeat(n) Executes the block exactly n times (like a loop, but without automatic index variable)
a and b Are 4-bit variables → 2⁴ = 16 values each (0 to 15)
cin Is 1-bit → only 2 values (0 and 1)
Total Cases 16 × 16 × 2 = 512
~cin Bitwise NOT (flips 0↔1)
$monitor(...) Prints variables every time one of them changes

If you'd like, I can also help you write this same nested loop structure using a for loop style in Verilog for better control. Would you like that?

From <https://chatgpt.com/c/68503ce8-5f54-8011-90de-5ec992bbb38b>

Case statements in verilog

Absolutely! Let’s break down case statements in Verilog in a very simple and clear way — with examples, notes, and common pitfalls.

What is a case statement in Verilog?


A case statement in Verilog is used to implement multi-way branching, like a switch-case in C or Python's match-case (from Python 3.10+).
It is used mainly in behavioral modeling inside always blocks.

Syntax
case (expression)
value1: statement1;
value2: statement2;
...
default: default_statement;
endcase

✅ Basic Example
Let’s say we want to design a 2-to-1 multiplexer:
always @(*) begin
case (sel)
2'b00: y = a;
2'b01: y = b;
default: y = 1'b0; // optional
endcase
end

✅ Real-Life Example: 4:1 MUX


module mux4to1_case (
input wire [1:0] sel,
input wire [7:0] i0, i1, i2, i3,
output reg [7:0] y
);
always @(*) begin
case (sel)
2'b00: y = i0;
2'b01: y = i1;
2'b10: y = i2;
2'b11: y = i3;
default: y = 8'b00000000; // optional safety net
endcase
end
endmodule

Case vs If-Else
if-else case
Good for range comparisons Good for checking exact values
Can be less readable with many cases Very readable for fixed choices
Supports inequalities (>, <, etc) Only equality matching

1. default case
• Always add a default case to avoid latch inference (especially in combinational logic).
• Example:
default: y = 8'b00000000;
2. Full coverage
• If you don’t handle all possible input values, Verilog might create unexpected hardware (like latches).
3. Expression width
• Make sure the case expression width matches the value widths.
case (sel) // sel is 2 bits
2'b00: ... // good
2: ... // also OK (2 == 2'b10)
endcase

New Section 1 Page 12


endcase
4. Use reg type for outputs inside always
• If you're assigning inside always, the output variable must be declared as reg.

Common Mistakes
Mistake Fix
Missing endcase Always end your case block with endcase.
No default case Add one even if it's a dummy assignment.
Using = in procedural blocks without reg type Declare outputs as reg.
Not using always @(*) for combinational logic Use @(*) to cover all input sensitivities.

✨ Summary
Component Purpose
case Multi-way selection based on exact value
sel Selector input (expression in case)
default Optional fallback (important for safety)
endcase Required to close the block
Use in always @(*) or always @(posedge clk)

Would you like to try a quiz or exercise using case to test your understanding?

From <https://chatgpt.com/c/68503ce8-5f54-8011-90de-5ec992bbb38b>

New Section 1 Page 13


2:1 mux design
18 June 2025 20:40

!) using Dataflow model :

BEGIN AND END STATEMENTS:

1
begin/end keywords are mandatory when you have multiple statements within an always block.
In your 1st always block, you don't need begin/end since the case statement is considered a single statement.
However, in your 2nd always block, you have 3 top-level if statements, which means you need to group them together inside begin/end. Here is the code with different whitespace to clearly show the separate
statements:
always@(posedge clock or state) begin
// Statement 1
if(!state) outstate <= 4'd0;
// Statement 2
if(state == 2'd1)
if(outstate != 4'd9)
outstate <= outstate +4'd1;
else
outstate <= 4'd0;
// Statement 3
if(state == 2'd2) outstate <= outstate;
end
Since this code compiles without syntax errors, it demonstrates a couple things:
1. The begin/end keywords shown are mandatory
2. No other begin/end keywords are needed
However, other begin/end keywords are optional. You may decide to use them in every if statement. Here is another way to write the code:
always@(posedge clock or state) begin
if (!state) begin
outstate <= 4'd0;
end
if (state == 2'd1) begin
if (outstate != 4'd9) begin
outstate <= outstate +4'd1;
end else begin
outstate <= 4'd0;
end
end
if (state == 2'd2) begin
outstate <= outstate;
end
end
The same rules apply for initial and final procedural blocks, just like they do for always blocks.
From <https://stackoverflow.com/questions/70344979/usage-of-begin-end-in-design-modules/70350101#70350101>

New Section 1 Page 14


Since this is just a single if else statement we don’t have to put a
begin or an end statement here

So basically since S is a 2 bit input


And if S is 00 then the I[0] will be implemeted and is S is 01 then I[1] will be implemented and so on
This same logic can be used for a 8:1 mux a 16:1 mux a 32:1 mux and so on

The delay for all the signals is also same

This type of code assigns priority to the inputs ie the zeros gets executed first and fastest (00)
And then 11 is given the next priority and so on

Absolutely! Here's a clear and concise set of notes on reduction operators in Verilog, with detailed explanations and examples.

Reduction Operators in Verilog


Reduction operators take a vector (multi-bit signal) and reduce it to a single bit by applying a bitwise logic operation across all the bits.

List of Common Reduction Operators


Operator Name Description Example
& Reduction AND True if all bits are 1 &a
` ` Reduction OR True if any bit is 1
^ Reduction XOR True if odd number of 1's ^a
~& Reduction NAND Negation of AND → False only if all 1s ~&a
`~ ` Reduction NOR Negation of OR → True only if all 0s
~^ or ^~ Reduction XNOR True if even number of 1's ~^a or ^~a

Detailed Explanation with Examples


Assume:
wire [3:0] a = 4'b1101; // Bits: a[3]=1, a[2]=1, a[1]=0, a[0]=1

&a → R duc i A D
• Meaning: Are all bits 1?
• a = 1101 → 1 & 1 & 0 & 1 = 0
assign y = &a; // y = 0

|a → R duc i OR

New Section 1 Page 15


|a → R duc i OR
• Meaning: Is any bit 1?
• a = 1101 → 1 | 1 | 0 | 1 = 1
assign y = |a; // y = 1

^a → R duc i XOR
• Meaning: XOR all bits → true if odd number of 1's
• a = 1101 → 1 ^ 1 ^ 0 ^ 1 = 1
assign y = ^a; // y = 1 (since three 1's)

~&a → R duc i A D
• Equivalent to: ~(&a)
• a = 1101 → &a = 0 → ~0 = 1
assign y = ~&a; // y = 1

~|a → R duc i OR
• Equivalent to: ~(|a)
• a = 1101 → |a = 1 → ~1 = 0
assign y = ~|a; // y = 0

~^a or ^~a → R duc i X OR


• True if even number of 1's
• a = 1101 → 3 ones → odd → result is 0
assign y = ~^a; // y = 0

Key Observations:
• Reduction operators convert a vector into a single logic value.
• They are often used in control logic, comparisons, zero-checks, and priority logic.

✅ Use Cases
1. Zero check:
assign is_zero = ~|data; // true if all bits in data are 0
1. All-ones check:
assign is_full = &data; // true if all bits are 1
1. Odd parity check:
assign odd_parity = ^data;
1. Even parity check:
assign even_parity = ~^data;

Summary Table:
| Input Bits | &a | |a | ^a | ~&a | ~|a | ~^a |
|-----------------|----|----|----|------|------|------|
| 0000 | 0 | 0 | 0 | 1 | 1 | 1 |
| 1111 | 1 | 1 | 0 | 0 | 0 | 1 |
| 1010 (2 ones) | 0 | 1 | 0 | 1 | 0 | 1 |
| 1101 (3 ones) | 0 | 1 | 1 | 1 | 0 | 0 |

Bonus Tip: Visualizing Reduction Logic in Simulation


When writing testbenches, you can print and simulate expressions like:
$display("Reduction AND of a = %b", &a);
$display("Reduction OR of a = %b", |a);

Let me know if you'd like this as a PDF, or want visual waveforms for simulation!

From <https://chatgpt.com/c/6852dd67-aa7c-8011-b100-bea6388d1c95>

Explanation for the tenary operator

Let's deeply break down the Verilog expression from your image:

Original Code:
assign Y = ~|S ? I[0] : (&S ? I[3] : (S[0] ? I[1] : I[2]));

Syntax:
condition ? value_if_true : value_if_false
From <https://www.google.com/search?
q=ternary+operator&oq=tenary+&gs_lcrp=EgZjaHJvbWUqDAgBEAAYChixAxiABDIGCAAQRRg5MgwIARAAGAoYsQMYgAQyDAgCEAAYChixAxiABDIJCAMQABg KGIAEMg8IBBAAGAoYgwEYsQMYgAQyCQgFEAAYChiABDIJCAYQABgKGIAEMgkIBxAAGAoYgAQyCQgIEAAYChiABDIJCAkQABgKGIAE0gEIMzYzMWowajeoAgCwAgA& sourceid=chrome&ie=UTF-8>

What This Does:


This is a nested ternary (conditional) operator expression that evaluates S and selects one of the values from the input vector I.

Key Concepts Used:


• ~|S → Reduction NOR: True (1) only if all bits of S are 0
• &S → Reduction AND: True (1) only if all bits of S are 1
• S[0] → Refers to the LSB of S
• ? : → Ternary conditional: condition ? true_case : false_case

Step-by-Step Evaluation:
Let’s go through the ternary conditions in priority order:
✅ 1. ~|S ? I[0]
• This checks if all bits of S are 0.
• If true → output Y = I[0]
❌ Else → Ch ck &S ? [3]
• Checks if all bits of S are 1.
• If true → output Y = I[3]
❌ Else → Ch ck S[0] ? [1] : [2]
• If S[0] is 1 → Y = I[1]
• Else → Y = I[2]

Truth Table Summary:


| S | ~|S | &S | S[0] | Output |
|-------|-----|-----|------|--------|
| 000 | 1 | 0 | 0 | I[0] |
| 111 | 0 | 1 | 1 | I[3] |
| 001 | 0 | 0 | 1 | I[1] |
| 010 | 0 | 0 | 0 | I[2] |
| ... | ... | ... | ... | ... |

What's the Purpose?


This is essentially 4-input selection logic, like a mini multiplexer based on the value of S:
Condition Output

New Section 1 Page 16


Condition Output
S == 000 I[0]
S == 111 I[3]
Otherwise + S[0]=1 I[1]
Otherwise + S[0]=0 I[2]
So it chooses:
• I[0] when S is all 0s
• I[3] when S is all 1s
• I[1] or I[2] depending on S[0]

C d C i :
assign Y = ~|S ? I[0] : // if all S bits are 0 → I[0]
(&S ? I[3] : // else if all S bits are 1 → I[3]
(S[0] ? I[1] : // else if S[0] is 1 → I[1]
I[2])); // else → I[2]

Summary:
• This is a compact and clever way of implementing conditional selection based on multiple conditions using reduction operators .
• Very common in FSMs or MUX logic where the control signal (S) is a few bits wide.
Let me know if you want a waveform example or how to convert this to a case statement or always block!

From <https://chatgpt.com/c/6852dd67-aa7c-8011-b100-bea6388d1c95>

The tenary operator thing explained clearly

Absolutely — let's walk through the syntax of how nested ternary operators (? :) work in Verilog, especially when implementing something like a 4:1 multiplexer using them.

Basic Ternary Syntax in Verilog


The ternary operator format is:
condition ? value_if_true : value_if_false;
✅ It's exactly like an if-else statement, but in one line.

Nested Ternary for a 4:1 MUX


A 4:1 multiplexer selects one of four inputs (I[0] to I[3]) based on a 2-bit select signal (S[1:0]).
If you were writing this in logic, you might say:
if (S == 2'b00) Y = I[0];
else if (S == 2'b01) Y = I[1];
else if (S == 2'b10) Y = I[2];
else if (S == 2'b11) Y = I[3];
Using ternary operators, this becomes:
assign Y = (S == 2'b00) ? I[0] :
(S == 2'b01) ? I[1] :
(S == 2'b10) ? I[2] :
I[3]; // if none of the above, default to I[3]
Nested ternary is right-associative, meaning:
This:
a?b:c?d:e
Is interpreted as:
a ? b : (c ? d : e)

Now Your Example:


assign Y = ~|S ? I[0] : (&S ? I[3] : (S[0] ? I[1] : I[2]));
Here’s how the nesting works:
Step-by-step:
1. ~|S — checks if all bits in S are 0 → select I[0]
2. Else, check &S — are all bits in S 1 → select I[3]
3. Else, check S[0]:
○ If S[0] is 1 → select I[1]
○ Else → select I[2]
Rewritten cleanly:
assign Y = (~|S) ? I[0] :
(&S) ? I[3] :
(S[0]) ? I[1] :
I[2];

Syntax Tips:
• You can nest ternary operators as deeply as needed, but use parentheses or formatting to keep it readable.
• Think of it like a decision tree: top condition gets checked first, then fallbacks go deeper.
• Verilog evaluates right to left for nested ternaries.

TL;DR – Syntax Summary:


• ✅ a ? b : c → Simple decision
• ✅ Nested: a ? b : (c ? d : e)
• For a 4:1 MUX, use chained ternaries or use a case block instead for readability if the logic is complex.

Let me know if you’d like the always block version or a case version too!

From <https://chatgpt.com/c/6852dd67-aa7c-8011-b100-bea6388d1c95>

Case statement: Has no priority and makes the selection based on a particular case line or a selection

New Section 1 Page 17


Case statement: Has no priority and makes the selection based on a particular case line or a selection

The Synthesis ignores the display statement so its only used in simulation
Also in this case all of them have equal priority

module top_module (
input clk,
input [7:0] d,
input [1:0] sel,
output reg [7:0] q // <- make q a reg
);
wire [7:0] w1, w2, w3;

my_dff8 inst1(clk, d, w1); // stage 1


my_dff8 inst2(clk, w1, w2); // stage 2
my_dff8 inst3(clk, w2, w3); // stage 3

always @(*) begin


case(sel)
2'd0: q = w3;
2'd1: q = w2;
2'd2: q = w1;
2'd3: q = d;
default: q = 8'd0; // optional fallback
endcase
end

endmodule

New Section 1 Page 18


problems
23 June 2025 18:59

In verilog if we don’t give/specify the size of the bits the operator will assume it’s the complete size

In Verilog, the concatenation operator {} combines multiple signals (wires, regs, constants, etc.) into a single vector, and the order matters very specifically in terms of bit positions.

Rule of Thumb:
Left to right = Most Significant Bit (MSB) to Least Significant Bit (LSB)
In other words:
• Leftmost element inside the {} becomes the upper bits.
• Rightmost element becomes the lower bits.

Example:

verilog

wire [3:0] a = 4'b1010;


wire [3:0] b = 4'b1100;
wire [7:0] c;
assign c = {a, b}; // Concatenation
This means:
• c[7:4] = a = 4'b1010
• c[3:0] = b = 4'b1100
So the result:
c = 8'b10101100
Let’s break it down clearly.

Key Clarification:
"The code for one module is not written inside another module's body"

"You cannot instantiate a module inside another module."
They're saying:
✅ You can instantiate a module inside another module.
❌ You cannot write the full definition of one module inside another.

What You CAN Do (This is Normal & Correct):

verilog
CopyEdit
module top_module(input a, input b, output out);
mod_a instance1(a, b, out); // This is an instantiation — 100% correct!
endmodule

module mod_a(input in1, input in2, output out);


// Module body (assume it's defined separately)

New Section 1 Page 19


// Module body (assume it's defined separately)
endmodule
✅ This is correct Verilog. You're simply saying:
"Hey, inside top_module, I'm using a circuit called mod_a, and here's how its ports are connected."
This is called instantiation, and it’s exactly how hierarchical design works in Verilog.

❌ What You CANNOT Do (This is Illegal):

verilog
CopyEdit
module top_module(input a, input b, output out);
module mod_a(input in1, input in2, output out); // ❌ You CANNOT define a module here
// Illegal nested definition
endmodule
endmodule
This is invalid because you're trying to define a module inside another module, which Verilog does not allow.

module top_module(input a, input b, output out);


mod_a instance1(a, b, out); // Connects top_module's a, b, and out
endmodule
You can reuse signal names like a, b, out across modules.
They are local to each module, and Verilog is smart enough to handle the connections based on position or named mapping.
Let me know if you want to test this or walk through a waveform example!

Instantiating module by name syntax:

.module_port_name(signal_in_current_scope)
module_port_name (the one after the dot .):
This is the port name inside the module you are instantiating.

Module port name=current signal in the module


Signal_in_current_scope=the signal in the scope you are defining

signal_in_current_scope (the one in parentheses):


This is the signal that exists in the current (parent) module — like top_module.

WHEN TO INSTANTIATE MODULES

✅ Your Summary (Rephrased and Confirmed)

New Section 1 Page 20


✅ Your Summary (Rephrased and Confirmed)
Case 1: Using Two 4:1 Muxes Inside One Mux Module
• You're making a mux module.
• Inside it, you instantiate two other muxes.
• To connect them internally, you use wire — correct ✅
• Those internal wires are not visible to the outside, so they do not need to be output — again, correct ✅
✅ So yes — you use wire for internal connections.

Case 2: Separate Modules for Logical Unit, Full Adder, Mux


• Each of these blocks (logical_unit, full_adder, etc.) is a separate module.
• They send outputs to another module (like top_module or the mux).
• That means the signal must come out of the module — so it must be declared as an output.
✅ Yes — if a module is outputting a signal to be used by another module, you must declare that signal as output in the port list .

New Section 1 Page 21


Decoder design
25 June 2025 21:27

Note that in the dataflow statement we use the concatination operator for Y (see the truth table and figure it out)

So if you want to like use the same output for multiple case statements you can just add a comma in the end and combine all o f them into one output
In our case when the enable is one the outputs get executed (each of them are assigned to a output) but when enable is zero t hey are all assigned to a single output(0001)

Also since you are using case statements the hardware will behave like a multiplexer (this hardware is a bit bulky then our d ataflow statement tho)

The display statement will only work for synthesis

New Section 1 Page 22


So,basically if the EN==1 and all the inputs I2 I1 and I0 are zero (the one in blue) then in that case the final case gets e xecuted (the final thing gives out 1)

New Section 1 Page 23


Encoder Design and priority encoder
26 June 2025 19:39

So,the bit Y[1] will be active if either the bits I[1] or I[0]= is one
And the bit y[0] will be one if the other bits 2 and 3 are one
The expression V is the or (bitwise) of all the bits and will only be zero if all the inputs (I[0] TO I[3] are zero)

Yes, the valid bit is a logical OR, but since we're using 1-bit values, logical OR and bitwise OR give the same result.
• All I[i]s are 1-bit (either 0 or 1)
• valid = I[0] | I[1] | I[2] | I[3] — This is a bitwise OR of 1-bit values, and it works like a logical OR here

New Section 1 Page 24


Great question! You're clearly thinking deeply about how numbers are represented — that’s essential for Verilog and digital design.
Let’s clear this up step by step, because I think what’s confusing you is:
• You're thinking in terms of binary-coded decimal (BCD) like 8421, but this is not BCD.
• This is just basic binary indexing based on position of input bits in the encoder.

What’s Actually Happening Here?


In this 4x2 encoder, the inputs are I[3:0], representing one-hot encoded inputs — only one of the bits is high at a time. The encoder outputs the binary index of the
active input.

Let’s go through this line:


4'd1: {V, Y} = 3'b100;
• 4'd1 = 4-bit number where only I[0] is 1:
→ I = 0001
• So input line 0 is active
• Output Y = 2'b00 (binary of 0) and V = 1 (valid)
• So {V,Y} = {1, 2'b00} = 3'b100

4'd2
This means:

A 4-bit number with decimal value 2

In binary: 4'd2 = 4'b0010

So if this line appears:

verilog
Copy
Edit
4'd2: {V,Y} = 3'b101;
What it means:

If the input I = 4'b0010 → only I[1] is 1 (this is the second input, zero-indexed)

Then:

Output Y = 2'b01 (binary index of input 1)

Valid bit V = 1

{V,Y} = 3'b101

Full Breakdown:
Decimal I[3:0] Active Input Y (binary index) V {V,Y}
4'd1 0001 I[0] 00 1 100
4'd2 0010 I[1] 01 1 101
4'd4 0100 I[2] 10 1 110
4'd8 1000 I[3] 11 1 111

New Section 1 Page 25


Why Not BCD?
BCD (Binary-Coded Decimal) means you represent decimal digits (0–9) in 4-bit binary, like:
Decimal BCD (8421)
0 0000
1 0001
2 0010
3 0011
... ...
But we’re not using BCD here — we are using the binary index of the input line that is active.
So:
• We don’t care that 4'd2 is 0010 in binary
• We care that input 1 is active → so output is binary 1 = 01

The Key Idea


This is what an encoder does:
• You give it one-hot inputs: only one of the inputs is 1 at a time
• It gives you binary code of the position of that input

Final Takeaway
This is not BCD. This is basic binary encoding of the index of the high bit in the input.
So {V,Y} = 3'b100 just means:
• V = 1 (valid input)
• Y = 2'b00 (input 0 is high → index 0 → binary = 00)
Let me know if you want me to draw or simulate this with a truth table or diagram!

From <https://chatgpt.com/c/685d562b-8540-8011-a738-5f6475179771>

New Section 1 Page 26


HOW DECIMAL NUMBERS ARE STORED IN VERILOG

But why does it show up or behave like binary 01?

Because under the hood, all numbers in Verilog are stored and manipulated in binary.
So even though you're writing 2'd1 (which is clearly a decimal 1), Verilog converts and stores that number in binary using the specified number of bits.

ch : u c
Be careful if your value is too large for the bit-width:

verilog
CopyEdit
2'd4 // ERROR or truncates to 2'b00 because 4 doesn't fit in 2 bits (max = 3)

New Section 1 Page 27

You might also like