#include <xc.h>



void InitSPI(void){
    SSPSTATbits.SMP=0;
    SSPSTATbits.CKE=0;
    SSPCON1bits.CKP=0;
    SSPCON1bits.SSPM3=0;
    SSPCON1bits.SSPM2=0;
    SSPCON1bits.SSPM1=0;
    SSPCON1bits.SSPM0=0;
    SSPCON1bits.SSPEN=1;
    TRISCbits.RC4=1;
    LATCbits.LC4=1;
}

unsigned int ReadSPI(int CS){
    int prvy=0;
    int druhy=0;
    int celkom=0;
    
    switch(CS)
    {
        case 0:
        LATEbits.LE0=0;
        break;
        
        case 1:
        LATAbits.LA5=0;
        break; 
        
        case 2:
        LATAbits.LA4=0;
        break;
        
        case 3:
        LATAbits.LA3=0;
        break;
    
        case 4:
        LATAbits.LA2=0;
        break;
        
        case 5:
        LATAbits.LA1=0;
        break;
        
        case 6:
        LATAbits.LA0=0;
        break;
        
        case 7:
        LATBbits.LB4=0;
        break;
    
    }
    

    PIR1bits.SSPIF=0;
    SSPBUF=0b0;    
    while(!PIR1bits.SSPIF){};
    PIR1bits.SSPIF=0;
    prvy=SSPBUF;
    SSPBUF=0b0;
    while(!PIR1bits.SSPIF){};  
    
    switch(CS)
    {
        case 0:
        LATEbits.LE0=1;
        break;
        
        case 1:
        LATAbits.LA5=1;
        break; 
        
        case 2:
        LATAbits.LA4=1;
        break;
        
        case 3:
        LATAbits.LA3=1;
        break;
    
        case 4:
        LATAbits.LA2=1;
        break;
        
        case 5:
        LATAbits.LA1=1;
        break;
        
        case 6:
        LATAbits.LA0=1;
        break;
        
        case 7:
        LATBbits.LB4=1;
        break;
    
    }
     
    druhy=SSPBUF;   
    celkom = (prvy << 8) | (druhy & 0xff);
    //celkom = (celkom & 0x0fff) | (000 & 0xF000);
    return(celkom);
    
}

