library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

--tim_bits = (log(time)/log(2)) +1

entity owread is
          generic (time_5:  integer:=5;  tim_bits_5:  integer:=3;
                   time_7:  integer:=7;  tim_bits_7:  integer:=3;
                   time_85: integer:=106;tim_bits_85: integer:=7); --byte
	  port (
	  clk, ck_slow, start_1, start_8: in std_logic; --byte
	  read, read_read: out std_logic);
end owread ;

architecture arch of owread is

signal rdpls, rdpls_reset: std_logic;
signal rd, rd_reset: std_logic;
signal start, start_bit, r3, r3_reset, r3_reset_dly, r3_pulse, rst_8: std_logic; --byte
signal count_8: std_logic_vector(3 downto 0); --byte

component mono  
	generic(time, tim_bits: integer);
	port (clk, enable: in std_logic;
	end_count: out std_logic);
end component;

begin

--byte section--
--start
process (clk)
begin
	if clk'event and clk='1' then
	  if start_1='1' or start_bit='1' then
	    start <= '1';
	  else
	    start <= '0';
	  end if;
	end if;
end process;
--one byte = eight bits
process (clk)
begin
	if clk'event and clk='1' then
	  rst_8 <= count_8(3);
	end if;
end process;

process (clk, rst_8)
begin
	if rst_8='1' then
	  count_8 <= (others => '0');
	elsif clk'event and clk='1' then
	  if start_8='1' then
	    count_8 <= count_8 + '1';
	    start_bit <= '1';
	  elsif r3_pulse='1' and count_8 /= "0000" then
	    count_8 <= count_8 + '1';
	    start_bit <= '1';
	  else 
	    start_bit <= '0';
	  end if;
	end if;
end process;

--timer 60 us (8 bits)
M3: mono generic map(time_85, tim_bits_85)
	 port map(ck_slow, r3, r3_reset);
r3_pulse <= not r3_reset and r3_reset_dly;
process (clk)
begin
	if clk'event and clk='1' then
	  r3_reset_dly <= r3_reset;
	end if;
end process;

process (clk, r3_reset)
begin
	if r3_reset='1' then
	  r3 <= '0';
	elsif clk'event and clk='1' then
	  if start_bit='1' then
	    r3 <= '1';
	  end if;
	end if;
end process;
--end byte section--

read <= rdpls;
read_read <= rd_reset;

-- retardo 5 us (read pulse)
M1: mono generic map(time_5, tim_bits_5) 
	 port map(ck_slow, rdpls, rdpls_reset);

process (clk, rdpls_reset)
begin
	if rdpls_reset='1' then
	  rdpls <= '0';
	elsif clk'event and clk='1' then
	  if start='1' then
	    rdpls <= '1';
	  end if;
	end if;
end process;

--retardo 7 us (read read)
M2: mono generic map(time_7, tim_bits_7)
	 port map(ck_slow, rd, rd_reset);

process (clk, rd_reset)
begin
	if rd_reset='1' then
	  rd <= '0';
	elsif clk'event and clk='1' then
	  if rdpls_reset='1' then
	    rd <= '1';
	  end if;
	end if;
end process;

end arch;
	
