----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;      
use IEEE.STD_LOGIC_ARITH.ALL;     
use IEEE.STD_LOGIC_UNSIGNED.ALL;
----------------------------------------------------------------------------------
entity SPI_transmitter3B is
  Port (
    
    CLK48 : in  STD_LOGIC;                    --Interface Clock
	 
    data : in  STD_LOGIC_VECTOR(15 downto 0); 
	 wr_en : in  STD_LOGIC; 

	 CS : out  STD_LOGIC := '1'; -- 1 busy 0 free AKA negated chip select
    MOSI : out STD_LOGIC := '0';
	 SPI_SCK	: out STD_LOGIC := '0'
	 
  );
end SPI_transmitter3B;
----------------------------------------------------------------------------------
architecture rtl of SPI_transmitter3B is
 

signal temp : std_logic_vector(15 downto 0) := X"0000";

signal SPI_clk_en : std_logic := '0';

signal wr_en_flag :  STD_LOGIC := '0';

signal clk_div_cntr : std_logic_vector(3 downto 0) := "0000";
signal SPI_state_cntr : std_logic_vector(4 downto 0) := "11111";

----------------------------------------------------------------------------------
begin
 
process(CLK48)
begin
    if(rising_edge(CLK48)) then
  
      clk_div_cntr <= clk_div_cntr + 1; -- dividing CLK by 4 gives 12MHz main SPI clk
		
		SPI_SCK	<= not(clk_div_cntr(3) and SPI_clk_en);
		
		
		if ((wr_en_flag = '0') and (SPI_state_cntr = "11111")) then -- making send now flag hi for time by it is checked
			wr_en_flag <= wr_en;											   	-- necessary becouse the SPI is 4x slower, and send now will be too fast 
		end if;



		if(clk_div_cntr = "0000") then -- for every 16 tics of clk48
		
	
			if (wr_en_flag = '1') then -- if rising edge of send_now
				SPI_state_cntr <= "00000"; -- startst the sending by nulling this cntr
				temp <= data; -- load data
				wr_en_flag <= '0';
				
			elsif SPI_state_cntr < "10011" then -- else if it is the end of counting
				SPI_state_cntr <= SPI_state_cntr + 1;
			end if;
			
			
			if (SPI_state_cntr = "0000") then
			 CS <= '0';
			end if;
			
			
			if ((SPI_state_cntr >= "00001") and (SPI_state_cntr <= "10000")) then
			 
			 temp <= temp(14 downto 0) & temp(15);
			 CS <= '0';
			 MOSI <= temp(15);
			 SPI_clk_en	<= '1';
			end if;
			
			if (SPI_state_cntr = "10001") then
			 MOSI <= '0';
			 SPI_clk_en	<= '0';
			end if;
			
			if (SPI_state_cntr = "10010") then
			 CS <= '1';
			end if;
			
			if (SPI_state_cntr = "10011") then --wait 1 dummy clk to distingwish the transfers from each other
				MOSI <= '0';
				SPI_clk_en	<= '0';
				SPI_state_cntr <= "11111";
			end if;
		 
		end if;

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

end rtl;