VHDL Code for a 2 to 4 Decoder

This page provides the VHDL source code for a 2 to 4 decoder. You’ll also find the block diagram and truth table to help understand how it works.

Block Diagram of 2 to 4 Decoder

2 to 4 Decoder Block Diagram

Truth Table of 2 to 4 Decoder

2 to 4 Decoder Truth Table

2 to 4 Decoder VHDL Code

Here’s the VHDL code implementing the 2 to 4 decoder:

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;

entity decoder2_4 is
    port (
        en   : in  std_logic;
        d_in : in  std_logic_vector (1 downto 0);
        d_op : out std_logic_vector (3 downto 0)
    );
end decoder2_4;

architecture behavioral of decoder2_4 is
begin
    process (en, d_in)
    begin
        if (en = '1') then
            d_op <= "ZZZZ"; -- High impedance when enable is active
        else
            case (d_in) is
                when "00" => d_op <= "0001";
                when "01" => d_op <= "0010";
                when "10" => d_op <= "0100";
                when "11" => d_op <= "1000";
                when others => null; -- Optional: handles unexpected input combinations
            end case;
        end if;
    end process;
end behavioral;

Explanation:

  • Library Declarations: The code starts by including necessary libraries for standard logic operations.
  • Entity Declaration: The entity declaration defines the input and output ports of the decoder.
    • en: Enable input (std_logic). When ‘1’, the output is high impedance (“ZZZZ”).
    • d_in: 2-bit input vector (std_logic_vector).
    • d_op: 4-bit output vector (std_logic_vector).
  • Architecture Declaration: The architecture describes the behavior of the decoder.
  • Process: A process is used to implement the logic. It’s sensitive to changes in the en and d_in signals.
  • Enable Logic: If the en (enable) input is ‘1’, the output d_op is set to “ZZZZ” (high impedance), effectively disabling the decoder.
  • Case Statement: The case statement decodes the 2-bit input d_in and sets the corresponding output bit in d_op to ‘1’, while the other bits are ‘0’.
  • when others: This is optional, but good practice. It handles any input combination that isn’t explicitly defined, preventing unexpected behavior. In this example, null means no action is taken.