/*
 Author: Obrtac Tomas  
 Mail: obrtac.tomas@gmail.com
 2017
 */



#include "SPI_commands.h"
#include <xc.h>

// Define TRIS ports which will be remapped
#define SPI_IN TRISD6
#define SPI_OUT TRISD7
#define SPI_CLK TRISD5

#define SPI_IN_N 23 // Selected RP port number
#define SPI_OUT_N RPOR24 // SPI output ports selected for remapping . Always RP + slected port
#define SPI_CLK_N RPOR22

#define CS0 

void SPI_Remap(void)
{
    SPI_IN = 1;  // Setting I/O ports
    SPI_OUT = 0;
    SPI_CLK = 0; 
    RPINR21 = SPI_IN_N; // Selecting the appropriate port. DTS page 151
    SPI_OUT_N = 9; // Assignment function for appropriate port. DTS page 152
    SPI_CLK_N = 10; // Assignment function for appropriate port. DTS page 152
    SSP2STAT = 0b00000000; // Setting SPI registers
    SSP2CON1 = 0b00110000;
}

uint8_t ReadSPI(void)
{
	SSP2BUF = 0;				// Transmit a dummy byte to start receiving
	while (!SSP2STATbits.BF) continue;
	return SSP2BUF;			// Receive byte in SSPBUF
}

uint8_t wait_SPI(void)
{
    while(!SSP2STATbits.BF);   
    return SSP2BUF;
}

void Enable_SPI(void)
{
    SSP2CON1bits.SSPEN = 0;
    SSP2STAT = 0b00000000; // Setting registers
    SSP2CON1 = 0b00110000;
}

uint8_t ReceiveSPI(char command)
{
    SSP2STATbits.BF=0;    
    SSP2BUF = command;
    return wait_SPI(); //Save the received data from the slave.
}
