I assume you are using MPLAB with C18. The source for all the I2C functions can be found in: C:\Program Files (x86)\Microchip\mplabc18\v3.46\src\pmc_common\i2c
Next, you'll need to figure out what functions are hanging and then write your own versions that don't go into endless loops if the slave doesn't respond. Most like ReadI2C
is hanging waiting for a slave to respond. So you could replace it with myReadI2C
that takes a timeout parameter. A modified version of the code in i2c_read.c.
#if defined (I2C_V1)
int myReadI2C( long timeout )
{
if( ((SSPCON1&0x0F)==0x08) || ((SSPCON1&0x0F)==0x0B) ) //master mode only
SSPCON2bits.RCEN = 1; // enable master for 1 byte reception
while ( !SSPSTATbits.BF && timeout > 0) timeout--; // wait until byte received
return timeout == 0 ? (-1) : ( SSPBUF ); // return with read byte
}
#endif
#if defined (I2C_V4)
int myReadI2C( long timeout)
{
while ( !SSPSTATbits.BF && timeout > 0) timeout--; // wait until byte received
return timeout == 0 ? (-1) : ( SSPBUF ); // return with read byte
}
#endif
myReadI2C
will return -1 on timeout and unsigned char value (0 - 255) on success. You will need to modify the other I2C functions you use in a similar way to avoid loops that only test register status values. As for a value for timeout, you need to find a value through experimentation depending on your devices clock speed and your peripherals response time.