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

ENTITY testbench_spi_parser IS
END;

ARCHITECTURE Behavioral OF testbench_spi_parser 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 DATA_TRANS		:	std_logic_vector(15 DOWNTO 0) := (OTHERS => '0');

	SIGNAL EPWM_add			:	std_logic_vector(7 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWM_reg			:	std_logic_vector(7 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWM_val			:	std_logic_vector(15 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWM_vld			:	std_logic :=	'0';
	
BEGIN

	dut: ENTITY	work.spi_parser  
	PORT MAP	
	(
		CLK => SYSCLK,
		RST => RST,
		SCLK => SCLK,
		CS_N => CS_N,
		MOSI => MOSI,
		MISO => MISO,
		EPWM_add => EPWM_add,
		EPWM_reg => EPWM_reg,
		EPWM_val => EPWM_val,
		EPWM_vld => EPWM_vld,
		EPWM_dat => x"abcd"
	);
	
	clock_process: process 
	begin
		SYSCLK <= NOT SYSCLK;
      WAIT FOR clock_period/2;
	END process;

	main_sequence: PROCESS
	BEGIN

		--
		-- test spravneho parsovani dat urcenych pro zapis, nutno prijmout 4 byty ve stanoveny cas, rozliseno pomoci R/W bitu
		--

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

		-- data pro vysilani
		DATA_TRANS <= x"0101"; -- B 00000001_DEV		0_RW	0000001_REG

		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(15-i);	
			
			SCLK <= '1';		
			WAIT FOR 1 us;
			SCLK <= '0';
			WAIT FOR 1 us;
			
		END LOOP;
		
		CS_N <= '1';
		SCLK <= '0';
		MOSI <= '1';
		
		WAIT FOR 2 us;

		DATA_TRANS <= x"1234"; -- B 0001001000110100_DATA

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

		FOR i IN 0 TO 15 LOOP

			MOSI <= DATA_TRANS(15-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';
		
		WAIT FOR 2 us;

		--
		-- test spravneho parsovani dat urcenych pro cteni, nutno prijmout 2 byty, rozliseno pomoci R/W bitu
		--

		DATA_TRANS <= x"0181"; --B 00000001_DEV		1_RW	0000001_REG

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

		FOR i IN 0 TO 15 LOOP

			MOSI <= DATA_TRANS(15-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';

		WAIT;
	
	END PROCESS;	
END Behavioral;