I2CInit(void)
{
TRISC3 = 1; /* SDA and SCL as input pin */
TRISC4 = 1; /* these pins can be configured either i/p or o/p */
SSPSTAT |= 0x80; /* Slew rate disabled */
SSPCON = 0x28; /* SSPEN = 1, I2C Master mode, clock = FOSC/(4 * (SSPADD + 1)) */
SSPADD = 0x28; /* 100Khz @ 4Mhz Fosc */
}
I2CStart()
{
SEN = 1; /* Start condition enabled */
while(SEN); /* automatically cleared by hardware */
/* wait for start condition to finish */
}
I2CStop()
{
PEN = 1; /* Stop condition enabled */
while(PEN); /* Wait for stop condition to finish */
/* PEN automatically cleared by hardware */
}
I2CRestart()
{
RSEN = 1; /* Repeated start enabled */
while(RSEN); /* wait for condition to finish */
}
I2CAck()
{
ACKDT = 0; /* Acknowledge data bit, 0 = ACK */
ACKEN = 1; /* Ack data enabled */
while(ACKEN); /* wait for ack data to send on bus */
}
I2CNak()
{
ACKDT = 1; /* Acknowledge data bit, 1 = NAK */
ACKEN = 1; /* Ack data enabled */
while(ACKEN); /* wait for ack data to send on bus */
}
I2CWait()
{
while ( ( SSPCON2 & 0x1F ) || ( SSPSTAT & 0x04 ) );
/* wait for any pending transfer */
}
I2CSend(unsigned char dat)
{
SSPBUF = dat; /* Move data to SSPBUF */
while(BF); /* wait till complete data is sent from buffer */
while ( ( SSPCON2 & 0x1F ) || ( SSPSTAT & 0x04 ) ); /* wait for any pending transfer */
}
unsigned char I2CRead(void)
{
unsigned char temp;
RCEN = 1; /* Enable data reception */
while(!BF); /* wait for buffer full */
temp = SSPBUF; /* Read serial buffer and store in temp register */
while ( ( SSPCON2 & 0x1F ) || ( SSPSTAT & 0x04 ) ); /* wait to check any pending transfer */
return temp; /* Return the read data from bus */
}
READING PROCEDURE
// i2c reading starting here
I2CStart();
I2CSend(0xD0);
I2CSend(0x00);
I2CRestart();
I2CSend(0xD1);
for(a=0;a<8;a++)
{ tdata[a]=I2CRead();
I2CAck();
}//or X=I2CRead();
I2CStop();