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

LIBRARY WORK;
USE WORK.uart_types.all;

------------------------------------------------------------------------------------
ENTITY uart IS
	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_data_present	: 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;

signal data_out			: std_logic_vector(7 downto 0);
begin

dout 	<= unsigned(data_out);

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 
	port map
	(
		data_in				=> std_logic_vector(din), 
		write_buffer		=> we,
		reset_buffer		=> rst,
		en_16_x_baud		=> en_16_x_baud,
		serial_out			=> ser_tx,
		buffer_full			=> tx_full,
		buffer_half_full	=> tx_half_full,
		tx_complete			=> tx_complete,
		tx_empty			=> tx_empty,
		clk					=> clk
	);
	
inst_uart_rx: entity work.uart_rx
	port map
	(
		serial_in			=> ser_rx,
		data_out				=> data_out,
		read_buffer			=> re,
		reset_buffer		=> rst,
		en_16_x_baud		=> en_16_x_baud,
		buffer_data_present => rx_data_present,
		buffer_full			=> rx_full,
		buffer_half_full	=> rx_half_full,
		clk					=> clk
	);  

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

end rtl;

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


