#include "software_SPI.h"

void sSPI_init(){
	DDRC |= (1<<DDRC0)|(1<<DDRC1);
	PORTC = 0;

	DDRD |= (1<<DDRD2)|(1<<DDRD3)|(1<<DDRD4);		//set CSx pins on out
	PORTD |= (1<<PORTD2)|(1<<PORTD3)|(1<<PORTD4);	//set CSx pins HIGH
}

void sSPI_select(uint8_t ch){
	if (ch > 3/*Max channel count*/) return;	
	
	sSPI_free();		
	
	if (ch == 3)
		PORTD &= (~(0b111<<(PORTD2)));
	else
		PORTD &= (~(1<<(PORTD2+ch)));
}

inline void sSPI_free(){
	PORTD |= (1<<PORTD2)|(1<<PORTD3)|(1<<PORTD4);	//set CSx pins HIGH
}

void sSPI_write_byte(uint8_t byte){
	for (uint8_t i = 8; i > 0; i--){
		if ( (byte>>(i-1)) & 1 )
			MOSI_Hi;
		else 
			MOSI_Lo;
		
		_delay_us(delay);

		CLK_invert;
		
		_delay_us(delay);
		
		CLK_invert;
	}	
}

uint8_t sSPI_read_byte(){
	uint8_t rx = 0;
	
	for (uint8_t i = 8; i > 0; i--){
		CLK_invert;
		
		_delay_us(delay);
		
		rx |= ((PINC >> PORTC2)&1)<<(i-1);

		CLK_invert;

		_delay_us(delay);
	}	

	return rx;
}
