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

ENTITY testbench_sci_spi IS
END;

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

	SIGNAL TX				:	std_logic_vector(8 DOWNTO 0) := (OTHERS => '0');
	SIGNAL ERR				:	std_logic :=	'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.sci
	
		PORT MAP	
		(
				CLK			=> SYSCLK,
				RST			=> RST,
				SCLK		=> SCLK,
				CS_N		=> CS_N,
				MOSI		=> MOSI,
				MISO		=> MISO,
				OUTPUT1		=> open,
				TX			=> TX,
				SCI_ERR		=> ERR
		);
	
	clock_process: process 
	begin
		SYSCLK <= NOT SYSCLK;
      WAIT FOR clock_period/2;
	END process;

	main_sequence: PROCESS
	BEGIN
		
		WAIT FOR 10 us;

		-- seriova linka 1, hodnota 0x55

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

		WAIT FOR 210 us;

		-- seriova linka 11 (mimo rozsah), hodnoty 0x23

		spi_master(SCLK, CS_N, MOSI, MISO, x"0b23");
		
		WAIT FOR 85 us;

		-- seriova linka 6, hodnoty 0x23

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