22.6.7 Client Transmission (7-bit Address)

Client Transmission (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;
volatile unsigned char transmittedCount = 0;
volatile unsigned char clientTransmit[PACKET_SIZE] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};

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.CDTXIE = 1;           // Assert CLTIF on transmit 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)) {
        transmittedCount = 0;
        recievedCount = 0;
        clientReceived[recievedCount] = I2C2RCV;
        recievedCount++;        
    }/* Read received data byte*/
    else if ((I2C2STAT1bits.RBF)&& (I2C2STAT1bits.D_A)) {
        clientReceived[recievedCount] = I2C2RCV;
        recievedCount++; // Read received data (?)
    }
    /* transmit byte if R_W is set */
    if ((I2C2STAT1bits.R_W) && (!I2C2STAT1bits.ACKSTAT)) {
        I2C2TRN = clientTransmit[transmittedCount++]; // transmit data
    }
}