23.6.7 Client Transmission (7-bit Address)

Client Transmission (7-bit Address)

#include <xc.h>


#define mCLIENT_ADDRESS 0x4C

#define INIT              1
#define ADDRESS_PHASE     2
#define DATA_READ         3

volatile unsigned char gReceived[20], gRcv_count, gTrans_count, count = 0;

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

    /*I2C1 configured as client*/

    I2C1ADD = mCLIENT_ADDRESS; // Configure Client address
    I2C1INTCbits.CADDRIE = 1; // Assert CLTIF on address detect
    I2C1INTCbits.CDRXIE = 1; // Assert CLTIF on received byte
    I2C1INTCbits.CDTXIE = 1; // Assert CLTIF on transmit byte
    I2C1INTCbits.CLTIE = 1; // Assert I2CxIF when CLTIF is asserted

    I2C1CON2bits.SMEN = 1; // Enable smart mode
    I2C1CON2bits.PSZ = 10; // Packet size	


    I2C1CON1bits.ON = 1; // Enable I2C


    IFS2bits.I2C1IF = 0; // Clear I2C general interrupt    
    IEC2bits.I2C1IE = 1; // Enable I2C general interrup													   

    while (1) {

    }
}

void __attribute__((__interrupt__, no_auto_psv)) _I2C1Interrupt(void) {

    IFS2bits.I2C1IF = 0;
    /* Read received address*/
    if ((I2C1STAT1bits.RBF)&& (!I2C1STAT1bits.D_A)) {
        gTrans_count = 0;
        gRcv_count = 0;
        gReceived[gRcv_count] = I2C1RCV;
        gRcv_count++;

    }/* Read received data byte*/
    else if ((I2C1STAT1bits.RBF)&& (I2C1STAT1bits.D_A)) {
        gReceived[gRcv_count] = I2C1RCV;
        gRcv_count++; // Read received data

    }
    /* transmit byte if R_W is set */
    if ((I2C1STAT1bits.R_W) &&(!I2C1STAT1bits.ACKSTAT)) {
        I2C1TRN = gTrans_count++; // transmit data

    }
}

s