----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    13:42:35 01/08/2010 
-- Design Name: 
-- Module Name:    debouncer - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
-- hds interface_start
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;

-- -- Uncomment the following library declaration if instantiating
-- -- any Xilinx primitives in this code.
-- library UNISIM;
-- use UNISIM.VComponents.all;
-- 
ENTITY debouncer IS
   GENERIC( 
      WIDTH : INTEGER := 17
   );
   PORT( 
      clk         : IN     STD_LOGIC;
      --           rst : in  STD_LOGIC;
      trigger_in  : IN     STD_LOGIC;
      trigger_out : OUT    STD_LOGIC  := '0'
   );

-- Declarations

END debouncer ;
-- hds interface_end

architecture Behavioral of debouncer is
  
  signal counter : STD_LOGIC_VECTOR(WIDTH-1 downto 0) := (others => '0');
  signal int_trigger : std_logic := '0';
  signal temp_trig : std_logic_vector(1 downto 0) := "00";
  signal trigger_flag : std_logic := '0';
  signal temp_signal : std_logic := '0';
  
begin

  debounce_proc: process (clk) 
  begin
--		if (rst = '1') then
--			counter <= (others => '0');
--			trigger_out <= '0';
--		elsif rising_edge(clk) then
    if rising_edge(clk) then
      if (trigger_in = '1') then
        if (unsigned(counter) = 2**WIDTH-1) then
          int_trigger <= '1';
          counter <= (others => '1');
        else
          counter <= std_logic_vector(unsigned(counter) + to_unsigned(1,WIDTH));
        end if;
      else
        if (unsigned(counter) = 0) then
          int_trigger <= '0';
          counter <= (others => '0');
        else
          counter <= std_logic_vector(unsigned(counter) - to_unsigned(1,WIDTH));
        end if;
      end if;
    end if;
  end process debounce_proc;
  
  shaping_proc : process (clk)
  begin
--    if (rst = '1') then
--      trigger_out <= '0';
--      trigger_flag <= '0';
--      temp_signal <= '0';
--    elsif rising_edge(clk) then
    if rising_edge(clk) then
--      temp_trig <= temp_trig(2 downto 0) & trigger_in;
--      trigger_out <= not temp_trig(3) and temp_trig(2);
      temp_trig <= temp_trig(0) & int_trigger;
      temp_signal <= not temp_trig(1) and temp_trig(0);
      trigger_out <= temp_signal and not trigger_flag;
      if (int_trigger = '0') then
        trigger_flag <= '0';
      end if;
      if (temp_signal = '1') then
        trigger_flag <= '1';        
      end if;
    end if;
  end process shaping_proc;


end Behavioral;


