#include <xc.h>
void I2C1_Initialize(void)
{
if(!I2C1CON0bits.EN)
{
I2C1CON1 = 0x80;
I2C1CON2 = 0x20;
// CLK MFINTOSC
I2C1CLK = 0x03;
I2C1CON0 = 0x84;
I2C1PIR = 0;// ;Clear all the error flags
I2C1ERR = 0;
}
}
void i2c_start(unsigned char addr, unsigned char length) {
I2C1_Initialize();
I2C1STAT1bits.CLRBF = 1;
while (I2C1STAT1bits.CLRBF) {}
while (!I2C1STAT0bits.BFRE) {}
I2C1ADB0 = 0;
I2C1ADB1 = addr;
I2C1CNT = length;
I2C1CON0bits.S = 1; //Start
while (I2C1CON0bits.S) {
__delay_us(1);
}
}
void i2c_stop(void) {
I2C1CNT = 0;
while (!I2C1PIRbits.PCIF) {
__delay_us(1);
}
}
unsigned char i2c_write(unsigned char byte) {
I2C1TXB = byte;
while (!I2C1STAT1bits.TXBE) {
__delay_us(1);
}
return I2C1CON1bits.ACKSTAT;
}
void i2c_writeNBytes(uint8_t address, unsigned char* data, uint8_t len)
{
i2c_start(address, len);
while(len--)
{
i2c_write(*data++);
}
i2c_stop();
}