/*
* spi_receive_02.c
* SPI-Slave - Daten am MOSI per Interrupt Anforderung empfangen und am PORTD ausgeben
* Controller: ATmega88 @ 8MHz
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

void SPI_Slave_Init(void)
{
	SPCR &= ~(1<<MSTR);				// Controller = Slave
	SPCR &= ~(1<<CPOL);				// CLK positiv phase
	SPCR |= (1<<CPHA);				// Sampling data @ rising edge
	SPCR |= ((1<<SPE)|(1<<SPIE));	// Enable SPI && interrupt enable bit
	DDRB |= (1<<PB4);				// Set MISO output
	DDRB &= ~(1<<PB3);				// Set MOSI input
	DDRB &= ~(1<<PB5);				// Set SCK input
	DDRB &= ~(1<<PB2);				// Set SS input
}

uint8_t SPI_Slave_Receive(void)
{
	while (!(SPSR & (1<<SPIF)));	// Wait for transmission complete
	return SPDR;					// return spi data register
}

int main(void)
{
	DDRD = 0xFF;
	SPI_Slave_Init();				// Init SPI Interface as Slave
	
	sei();							// enable Interrupts
	
	while(1)
	{
	}
}

/**** Interrupt Service Routine (SPI serial transfer complete) ****/
ISR(SPI_STC_vect)
{
	PORTD = SPI_Slave_Receive();	// Daten abholen und am PORTD ausgeben
}