----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;      
use IEEE.STD_LOGIC_ARITH.ALL;     
use IEEE.STD_LOGIC_UNSIGNED.ALL;
----------------------------------------------------------------------------------
entity SPI_core is
  Port (
    
    CLK48 : in  STD_LOGIC;                    --Interface Clock
	 
    data : in  STD_LOGIC_VECTOR(7 downto 0);
	 
	 wr_en : in  STD_LOGIC; -- write data now
	  
    MOSI : out STD_LOGIC := '0';
	 SPI_SCK	: out STD_LOGIC := '0'
	 
  );
end SPI_core;
----------------------------------------------------------------------------------
architecture rtl of SPI_core is
  

signal temp : std_logic_vector(7 downto 0) := X"81"; -- the data wich is rotated

signal SPI_clk_en : std_logic := '0';

signal wr_en_flag :  STD_LOGIC := '0'; -- to detect wr_en  becose it is 48MHz fast

signal clk_div_cntr : std_logic_vector(1 downto 0) := "00"; -- to generate 12MHz
signal SPI_state_cntr : std_logic_vector(3 downto 0) := "1111";

----------------------------------------------------------------------------------
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	<= clk_div_cntr(1) and SPI_clk_en;
		
		
		
		
		if ((wr_en_flag = '0') and (SPI_state_cntr = "1111")) then -- making 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 = "00") then -- 4x divider
					 
			if (wr_en_flag = '1') then -- if rising edge of send_now
				SPI_state_cntr <= "0000"; -- startst the sending by nulling this cntr
				wr_en_flag <= '0';
				temp <= data;
		
				
			elsif SPI_state_cntr < "1001" then -- else if it is the end of counting
				SPI_state_cntr <= SPI_state_cntr + 1;
			end if;
			
			
			
			
			if ((SPI_state_cntr >= "0000") and (SPI_state_cntr <= "0111")) then --sending data by shifting
			 
			 temp <= temp(6 downto 0) & temp(7);
			
			 MOSI <= temp(7);
			 SPI_clk_en	<= '1';
			end if;
			
			if (SPI_state_cntr = "1000") then
			 MOSI <= '0';
			 SPI_clk_en	<= '0';
			end if;
			
			if (SPI_state_cntr = "1001") then 
			 
				MOSI <= '0';
				SPI_clk_en	<= '0';
			
				SPI_state_cntr <= "1111";
			end if;
	
		end if;
    end if;
  end process;
end rtl;