Problem: Implement Encoder in Verilog (Gate Level)
Objective
An Encoder is a combinational circuit that converts 2ⁿ input lines into n output lines.
At any time, only one input should be active (logic 1).
The encoder outputs the binary code corresponding to the active input line.
In this tutorial, we will design a 4-to-2 encoder in Verilog and verify it using a testbench.
Explanation (How it works)
A 4-to-2 encoder has:
- Inputs:
I0, I1, I2, I3
- Outputs:
Y1, Y0
Encoding rules:
- If
I0 = 1
→ Output =00
- If
I1 = 1
→ Output =01
- If
I2 = 1
→ Output =10
- If
I3 = 1
→ Output =11
Boolean equations:
Y0 = I1 | I3
Y1 = I2 | I3
Limitation: If more than one input is 1
, the output becomes undefined.
(That’s why we use a Priority Encoder in real designs.)
Requirements
- Create a Verilog module named
encoder4to2
with:- Inputs:
I0, I1, I2, I3
- Outputs:
Y0, Y1
- Inputs:
- Implement the Boolean equations:
assign Y0 = I1 | I3;
assign Y1 = I2 | I3;
- Write a
testbench
module:- Activate one input at a time.
- Verify that outputs match the expected binary code.
Expected Truth Table
I3 | I2 | I1 | I0 | Y1 | Y0 |
---|---|---|---|---|---|
0 | 0 | 0 | 1 | 0 | 0 |
0 | 0 | 1 | 0 | 0 | 1 |
0 | 1 | 0 | 0 | 1 | 0 |
1 | 0 | 0 | 0 | 1 | 1 |
Test Plan (What to do)
- Apply test vectors where exactly one input is
1
. - Check that the outputs match the binary code of the active input.
- (Optional) Try multiple active inputs and observe undefined behavior.
Common Pitfalls
- Forgetting that only one input should be 1 at a time.
- Confusing encoder with decoder (they are opposites).
- Mixing up the order of outputs (
Y1
is MSB,Y0
is LSB).
Extension (Challenge)
- Implement an 8-to-3 encoder using our text editor.
- Upgrade the design to a Priority Encoder (gives highest priority to the highest-numbered input when multiple inputs are active).
No Waveform Data
Submit your Verilog code using Cmd+Enter to see the simulation results and waveform visualization.