#include "i2c.h"
#include <xc.h> //XC32 prekladac

//I2C jako master

void initI2c(void) {
    //7-bit adresa
    I2C1CONbits.ON = 0; //vypnout
    I2C1BRG = 3; //100 kHz, 104 ns
    I2C1CONbits.ON = 1; //zapnout
}

void startI2c(void) { //start podminka
    I2C1CONbits.SEN = 1;
    while(I2C1CONbits.SEN);
}

void restartI2c(void) { //restart podminka (misto stop a start)
    I2C1CONbits.RSEN = 1;
    while(I2C1CONbits.RSEN);
}

void stopI2c(void) { //stop podminka
    I2C1CONbits.PEN = 1;
    while(I2C1CONbits.PEN);
}

void writeI2c(unsigned char data) { //zapsat data
    I2C1TRN = data;
    while(I2C1STATbits.TBF);
    while(I2C1STATbits.TRSTAT);
}

unsigned char readI2c(void) { //vycist data
    I2C1CONbits.RCEN = 1; //precist
    while(I2C1CONbits.RCEN);
    
    return I2C1RCV;
}

void ackI2c(void) { //odeslat ACK
    I2C1CONbits.ACKDT = 0;
    I2C1CONbits.ACKEN = 1;
    while(I2C1CONbits.ACKEN);
}

void nackI2c(void) { //odeslat NACK
    I2C1CONbits.ACKDT = 1;
    I2C1CONbits.ACKEN = 1;
    while(I2C1CONbits.ACKEN);
}

unsigned char getAckI2c(void) { //precist ACK/NACK
    return !I2C1STATbits.ACKSTAT;
}