LIBRARY ieee;
USE ieee.std_logic_1164. all;
USE ieee.numeric_std.all;

ENTITY testbench_spi IS
END;

ARCHITECTURE Behavioral OF testbench_spi IS
	
	CONSTANT clock_period	: delay_length 	:= 20 ns;	-- 1/50MHz
	SIGNAL 	SYSCLK			:	std_logic	:=	'0';
	
	SIGNAL RST				:	std_logic :=	'0';

	SIGNAL SCLK				:	std_logic :=	'0';
	SIGNAL CS_N				:	std_logic :=	'0';
	SIGNAL MOSI				:	std_logic :=	'0';
	SIGNAL MISO				:	std_logic :=	'0';
	
	SIGNAL DIN				:	std_logic_vector(15 DOWNTO 0);
	SIGNAL DOUT				:	std_logic_vector(15 DOWNTO 0);

	SIGNAL DATA_TRANS		:	std_logic_vector(15 DOWNTO 0);
	
BEGIN

	dut: ENTITY	work.spi_slave  
	GENERIC MAP 
	(
		BYTES => 2
	)
	PORT MAP	
	(
		CLK => SYSCLK,
		RST => RST,
		SCLK => SCLK,
		CS_N => CS_N,
		MOSI => MOSI,
		MISO => MISO,
		DIN => x"abcd",
		DOUT => DOUT
	);
	
	clock_process: process 
	begin
		SYSCLK <= NOT SYSCLK;
      WAIT FOR clock_period/2;
	END process;

	main_sequence: PROCESS
	BEGIN

		-----------------------------------------------
		-- test spravne komunikace
		-----------------------------------------------	

		WAIT FOR 1 us;	-- power up and wait for 100 us
		CS_N <= '1';
		SCLK <= '0';
		MOSI <= '1';

		-- data pro vysilani
		DATA_TRANS <= x"aaaa";

		WAIT FOR 10 us;	

		CS_N <= '0';
		MOSI <= '0';
		WAIT FOR 1 us;

		-- CS do log. 0, zacatek komunikace
		
		FOR i IN 0 TO 15 LOOP

			MOSI <= DATA_TRANS(i);	
			
			SCLK <= '1';		
			WAIT FOR 1 us;
			SCLK <= '0';
			WAIT FOR 1 us;
			
		END LOOP;

		-- CS high, end transmission
		CS_N <= '1';
		MOSI <= '1';
		
		WAIT FOR 10 us;

		CS_N <= '1';
		SCLK <= '0';
		MOSI <= '1';

		-----------------------------------------------
		-- test chybove komunikace
		-----------------------------------------------
		
		WAIT FOR 10 us;	
		
		-- data pro vysilani
		DATA_TRANS <= x"1234";	
		
		-- CS do log. 0, zacatek komunikace
		CS_N <= '0';	
		
		WAIT FOR 1 us;
		
		FOR i IN 0 TO 15 LOOP
			
			MOSI <= DATA_TRANS(i);	
			
			SCLK <= '1';		
			WAIT FOR 1 us;
			SCLK <= '0';
			WAIT FOR 1 us;
			
		END LOOP;

		-- generovani chyboveho SCLK signalu
		FOR i IN 0 TO 2 LOOP
		
			WAIT FOR 1 us;
			SCLK <= '1';		
			WAIT FOR 1 us;
			SCLK <= '0';
			WAIT FOR 1 us;

		END LOOP;

		CS_N <= '1';
		SCLK <= '0';
		MOSI <= '1';
		
		WAIT;
	
	END PROCESS;	
END Behavioral;