Implement Decoder in Verilog (gate level)
Objective
A Decoder is a combinational circuit that converts n input lines into 2ⁿ unique outputs.
It activates exactly one output line corresponding to the binary code of the input.
In this tutorial, we will design a 2-to-4 decoder in Verilog and verify it using a testbench.
Explanation (How it works)
A 2-to-4 decoder has:
- Inputs:
A1, A0(2-bit binary input) - Outputs:
D0, D1, D2, D3
Decoding rules:
- If input =
00→D0 = 1 - If input =
01→D1 = 1 - If input =
10→D2 = 1 - If input =
11→D3 = 1
All other outputs remain 0.
Boolean equations:
D0 = ~A1 & ~A0D1 = ~A1 & A0D2 = A1 & ~A0D3 = A1 & A0
Requirements
- Create a Verilog module named
decoder2to4with:- Inputs:
A1, A0 - Outputs:
D0, D1, D2, D3
- Inputs:
- Implement the Boolean equations for each output.
- Write a
testbenchmodule:- Apply all 4 input combinations (
00,01,10,11). - Verify that exactly one output is active at a time.
- Apply all 4 input combinations (
Expected Truth Table
| A1 | A0 | D0 | D1 | D2 | D3 |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 0 | 0 |
| 1 | 0 | 0 | 0 | 1 | 0 |
| 1 | 1 | 0 | 0 | 0 | 1 |
Test Plan (What to do)
- Simulate
testbenchand apply all input combinations. - Confirm only one output is high for each input code.
- Compare simulation results with the truth table.
Common Pitfalls
- Forgetting to invert the inputs for equations of
D0andD1. - Activating multiple outputs at once (incorrect).
- Mixing up decoder vs encoder (decoder expands inputs, encoder compresses inputs).
Extension (Challenge)
- Design a 3-to-8 decoder using the same method.
- Add an enable input (EN) that controls whether outputs are active or forced to
0. - Implement a hierarchical decoder (e.g., build a 3-to-8 decoder using two 2-to-4 decoders).
No Waveform Data
Submit your Verilog code using Cmd+Enter to see the simulation results and waveform visualization.