/****************************************************************************/
/* Copyright 2013 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/
/* Written by Bob Herlien for SensorNode for xFOCE, June 2013               */
/****************************************************************************/

#include "spi.h"
#include "p24Fxxxx.h"
#include "port.h"


/****************************************************************************/
/*  Setup SPI signals                                                       */
/****************************************************************************/

void spiInit()
{
    /* Setup SPI1 (local) Control Registers */

    SPI1CON1bits.DISSCK = 0;	// spi clock enabled
    SPI1CON1bits.DISSDO = 0;	// SDO pin enabled
    SPI1CON1bits.MODE16 = 1;	// 16 bit transfers
    SPI1CON1bits.SMP = 0;	// input sample in  0:middle   1:end
    SPI1CON1bits.CKE = 1;	// output transition is 0:idle to active, 1:active to idle
    SPI1CON1bits.SSEN = 0;	// using a digital out for cs
    SPI1CON1bits.CKP = 0; 	// idle=low, active=high
    SPI1CON1bits.MSTEN = 1;	// PIC is master
    SPI1CON1bits.SPRE = 7;	// Clock secondary prescale = 1:1 
    SPI1CON1bits.PPRE = 2; 	// Clock primary prescale = 4:1 
	
    SPI1CON2bits.FRMEN = 0;	// framed SPI disabled
    SPI1CON2bits.SPIFSD = 0;
    SPI1CON2bits.SPIFPOL = 0;
    SPI1CON2bits.SPIFE = 0;
    SPI1CON2bits.SPIBEN = 0;	// Enhanced mode disabled

    SPI1STATbits.SPIROV = 0;

    SPI1STATbits.SPIEN = 1;	// enables SPI Communication
}


USHORT spiReadWrite(USHORT dat)
{
    while ( SPI1STATbits.SPITBF )	/* Wait for Tx buf available	*/
        ;

    SPI1BUF = dat;			/* put data in SPI TX buffer	*/

    while ( !SPI1STATbits.SPIRBF )	/* wait for received byte	*/
        ;

    return(SPI1BUF);			/* Return received byte		*/
}
