Auto-Loading the I2C Byte Count Register

The stand-alone I2C module features the ability to configure the I2CxCNT register to be automatically loaded in hardware by enabling the Auto Load I2C Count (ACNT) register enable bit. When auto-loading of the I2C Count register has been enabled, the first received or transmitted data byte following the address will be loaded into the I2CxCNT register in hardware. The value of the Acknowledge Data (ACKDT) bit will be used for the ACK response, which prevents a false NACK bit from being generated before the I2CxCNT register has been updated. Auto-loading the I2CxCNT register is a valid configuration for all I2C modes of operation and can be very useful in applications where the master needs information from the slave about the size of an incoming data packet or vice versa.

Auto-Loading I2C Byte Count

void WriteNBytes_AutoLoad(uint8_t address, uint8_t reg, void* data, uint8_t len){
      uint8_t *dataPointer = data; // Data Packet for transmission
      // When ACNT = 1, First Transmitted/Received Byte 
      // Following Address is Loaded into I2CxCNT
      I2CxCON2bits.ACNT = 1; // Auto-Load Count Enabled
      I2CxTXB = len; // Transmits length, automatically Loads len into I2CxCNT
      I2CxCON0bits.S = 1; // Set start bit to transmit 0x03 (I2CxCNT) 
      while (!I2CxSTAT1bits.TXBE); //Waiting for the buffer to be empty
      I2CxCON0bits.S = 1; // Set Start bit to transmit data packet;
      while (I2CxCNT) // While Count is true
            while (!I2CxSTAT1bits.TXBE); // Wait until buffer is empty;
            I2CxTXB = *dataPointer++; // Load next byte to transmit;
      wait4Stop(); // Wait for hardware to issue Stop