22.6.5 Client Reception (7-bit Address)

Client Reception (7-bit Address)

#include <xc.h>

#define mCLIENT_ADDRESS 0x4C

#define PACKET_SIZE 10

volatile unsigned char clientReceived[PACKET_SIZE + 1];
volatile unsigned char recievedCount = 0;

int main(void) {
    
    /*Configure I2C pins as digital*/

    //I2C module has Host and Client functionality which may both be active at the same time.
    //In this example, Client functionality will be configured and used.
    
    //Set up I2C2 client configuration
    I2C2ADD = mCLIENT_ADDRESS;         // Configure Client address
    I2C2INTCbits.CADDRIE = 1;          // Assert CLTIF on address detect
    I2C2INTCbits.CDRXIE = 1;           // Assert CLTIF on received byte
    I2C2INTCbits.CLTIE = 1;            // Assert I2CxIF when CLTIF is asserted
    I2C2CON2bits.SMEN = 1;             // Enable smart mode
    I2C2CON2bits.PSZ = PACKET_SIZE;    // Packet size 
    I2C2CON1bits.ON = 1;               // Enable I2C  
    IFS2bits.I2C2IF = 0;               // Clear I2C general interrupt 
    IEC2bits.I2C2IE = 1;               // Enable I2C general interrupt 

    while (1) {}
 
}
void __attribute__((__interrupt__, no_auto_psv)) _I2C2Interrupt(void) {
    IFS2bits.I2C2IF = 0;
    /* Read received address*/
    if ((I2C2STAT1bits.RBF)&& (!I2C2STAT1bits.D_A)) {
        recievedCount = 0;
        clientReceived[recievedCount] = I2C2RCV;
        recievedCount++;
    } /* Read received data byte*/
    else if ((I2C2STAT1bits.RBF)&& (I2C2STAT1bits.D_A)) {
        clientReceived[recievedCount] = I2C2RCV;
        recievedCount++; // Read received data
    }
}