#include "spi.h"

void spi_select(void)
{
    CS_PORT&=~(1<<CS_BIT);
}

void spi_deselect(void)
{
    CS_PORT|=(1<<CS_BIT);
}

unsigned char spi_xchg(unsigned char val)
{
	SPDR = val;
	while (!(SPSR & (1 << SPIF))) ;
	return SPDR;
}

uint8_t spi_read(){
	return spi_xchg(0x00);
}

void spi_write(uint8_t d){
	spi_xchg(d);
}

void spi_init(){
	CS_PORT |= (1 << CS_BIT);	// pull CS pin high
	CS_DDR |= (1 << CS_BIT);	// now make it an output

	SPI_PORT |= (1 << 0);	// make sure SS is high
	SPI_DDR = (1 << PORTB2) | (1 << PORTB1) | (1 << PORTB0);	// set MOSI, SCK and SS as output, others as input
	SPCR = (1 << SPE) | (1 << MSTR);	// enable SPI, master mode 0
	SPCR |= (1 << SPR0) | (0<<SPR1); // div 128
	SPSR |= (0 << SPI2X);	// set the clock rate fck/2
}
