/*
 * SPI.cpp
 *
 * Created: 4.3.2013 18:25:08
 *  Author: Jirka
 */ 

#include <avr/io.h>
#include <stdio.h>
#include <util/delay.h>
#include "SPI.h"

#define CS_LOW (SPI_CS_PORT &= ~ _BV(SPI_CS_PIN))									//Makro pro CS=0
#define CS_HIGH (SPI_CS_PORT |= _BV(SPI_CS_PIN))									//Makro pro CS=1

#define DDR(x) (*(&x - 1))
#define PORT(x) (*(&x - 1))

void SPI_init (void)												//Inicializace SPI
{	
	DDR(SPI_CS_PORT) |= _BV(SPI_CS_PIN);
	DDR(SPI_MOSI_PORT) |= _BV(SPI_MOSI_PIN);
	DDR(SPI_MISO_PORT) &= ~_BV(SPI_MISO_PIN);
	DDR(SPI_SCK_PORT) |= _BV(SPI_SCK_PIN);
	//PORT(SPI_CS_PORT) |= _BV(SPI_CS_PIN);
	SPI_CS_PORT |= _BV(SPI_CS_PIN);
	
	SPCR |= (1<<SPE);
	SPCR |= (1<<MSTR);
	SPCR |= (1<<SPR0);
	SPCR |= (1<<SPR1);
	SPSR |= (1<<SPI2X);
	SPCR |= (1<<CPHA);				//Nastaveni hran
	SPCR |= (1<<CPOL);				//Nastaveni hran
	PRR &= ~(1<<PRSPI);
}

unsigned char SPI_f(unsigned char data)								//Funkce pro preposlani dat
{	
	SPDR = data;
	_delay_ms(1);
	while(!(SPSR & (1<<SPIF)));										//Pokud je SPIF = 0 ,pak je while(1), pokud je SPIF = 1, pak je while(0)
	return SPDR;
}

unsigned char SPI_write(unsigned char write)						//Funkce, ktera odesle data write (nezajima nas, co prijde)
{
	CS_LOW;
	_delay_us(1);
	SPI_f(write);
	CS_HIGH;
	return 0;
}

unsigned char SPI_read(void)										//Funkce, ktera prijme data read (vysle prazdny byte)
{
	unsigned char read;
	CS_LOW;
	_delay_us(1);
	read = SPI_f(0x00);												//Vysilam prikaz NOP, SPI_f vraci hodnotu SPDR do read
	CS_HIGH;
	return read;
}