/*
 * BP_SPI.h
 *
 *  Created on: 30. 10. 2016
 *      Author:
 */

#ifndef BP_SPI_H_
#define BP_SPI_H_

#include <avr/io.h>
#include <stdint.h>

void SPI_init(void);
uint8_t SPI_send(uint8_t SPI_data);

void SPI_init() {
	SPI_Data_Dir |= ((1<<SPI_MOSI) | (1<<SPI_SCK) | (1<<SPI_SS) | (1<<SPI_LDAC));	//MOSI, SCK, SS, LDAC as outputs
	SPI_Data_Dir &= ~(1<<SPI_MISO);									//MISO as input
	SPI_Port |= (1<<SPI_SS);										//Set SS to 1 (inactive)

	//SPIE=0 - SPI interrupt disable, SPE=1 - SPI enable, DORD=0 - MSB first, MSTR=1 - Set SPI as master
	//CPOL=0, CPHA=0 - SPI mode 0, SPR1=0, SPR0=0, SPI2X=1 - fosc/2
	SPCR = ((1<<SPE) | (1<<MSTR));
	SPSR |= 1<<SPI2X;
}

uint8_t SPI_send(uint8_t SPI_data) {
	SPDR = SPI_data;
	while((SPSR & (1<<SPIF)) == 0);	//Wait until SPI interrupt flag is 1

	return SPDR;
}


#endif /* BP_SPI_H_ */

