#include "h/p33FJ64GP802.h"
#include "h/spi.h"
#include "h/types.h"
/* Initialize and enable the SPI module */

void InitSPI(int speed)
{
	// Initialise the SPI System
	//
	// map SPI1 pins as follows:
	// RP11= /SS
	// RP10= SDO1
	// RP7=  SCKL
	// RP6=  SDI1
	
	SPI1STAT=0;
	SPI1CON1=0;
	SPI1CON2=0;
	TRISBbits.TRISB11=0;
	TRISBbits.TRISB6=1;
	SDCS=1;
	RPOR4=0x0700;		// RP9= SPI Data Out
	RPOR5=0x0008;		// RP10= SPI Clk
	RPINR20=0x0A0B;		// RP11= SPI Data In
	IFS0bits.SPI1IF=0;
	SPI1CON1=(speed & 0x001F);
	SPI1CON1bits.SMP=0;
	SPI1CON1bits.CKP=0;			// clock Polarity 0: idle low, active high 1: idle high, active low
	SPI1CON1bits.CKE=1;			// clock edge selection
	SPI1CON1bits.MSTEN=1;		// enable Master Mode
	SPI1CON2=0x0000;
	SPI1STATbits.SPIROV=0;
	SPI1STATbits.SPIEN=1;
}

BYTE WriteSPI(BYTE x)
{
	SDCS=0;
	SPI1BUF=x;
	while(SPI1STATbits.SPITBF);
	while(SPI1STATbits.SPIRBF==0);
	x=SPI1BUF;
	SDCS=1;
	return x;
}


BYTE WriteSPIWithoutSS(BYTE x)
{
	SPI1BUF=x;
	while(SPI1STATbits.SPITBF);
	while(SPI1STATbits.SPIRBF==0);
	x=SPI1BUF;
	return x;
}

