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;

-- Format přenosu: [AB][start bit][stop bit][slovo][start bit][stop bit][slovo negovane][stop bit][start bit][AB][stop bit]
entity rf is
	Generic (
				 prfx : std_logic_vector(7 downto 0) := x"AB" -- AB kontrolni slovo								
				 ); 

	 Port ( rx_out : out std_logic_vector(7 downto 0);
			  data_ready : out  STD_LOGIC;
           rx_data,rx_16clk : in  STD_LOGIC);

end rf;

architecture Behavioral of rf is
signal regrx : std_logic_vector(39 downto 0) := (others => '0');
signal rx_clk : std_logic;  

signal rxd1 : std_logic ;
signal rxd2 : std_logic ;
signal clkdiv :  std_logic_vector (3 downto 0) := "0111" ;
signal edge : std_logic := '0' ;
begin
data_ready <= rx_clk ; --nutne, nechyta se na jednu hranu
rx_clk <= clkdiv(3) ;

process (rx_16clk,rxd1,rxd2)
begin
if rx_16clk'event and rx_16clk = '1' then
	if rxd1 /= rxd2 then			-- detekce hrany, vzorky odebirany v case 1/rx_16clk
		edge <= '1';
	else
		edge <= '0';
	end if ;
end if ;
end process  ;

process (rx_16clk,edge)
begin
if rx_16clk'event and rx_16clk = '1' then
	rxd1 <= rx_data ;
	rxd2 <= rxd1 ;
	clkdiv <= clkdiv + "0001" ;
	if edge = '1' then
		clkdiv <= "0011" ;
	end if ;
end if ;
end process ;

---- prijimac
process (rx_clk,rx_data,regrx) begin
if rx_clk'event and rx_clk='1' then
	regrx <= (rx_data & regrx(39 downto 1));
	if regrx(8 downto 1) = prfx and regrx(10 downto 9)="01" and  -- zkontroluje prefix a stop,start bity
	   regrx(20 downto 19)="01" and regrx(30 downto 29)="01" and regrx(0)='0' and regrx(39)='1' and regrx(38 downto 31) = prfx  then
		
--		regrx(18 downto 11);	--prima data
--		regrx(28 downto 21);	--negovana data
		if regrx(18 downto 11) = not regrx(28 downto 21) then
			rx_out <= regrx(18 downto 11);	--na vystup zapise prima data

		end if;
	end if;
end if;
end process;

end Behavioral;

