LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;

LIBRARY WORK;
USE WORK.uart_types.all;

------------------------------------------------------------------------------------
ENTITY uart IS
	Generic 
	(
		fifo_depth_bits	: integer := 4
	);
	Port
	(
		clk			: in  STD_LOGIC;
		rst			: in  STD_LOGIC;
		we			: in  STD_LOGIC;
		re			: in  STD_LOGIC;
		din			: in  unsigned(7 downto 0);
		dout		: out unsigned(7 downto 0);
		ser_rx		: in  std_logic;
		ser_tx		: out std_logic;
		ctrl		: in  ctrl_t;
		status		: out status_t
	);
END uart;

ARCHITECTURE rtl OF uart IS

signal baud_count		: unsigned(15 downto 0);
signal en_16_x_baud		: std_logic;

signal rx_dout_vld		: std_logic;
signal rx_full			: std_logic;
signal rx_half_full		: std_logic;

signal tx_complete		: std_logic;
signal tx_empty			: std_logic;
signal tx_full			: std_logic;
signal tx_half_full		: std_logic;

begin

baud_timer:
process(clk)
begin
	if rising_edge(clk) then
		en_16_x_baud <= '0';
		if rst = '1' then
			baud_count <= (others => '0');
		elsif baud_count = ctrl.baudrate then
			baud_count <= (others => '0');
			en_16_x_baud <= '1';
		else
			baud_count <= baud_count + 1;
		end if;
	end if;
end process;

inst_uart_tx : entity work.uart_tx
	GENERIC MAP 
	(
		fifo_depth_bits	=> fifo_depth_bits
	)
	PORT MAP
	(
		rst					=> rst,
		clk					=> clk,
		we					=> we,
		din					=> din,
		en_16_x_baud		=> en_16_x_baud,
		full				=> tx_full,
		half_full			=> tx_half_full,
		tx_complete			=> tx_complete,
		tx_empty			=> tx_empty,
		ser_out				=> ser_tx
	);

inst_uart_rx : entity work.uart_rx
	GENERIC MAP 
	(
		fifo_depth_bits	=> fifo_depth_bits
	)
	PORT MAP
	(
		rst					=> rst,
		clk					=> clk,
		en_16_x_baud		=> en_16_x_baud,
		dout_vld			=> rx_dout_vld,
		dout				=> dout,
		re					=> re,
		full				=> rx_full,
		half_full			=> rx_half_full,
		ser_in				=> ser_rx
	);

-- Status
status.rx_present		<= rx_dout_vld;
status.tx_complete		<= tx_complete;
status.tx_empty			<= tx_empty;
status.tx_full			<= tx_full;

end rtl;

------------------------------------------------------------------------------------
--
-- END OF FILE UART_RX.VHD
--
------------------------------------------------------------------------------------


