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

ENTITY testbench_spi_epwm IS
END;

ARCHITECTURE Behavioral OF testbench_spi_epwm 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 :=	'1';
	SIGNAL MOSI				:	std_logic :=	'1';
	SIGNAL MISO				:	std_logic :=	'1';

	SIGNAL TZ				:	std_logic_vector(5 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWMXA			:	std_logic_vector(1 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWMXB			:	std_logic_vector(1 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWMxSOCA		:	std_logic_vector(1 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWMxSOCB		:	std_logic_vector(1 DOWNTO 0) := (OTHERS => '0');
	SIGNAL EPWMxINTn		:	std_logic_vector(1 DOWNTO 0) := (OTHERS => '0');

	PROCEDURE spi_master 
	(	
		SIGNAL SCLK 	: 	OUT std_logic; 
		SIGNAL CS_N 	: 	OUT std_logic; 
		SIGNAL MOSI 	: 	OUT std_logic;
		SIGNAL MISO		:	IN std_logic;
		CONSTANT DIN	:	IN std_logic_vector(15 DOWNTO 0)
	) 
	IS BEGIN

		CS_N <= '0';
		MOSI <= '0';

		WAIT FOR 1 us;

		FOR i IN 0 TO 15 LOOP

			MOSI <= DIN(15-i);	

			SCLK <= '1';		
			WAIT FOR 1 us;
			SCLK <= '0';
			WAIT FOR 1 us;
		
		END LOOP;

		CS_N <= '1';
		MOSI <= '1';

	END PROCEDURE;		
	
BEGIN

	dut: ENTITY	work.epwm_spi 
	GENERIC MAP
	(
		COUNT => 2
	)
	
	PORT MAP	
	(
		CLK => SYSCLK,
		RST => RST,
		SCLK => SCLK,
		CS_N => CS_N,
		MOSI => MOSI,
		MISO => MISO,
		TZ => TZ,
		EPWMXA => EPWMXA,
		EPWMXB => EPWMXB,
		EPWMxSOCA => EPWMxSOCA,
		EPWMxSOCB => EPWMxSOCB,
		EPWMxINTn => EPWMxINTn
	);
	
	clock_process: process 
	begin
		SYSCLK <= NOT SYSCLK;
      WAIT FOR clock_period/2;
	END process;

	main_sequence: PROCESS
	BEGIN
		
		WAIT FOR 10 us;

		-- zapis do periferie 0, registru 1

		spi_master(SCLK, CS_N, MOSI, MISO, x"0001");

		WAIT FOR 1 us;

		-- zapis hodnoty x"1234"

		spi_master(SCLK, CS_N, MOSI, MISO, x"1234");

		WAIT FOR 5 us;

		-- cteni z periferie 0, registru 1,

		spi_master(SCLK, CS_N, MOSI, MISO, x"0081");

		WAIT FOR 1 us;

		-- cteni hodnoty x"1234"

		spi_master(SCLK, CS_N, MOSI, MISO, x"1234");
		
		WAIT;
	
	END PROCESS;	
END Behavioral;