#include "I2C2.h"

void i2c_init(void)
{
  //Clear all registers, enable device, set BRG
    I2C2CON = 0;
    I2C2STAT = 0;
    I2C2ADD = 0;
    I2C2MSK = 0;
    I2C2BRG = 0;
    I2C2TRN = 0;
    I2C2RCV = 0;
    DDPCONbits.JTAGEN = 0; //Disable JTAG
    I2C2CONbits.ON = 1;
    I2C2BRG = 0x025;
}

void i2c_start(void)
{

    //Check if bus is idle
    while(I2C2STATbits.BCL)
    {
        I2C2STATbits.BCL = 0;
    }
    //Send start condition
    I2C2CONbits.SEN = 1;
    while(!IFS1bits.I2C2MIF);
    IFS1bits.I2C2MIF = 0;
}

void i2c_stop(void)
{
    //Check if bus is idle
    while(I2C2STATbits.BCL)
    {
        I2C2STATbits.BCL = 0;
    }
    //Send stop condition
    I2C2CONbits.PEN = 1;
    while(!IFS1bits.I2C2MIF);
    IFS1bits.I2C2MIF = 0;
}

void i2c_restart(void)
{
    //Check if bus is idle
    while(I2C2STATbits.BCL)
    {
        I2C2STATbits.BCL = 0;
    }
    //Send restart condition
    I2C2CONbits.RSEN = 1;
    while(!IFS1bits.I2C2MIF);
    IFS1bits.I2C2MIF = 0;
}

int i2c_send(char send_data)
{
    I2C2TRN = send_data;
    while(I2C2STATbits.TBF);
    while(!IFS1bits.I2C2MIF);
    IFS1bits.I2C2MIF = 0;
    return I2C2STATbits.ACKSTAT;
}

int i2c_receive(void)
{
    I2C2CONbits.RCEN = 1;
    while(!I2C2STATbits.RBF);
    while(!IFS1bits.I2C2MIF);
    IFS1bits.I2C2MIF = 0;
    return I2C2RCV;
}


