 /*
 * File            : newmain.c
 * Author          : Ligo George
 * Company         : electroSome
 * Project         : SPI Master Example
 * Microcontroller : PIC 16F877A
 * Created on April 15, 2017, 5:59 PM
 */

#pragma config FOSC = INTRCIO   // Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled and can be enabled by SWDTEN bit of the WDTCON register)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // MCLR Pin Function Select bit (MCLR pin function is MCLR)
#pragma config CP = OFF         // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF      // Brown-out Reset Selection bits (BOR disabled)
#pragma config IESO = ON        // Internal External Switchover bit (Internal External Switchover mode is enabled)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is enabled)

#include <xc.h>
#include <pic16f690.h>
#include "spi.h"

#define _XTAL_FREQ 8000000

/* Master
SSPCON
0b00100000  - Spi_Type |
0b00000000  - Spi_Clock_Idle 
0b00100000 => SSPCON
 * SSPEN = 1;  // ??????? MSSP

 * SSPSTAT = 0 

* Slave
0b00100100  - Spi_Type |
0b00000000  - Spi_Clock_Idle 
0b00100100 => SSPCON
 * SSPEN = 1;  // ??????? MSSP
 * ????? - 0100 - ??????? SS ?????????
 
* SSPSTAT = 0
 

 */

void main()
{
   //nRBPU = 0;                    //Enable PORTB internal pull up resistor
   TRISB = 0;                 //PORTB as output
//   TRISC7 = 0;
   RB5 = 1;                     // CS

    TRISA = 0b11111000; // RA1 - output, RA2 - output
    ANS5 = 0;  // 0-digital IO, 1 - Analog in  - BUTTON
   
   spiInit(SPI_MASTER_OSC_DIV4, SPI_DATA_SAMPLE_MIDDLE, SPI_CLOCK_IDLE_LOW, SPI_IDLE_2_ACTIVE);
   
   while(1)
   {
       RB5 = 0;       //Slave Select
       __delay_ms(1);
       
        if (RA5 == 1) {
            spiWrite(0xAA);
            RA2 = 0;
        } else {
            spiWrite(0);
            RA2 = 1;
        }
 //       spiWrite(PORTB);
//       PORTD = spiRead();
       
       __delay_ms(1);
       RB5 = 1;       //Slave Deselect 
       
       __delay_ms(100);
   }
}