/*I2CTransmission.c
 *This file contains general I2C Transmission code
 *Author: Matthew Domenech
 */



int I2CTransmission(void){
    I2C1CONbits.ON = 1;
    I2C1CONbits.A10M = 0; //sets I2CxADD to 7 bit address mode
    I2C1ADD = 0b00000000; //first set address of slave to 0000000 in binary
    ACK_true = 0;
    
    //this next part loops forever
    while(1){
        if (I2C1RCV == 0b00000001 || I2C1RCV == 0b00000000){    //check if address received matches slave address
            //I2C1STATbits.D_A = 0; //last bit received was an address
            check_RW = I2C1STATbits.R_W;    //check read write bit
            
            ACK_true = 1;
            while (ACK_true) {
                
                switch (check_RW) {  //Read/Write switch case

                    case 0: //write bit enabled. GET DATA FROM MASTER 
                        rx_buffer = I2C1RCV; //get data from receive buffer
                        I2C1CONbits.SCLREL = 1; //release clock
                        dummy = rx_buffer;
                        ACK_true = 0;
                        break;

                    case 1: //read bit enabled. SEND DATA TO MASTER
                        
                        I2C1TRN = dummy; //load transmit buffer with test data
                        if(I2C1STATbits.TBF){ //if transmit buffer is full
                            dummy = dummy+5;
                        }
                        //Need Delay here?
                        I2C1CONbits.SCLREL = 1;
                        //dummy = I2C1TRN;
                        ACK_true = 0;
                        break;
                }
                //while(IFS0bits.I2C1SIF != 1);   //slave generates interrupt
                if (I2C1STATbits.ACKSTAT = 0) { //if acknowledged, then do not exit switch case and go back to idle
                    ACK_true = 1;
                    //dummy = dummy+5
                }
            }
        }                    
    }
    return(EXIT_SUCCESS);
}