--
-- VHDL Architecture FACT_FAD_lib.timer.beha
--
-- Created:
--          by - dneise.UNKNOWN (E5B-LABOR6)
--          at - 13:44:41 22.02.2011
--
-- using Mentor Graphics HDL Designer(TM) 2009.2 (Build 10)

LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
USE ieee.std_logic_unsigned.all;

ENTITY timer IS
	generic(
		TIMER_WIDTH : integer := 32;
		PRESCALER : integer := 5000		
	);
	port (
		clk : in std_logic; -- assumed to be 25MHz, if not 25MHz adjust PRESCALER
		time_o : out std_logic_vector ( TIMER_WIDTH-1 downto 0);
		synch_i : in std_logic ; 
		synched_o : out std_logic := '0';
		reset_synch_i : in std_logic;
		enable_i : in std_logic
	);
END ENTITY timer;

--
ARCHITECTURE beha OF timer IS
	signal prescale_counter : integer range 0 to PRESCALER - 1 := 0;
	
	--signal time_s : integer range 0 to 2**(TIMER_WIDTH-1);
	signal time_s : std_logic_vector ( TIMER_WIDTH-1 downto 0);
	
	signal en_sr : std_logic_vector(1 downto 0) := "00";
	signal sy_sr : std_logic_vector(1 downto 0) := "00";
	signal reset_synch_sr : std_logic_vector(1 downto 0) := "00";
	
	signal timer_proc_enabled : std_logic := '0';
	signal synched : std_logic := '0';
	
BEGIN
	--time_o <= conv_std_logic_vector(time_s, TIMER_WIDTH);
	time_o <= time_s;
	synched_o <= synched;
	
		
	main_proc: process (clk)
	begin
		if rising_edge(clk) then
			en_sr <= en_sr(0) & enable_i;
			sy_sr <= sy_sr(0) & synch_i;
			reset_synch_sr <= reset_synch_sr(0) & reset_synch_i; 
			
			if ( reset_synch_sr = "01" ) then
				synched <= '0';
			end if;
			
			if (sy_sr = "01" and synched = '0') then -- rising edge on synchronizstion_input detected AND if not already synched
				time_s <= conv_std_logic_vector(0,TIMER_WIDTH);
				prescale_counter <= 1;
				synched <= '1';
			end if;

			if (en_sr = "01") then -- rising edge on enable_input detected
				time_s <= conv_std_logic_vector(0,TIMER_WIDTH);
				prescale_counter <= 1;
				timer_proc_enabled <= '1';
			elsif (en_sr = "10") then -- falling edge on enable_input detected
				time_s <= conv_std_logic_vector(0,TIMER_WIDTH); 
				prescale_counter <= 0;
				timer_proc_enabled <= '0';
			end if;
			
			-- PRESCALER PART OF PROCESS
			if (timer_proc_enabled = '1') then
				if (prescale_counter < PRESCALER - 1) then 
					prescale_counter <= prescale_counter + 1;
				else 
					prescale_counter <= 0;
				end if;
				if (prescale_counter = PRESCALER - 1) then 
					if ( time_s < conv_std_logic_vector(2**TIMER_WIDTH-1 ,TIMER_WIDTH) ) then 
						time_s <= time_s + conv_std_logic_vector(1,TIMER_WIDTH);
					else
						time_s <= conv_std_logic_vector(0,TIMER_WIDTH);
					end if;
				end if;
			else  -- not timer_proc_enabled
				time_s <= conv_std_logic_vector(0,TIMER_WIDTH);
			end if; -- if timer_proc_enabled		
		end if; -- rising_edge(clk)
	end process main_proc;
END ARCHITECTURE beha;

