--------------------------------------------------------------------------------
-- Company: 
-- Engineer:
--
-- Create Date:    19:34:24 10/23/05
-- Design Name:    
-- Module Name:    debounce - Behavioral
-- Project Name:   
-- Target Device:  
-- Tool versions:  
-- Description:
--
-- Dependencies:
-- 
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
-- 
-----------------------------------------------------------------------
-- $Header: D:\usr\cvsroot/VHDL/lib/misc/debounce.vhd,v 1.1 2008/08/23 08:20:29 Jens Exp $
-----------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity debounce is
    Generic ( ncyc_latency : integer := 100);
    Port ( rst : in std_logic;
           clk : in std_logic;
           input : in std_logic;
           output : out std_logic);
end debounce;

architecture Behavioral of debounce is

type debounce_state_t is (init_st, wait_st, rel_st);
signal debounce_cs : debounce_state_t;
signal debounce_ns : debounce_state_t;
signal count       : integer range 0 to ncyc_latency;
signal input_last	 : std_logic;

begin

	debounce_clk: process(rst, clk, debounce_ns, debounce_cs, input)
	begin
		if (rst = '1') then
			count <= 0;
			output <= input;
			input_last <= input;
		else
			if rising_edge(clk) then
				debounce_cs <= debounce_ns;
				if (debounce_cs = wait_st) then
					if (count /= 0) then
						count <= count - 1;
					end if;
				else
					count <= ncyc_latency;
					if	(debounce_cs = rel_st) then
						output <= input;
						input_last <= input;
					end if;
				end if;
			end if;
		end if;
	end process;

	debounce_in: process(rst, clk, input, input_last, debounce_cs, count)
	begin
		debounce_ns <= debounce_cs;
		case debounce_cs is
			when init_st =>
				if (input /= input_last) then
					debounce_ns <= wait_st;
				end if;
			when wait_st =>
				if (count = 0) then
					debounce_ns <= rel_st;
				end if;
			when others => 
				debounce_ns <= init_st;
		end case;
	end process;

end Behavioral;
