----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    14:29:03 10/08/2015 
-- Design Name: 
-- Module Name:    ppsclock_sync - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Revision 0.02 - add FSM to start clock divider on first PPS
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
library UNISIM;
use UNISIM.VComponents.all;
use IEEE.NUMERIC_STD.ALL;


entity  ppsclock_sync is
    Port ( clk_i : in  STD_LOGIC;		--200MHz
           rst_i : in  STD_LOGIC;
			  pps_i : in  STD_LOGIC;
           clk_o : out  STD_LOGIC
			  );
end  ppsclock_sync;

architecture Behavioral of  ppsclock_sync is

	signal clk_div : STD_LOGIC := '0';
	signal cnt :  integer range 15 downto 0 := 1;
	type STATE_TYPE is (IDLE, CLK_GEN);
	signal current_state : STATE_TYPE;
	
begin

	clk_o <= clk_div;

 process (clk_i)
	begin
	if rising_edge(clk_i)then
		if (rst_i = '1') then
			cnt 		<= 1;
			clk_div  <= '0';
			current_state	<= IDLE;	

		else
			case current_state is
				
			when IDLE =>							
				if pps_i = '1' then				-- first PPS received to start clock divider
					clk_div  <= '1';
					cnt 		<= 1 ;
					current_state	<= CLK_GEN;		
				else
					cnt 		<= 1;
					clk_div  <= '0';
				end if;
				
				when CLK_GEN =>
					if (cnt = 10) then    		--10MHz @200MHz
						clk_div  <= not clk_div;
						cnt  		<= 1;
					else 
						cnt 		<= cnt + 1; 
						clk_div  <= clk_div;
					end if;			
						
				when others => 
					current_state	<=	IDLE;			
			end case;
		 end if; 
	end if;
	end process;

end Behavioral;

