4-Bit Up/Down Counter VHDL Source Code

This document presents VHDL source code for a 4-bit up/down counter.

VHDL Code

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity Counter_VHDL is
    port (
        Number    : in  std_logic_vector(0 to 3);
        Clock     : in  std_logic;
        Load      : in  std_logic;
        Reset     : in  std_logic;
        Direction : in  std_logic;
        Output    : out std_logic_vector(0 to 3)
    );
end Counter_VHDL;

architecture Behavioral of Counter_VHDL is
    signal temp : std_logic_vector(0 to 3);
begin
    process (Clock, Reset)
    begin
        if Reset = '1' then
            temp <= "0000";
        elsif (Clock'event and Clock = '1') then
            if Load = '1' then
                temp <= Number;
            elsif (Load = '0' and Direction = '0') then
                temp <= temp + 1;
            elsif (Load = '0' and Direction = '1') then
                temp <= temp - 1;
            end if;
        end if;
    end process;

    Output <= temp;

end behavioral;

Explanation

The VHDL code defines a 4-bit up/down counter with the following inputs and outputs:

  • Number: A 4-bit input used to load a specific value into the counter.
  • Clock: The clock signal that drives the counter.
  • Load: A control signal that, when asserted (‘1’), loads the value from the ‘Number’ input into the counter.
  • Reset: A reset signal that, when asserted (‘1’), resets the counter to “0000”.
  • Direction: A control signal that determines whether the counter counts up (‘0’) or down (‘1’).
  • Output: A 4-bit output that represents the current count value.

The architecture Behavioral describes the counter’s functionality. A process sensitive to the Clock and Reset signals implements the counter’s behavior.

  • When Reset is ‘1’, the internal signal temp (which holds the current count) is reset to “0000”.
  • On the rising edge of the Clock, the code checks the Load signal.
    • If Load is ‘1’, the temp signal is loaded with the value from the Number input.
    • If Load is ‘0’, the code checks the Direction signal.
      • If Direction is ‘0’, the temp signal is incremented (counts up).
      • If Direction is ‘1’, the temp signal is decremented (counts down).

Finally, the Output signal is assigned the value of the temp signal, making the current count available as an output.