Up-Down Counter VHDL Code

In digital design, a counter is a device which stores the number of times a particular event has occurred, often with respect to a clock signal. The most common type is a sequential digital logic circuit with an input line called the clock and multiple output lines representing the count. The values on the output lines represent a number in the binary or BCD number system. Each pulse applied to the clock input increments or decrements the number in the counter.

VHDL Code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_unsigned.ALL;

entity U_DCOUNTER is
    Port ( RESET : in  STD_LOGIC;
           U_D : in  STD_LOGIC;
           CLK : in  STD_LOGIC;
           Cout : out  STD_LOGIC_VECTOR (3 downto 0));
end U_DCOUNTER;
architecture U_DCOUNTER of U_DCOUNTER is
begin
process(CLK,RESET)
variable temp:STD_LOGIC_VECTOR (3 downto 0):="0000";
begin
if (RESET='1')then
temp:="0000";
elsif(CLK'event and CLK='1')then
if(U_D='1')then
temp:=temp+1;
else
temp:=temp-1;
end if;
end if;
Cout<=temp;
end process;
end U_DCOUNTER;



Testbench:

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
 
ENTITY Up_dn_count_tb IS
END Up_dn_count_tb;
 
ARCHITECTURE behavior OF Up_dn_count_tb IS 
 
    -- Component Declaration for the Unit Under Test (UUT)
 
    COMPONENT U_DCOUNTER
    PORT(
         RESET : IN  std_logic;
         U_D : IN  std_logic;
         CLK : IN  std_logic;
         Cout : OUT  std_logic_vector(3 downto 0)
        );
    END COMPONENT;
    

   --Inputs
   signal RESET : std_logic := '0';
   signal U_D : std_logic := '0';
   signal CLK : std_logic := '0';

  --Outputs
   signal Cout : std_logic_vector(3 downto 0);

   -- Clock period definitions
   constant CLK_period : time := 10 ns;
 
BEGIN
 
-- Instantiate the Unit Under Test (UUT)
   uut: U_DCOUNTER PORT MAP (
          RESET => RESET,
          U_D => U_D,
          CLK => CLK,
          Cout => Cout
        );

   -- Clock process definitions
   CLK_process :process
   begin
CLK <= '0';
wait for CLK_period/2;
CLK <= '1';
wait for CLK_period/2;
   end process;
 

   -- Stimulus process
   stim_proc: process
   begin
reset <='1'; wait for 25 ns;
reset <= '0'; wait for 100 ns;
      U_D <= '1'; wait for 100 ns;
   end process;
END;


Output:


Up to 25 ns, reset signal is active and output will remain Zero. After that, till 125 ns, U_D ='0' thus the circuit is in down count mode. At 125ns U_D='1', will force the design to start up counting.


The above code is tested on Xilinx ISE Design Suite 14.7 Webpack.
It is intended only for educational purpose.

Comments

Popular posts from this blog

3-to-8 line Decoder VHDL Code (with-select-when)

4-to-1 Multiplexer (if-else Statement)

1-bit Full Adder (Dataflow & Behavioral Style)