#include "spi.h"
#include <xc.h> //XC32 prekladac
#include "delay.h"

void initSpi(void) {
    SPI_CS1_ANSEL = 0; //digitalni pin
    SPI_SDI_ANSEL = 0; //digitalni pin
    SPI_SDO_ANSEL = 0; //digitalni pin
    SPI_SCK_ANSEL = 0; //digitalni pin
    
    SPI_CS1_TRIS = 1; //vstup
    SPI_SDI_TRIS = 1; //vstup
    SPI_SDO_TRIS = 1; //vstup
    
    SDI2R = 8; //SPI 2 SDI na RPB3
    RPB1R = 6; //SPI 2 SDO na RPB1
    SS2R = 7; //SPI 2 SS na RPB2
    
    //8-bit data
    SPI2CONbits.CKE = 1; //zmena dat pri nabezne hrane clk (active -> idle)
    SPI2CONbits.CKP = 1; //clk idle pri log. 1, active pri log. 0
    
    SPI2BRG = 4; //100 kHz
}

void masterSpi(void) { //nastavit jako master
    SPI2CONbits.ON = 0; //vypnout
    
    SPI2CONbits.MSTEN = 1; //master
    SPI2CONbits.SSEN = 0; //nepouzit HW CS/SS (CS1)
    
    SPI_CS1 = 1; //aktivni v log. 0
    
    SPI_CS1_TRIS = 0; //vystup
    SPI_SCK_TRIS = 0; //vystup
    
    SPI2CONbits.ON = 1; //zapnout
}

void slaveSpi(void) { //nastavit jako slave
    SPI2CONbits.ON = 0; //vypnout
    
    SPI_CS1_TRIS = 1; //vstup
    SPI_SCK_TRIS = 1; //vstup
    
    SPI2CONbits.MSTEN = 0; //slave
    SPI2CONbits.SSEN = 1; //pouzit HW CS/SS (CS1)
    
    SPI2CONbits.ON = 1; //zapnout
}

unsigned char putSpi(unsigned char data) { //odeslat/prijmout data
    SPI2BUF = data;
    while(!SPI2STATbits.SPIRBF);
    data = SPI2BUF;
    
    return data;
}