#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#include <util/delay.h>
#include <string.h>
#include <stdio.h>

#define BAUD 9600
#define UBRR F_CPU/16/BAUD-1
#define CMD_READ_DATA_FROM_SLAVE1	0x55
#define CMD_READ_DATA_FROM_SLAVE2	0xAA

uint8_t dataWrite[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
uint8_t dataRead;
volatile uint8_t	i_spi;

//SS0	PORTB2
//MOSI	PORTB3
//MISO	PORTB4
//SCK	PORTB5
//--------------------------------------------------------------------
//Inicializacia serial port
void USART_Init (unsigned int ubrr)	
{
	// set baud rate
	UBRR0H = (unsigned char)(ubrr>>8);
	UBRR0L = (unsigned char)ubrr;
	// Enable receiver and transmitter;
	UCSR0B |= (1 << RXEN0) | (1 << TXEN0);
	//Set Frame format: 8data 1stop
	//UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00); 
}
//---------------------------------------------------------------------
void USART_Transmit (char dataout) 
{
	while( !(UCSR0A & (1 << UDRE0)) );
	UDR0 = dataout;
}
//------------------------------------------------------------------------------
void USART_Transmit_text(char *text) {
	unsigned char j;
	for (j=0; j<strlen(text); j++) USART_Transmit (text[j]);
}
//-------------------------------------------------------------------------------------------
void USART_buffer_out(uint8_t *txBuffer, uint16_t buflength)
{
	char	x[3];
	
	for (uint16_t i=0; i<buflength; i++) {
		sprintf (x, "%02X ", txBuffer[i]);
		USART_Transmit_text (x);
	}
	USART_Transmit_text ("\r");
}
//---------------------------------------------------------------------
void SPI_SlaveInit()
{
	// MISO output pin
	DDRB |= (1 << DDB4);
	// SPI Interrupt Enable, SPI Enable, Slave mode
	SPCR = (1 << SPIE) | (1 << SPE);
}
//---------------------------------------------------------------------
ISR (SPI_STC_vect)
{
	if (i_spi == 0)	dataRead = SPDR;			//Slave receive command
	
	if (dataRead == CMD_READ_DATA_FROM_SLAVE1) {
		SPDR = dataWrite[i_spi++];
		if (i_spi == 11) {i_spi = 0; dataRead = 0;}
	}
	if (dataRead == CMD_READ_DATA_FROM_SLAVE2) {
		SPDR = 0xB0 + i_spi++;
		if (i_spi == 6) {i_spi = 0; dataRead = 0;}
	}
}
//------------------------------------------------------------------------------
int main (void) {

	USART_Init (UBRR);			//inicializacia UART
	SPI_SlaveInit ();			//inicializacia SPI
	sei();						//Enable Global Interrupt	
	
	USART_Transmit_text("\n\rSpi Data Transfer: SPI_slave_a.c\n\r");
	i_spi = 0;
				
	while(1) { 	
	}
}
//------------------------------------------------------------------------------

