library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;


entity Debouncer is
port(
		clk : in std_logic;
		reset_n : in std_logic := '1';
		a_in : in std_logic;
		a_out : out std_logic
);
end entity;

architecture Debouncer of Debouncer is

	constant CNT_MAX: unsigned(23 downto 0) := x"989680";--24d"10000000";
	constant LOW_LEVEL : unsigned(23 downto 0) := x"0F4240"; --24d"1000000";
	constant HI_LEVEL : unsigned(23 downto 0) := x"895440"; --24d"9000000";

	signal cnt : unsigned(23 downto 0) := (others => '0');

begin

	process(clk, reset_n)
	begin
		if(reset_n = '0')then
			cnt <= (others => '0');
		elsif rising_edge(clk) then
			if(a_in = '1')then
				if(cnt < CNT_MAX)then
					cnt <= cnt + x"000001";
				end if;
			else
				if(cnt > x"000000")then
					cnt <= cnt - x"000001";
				end if;
			end if;
		end if;	
	end process;

	
		process(clk, reset_n)
	begin
		if(reset_n = '0')then
			a_out <= '0';
		elsif rising_edge(clk) then
			if(cnt < LOW_LEVEL)then
				a_out <= '0';
			elsif(cnt > HI_LEVEL)then
				a_out <= '1';
			end if;
		end if;	
	end process;


end architecture;

