#include <io.h>
#include "spi.h"

#include <util/delay.h>
#define delay_microsec _delay_us

void spiInit()
{
	uint8 Mask;

	#if 1

	// Port F, SPI in/out:
	
	// SPI output pins
	Mask =  (1 << SO_OUTPUT_ENABLE) |
			(1 << SO_DATA)          |
			(1 << SO_CLOCK)         |
			(1 << SO_INPUT_ENABLE);

	DDRF  = Mask; // '1' output, '0' input
	PORTF = Mask; // '1' pull up resistor on

	// Set defaults for output
	SET_PIN(F, SO_OUTPUT_ENABLE);
	SET_PIN(F, SO_INPUT_ENABLE);
	
	
	#else
	
	// Port B, SPI in/out:
	
	// SPI output pins
	Mask =  (1 << SO_OUTPUT_ENABLE) |
			(1 << SO_DATA)          |
			(1 << SO_CLOCK)         |
			(1 << SO_INPUT_ENABLE);

	// SPI input pins
	Mask |= (1 << SI_CLOCK)         |
			(1 << SI_PLOAD)         |
			(1 << SI_CLOCK_ENABLE);

	DDRB  = Mask; // '1' output, '0' input
	PORTB = Mask; // '1' pull up resistor on

	// Set defaults for input
	CLR_PIN(B, SI_CLOCK_ENABLE);
	SET_PIN(B, SI_PLOAD);

	// Set defaults for output
	SET_PIN(B, SO_OUTPUT_ENABLE);
	SET_PIN(B, SO_INPUT_ENABLE);
	
	#endif
}

void spiWrite16(uint16 v)
{
	uint8 Data;
	
	CLR_PIN(F, SO_CLOCK);
	CLR_PIN(F, SO_INPUT_ENABLE);

	for (int i=0; i<sizeof(v)<<3; i++)
	{
		Data = (v & (1 << i)) != 0;
		if (Data)
			SET_PIN(F, SO_DATA);
		else
			CLR_PIN(F, SO_DATA);
			
		SET_PIN(F, SO_CLOCK);
		delay_microsec(PULSE_WIDTH_US);
		CLR_PIN(F, SO_CLOCK);
	}

	SET_PIN(F, SO_INPUT_ENABLE);
}

/*
uint8 spiRead8(void)
{
	uint8 Data = 0;

	SET_PIN(B, SI_CLOCK_ENABLE);
	CLR_PIN(B, SI_PLOAD);
	delay_microsec(PULSE_WIDTH_US);
	SET_PIN(B, SI_PLOAD);
	CLR_PIN(B, SI_CLOCK_ENABLE);

	for (int i=0; i<sizeof(Data)<<3; i++)
	{
		uint8 Bit = PINB & (1 << SI_DATA_OUT) ? 1 : 0;
		if (Bit)
			Data |= 1 << i;
		
		// Start the clock cycle
		SET_PIN(B, SI_CLOCK);
		delay_microsec(PULSE_WIDTH_US);
		CLR_PIN(B, SI_CLOCK);
	}
	
	return Data;
}

uint16 spiRead16(void)
{
	uint16 Data = 0;

	SET_PIN(B, SI_CLOCK_ENABLE);
	CLR_PIN(B, SI_PLOAD);
	delay_microsec(PULSE_WIDTH_US);
	SET_PIN(B, SI_PLOAD);
	CLR_PIN(B, SI_CLOCK_ENABLE);

	for (int i=0; i<sizeof(Data)<<3; i++)
	{
		uint8 Bit = PINB & (1 << SI_DATA_OUT) ? 1 : 0;
		if (Bit)
			Data |= 1 << i;
		
		// Start the clock cycle
		SET_PIN(B, SI_CLOCK);
		delay_microsec(PULSE_WIDTH_US);
		CLR_PIN(B, SI_CLOCK);
	}
	
	return Data;
}
*/