#include "sspslave.h"

/*
//typical ISR for RX
     if(PIR1bits.SSP1IF && PIE1bits.SSP1IE){
        PIR1bits.SSP1IF=0;  //clear flag
        i=SSP1BUF;          //read received data
        SSP1BUF=tx;         //set data for next byte
        SSP1CON1bits.SSPOV=0;   //if overflow, not necessary if BOEN set
    }
    if(PIR1bits.BCL1IF && PIE1bits.BCL1IE){ //probably only needed for I2C
        PIR1bits.BCL1IF=0;
    }
*/

void sspSlaveInit(void){    //set up for SSP slave
    anselbits.SSPSLAVE_SCK=0;
    anselbits.SSPSLAVE_MOSI=0;
    anselbits.SSPSLAVE_SS=0;
    anselbits.SSPSLAVE_MISO=0;
    trisbits.SSPSLAVE_SCK=1;
    trisbits.SSPSLAVE_MOSI=1;
    trisbits.SSPSLAVE_SS=1;
    trisbits.SSPSLAVE_MISO=0;
    wpubits.SSPSLAVE_SS=1;      //pullup for safety    
    //unlock
    //GIE = 0; //assume this occurs before interrupts enabled
    PPSLOCK = 0x55; //Required sequence
    PPSLOCK = 0xAA; //Required sequence
    PPSLOCKbits.PPSLOCKED = 0; //Clear PPSLOCKED bit
    //PPS inputs, use defines in sspslave.h
    SSP1CLKPPS=SSPSLAVE_SCK;   
    SSP1DATPPS=SSPSLAVE_MOSI;
    SSP1SSPPS=SSPSLAVE_SS;
    pps.SSPSLAVE_MISO=0x08;  //SDA1/SDO1
    pps.SSPSLAVE_SCK=0x07;   //SCL1/SCK1
    //lock
    PPSLOCK = 0x55; //Required sequence
    PPSLOCK = 0xAA; //Required sequence
    PPSLOCKbits.PPSLOCKED = 1; //LOCK
    //SPI Slave
    SSP1CON1=0;         //reset
    SSP1CON1bits.CKP=0;     //idle low
    SSP1CON1bits.SSPM=4;    //SPI slave with CS
    SSP1STATbits.CKE=1;
    SSP1CON3bits.BOEN=1;    //overwrite enable
    PIR1bits.SSP1IF=0;      //clear
    PIR1bits.BCL1IF=0;      //clear
    //SSP1BUF;
    //SSP1STATbits.BF;      //buffer full
    PIE1bits.SSP1IE=1;
    //PIE1bits.BCL1IE=1;
    SSP1CON1bits.SSPEN=1;   //enable
    PEIE=1;    
    //GIE=1;        //set in main
    SSP1BUF=0;      //
}
