/****************************************************************************/
/* Copyright 2009 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/

#include <stdio.h>
#include "sys_defs.h"
#include "spi2.h"
#include "p24Fxxxx.h"
#include "stdlib.h"
#include "serial.h"

// CONFIG2 = 0xFFEF;


/****************************************************************************/
/*  Setup SPI signals                                                       */
/****************************************************************************/

void spi2Init()
{
	/* Setup SPI2 (local) Control Registers */
	
	SPI2CON1bits.DISSCK = 0; // spi clock enabled
	SPI2CON1bits.DISSDO = 0; // SDO pin enabled
	SPI2CON1bits.MODE16 = 0; // 8-bit words
	SPI2CON1bits.SMP = 0; // input sample in  0:middle   1:end
	SPI2CON1bits.CKE = 0; // output transition is 0:idle to active, 1:active to idle
	SPI2CON1bits.SSEN = 0; // using a digital out for cs
	SPI2CON1bits.CKP = 0; // idle=low, active=high
	SPI2CON1bits.MSTEN = 1; // PIC is master
	SPI2CON1bits.SPRE = 0; // Clock secondary prescale = 1:8 
	SPI2CON1bits.PPRE = 3; // Clock primary prescale = 1:1 
	
	SPI2CON2bits.FRMEN = 0; // framed SPI disabled
	SPI2CON2bits.SPIFSD = 0; // 
	SPI2CON2bits.SPIFPOL = 0;
	SPI2CON2bits.SPIFE = 0;
	SPI2CON2bits.SPIBEN = 0; // Enhanced mode disabled

	SPI2STATbits.SPIEN = 1; // enables SPI Communication
	
	
	/* Map SPI signals to RP pins */
	/**********************************************/	
	/* Unlock PPS registers for configuration change  */ 
	
	asm volatile	(	"push	w1			\n"
						"push	w2			\n"
						"push	w3			\n"
						"mov	#OSCCON, w1	\n"
						"mov	#0x46, w2	\n"
						"mov	#0x57, w3	\n"
						"mov.b	w2,	[w1]	\n"
						"mov.b	w3,	[w1]	\n"
						"bclr	OSCCON,	#6	\n"
						"pop	w3			\n"
						"pop	w2			\n"
						"pop	w1");   
				
	/*Map SPI #2 Pins */
	//*added* --JP
	RPINR22bits.SDI2R = 13;	// SDI2 (MISO) RP13
	RPOR14bits.RP28R = 7;	// SDO2 (MOSI) RP28
	RPOR9bits.RP18R = 8;		// SCK2 (SCK)  RP18

	/* Lock PPS registers */						
	
	asm volatile	(	"push	w1			\n"
						"push	w2			\n"
						"push	w3			\n"
						"mov	#OSCCON, w1	\n"
						"mov	#0x46, w2	\n"
						"mov	#0x57, w3	\n"
						"mov.b	w2,	[w1]	\n"
						"mov.b	w3,	[w1]	\n"
						"bset	OSCCON,	#6	\n"
						"pop	w3			\n"
						"pop	w2			\n"
						"pop	w1");  
	
	/*********************************************/
	
}


unsigned int spiReadWrite2(unsigned char data)
{
    /* put data in SPI TX buffer */
    SPI2BUF = data;
	/* wait for xmit to finish */
    while ( !SPI2STATbits.SPIRBF )
        ; /* wait here */
	data = 0;
    return SPI2BUF;
}

