Here is some code that may help someone here. It is an I2C bus scan tool that I cobbled together from other examples online.
This uses a modified I2C write command (The mikroc pro built in i2c write will wait forever if it does not receive a response...)
It will scan the I2C bus and write the results out on a serial terminal.
I am not a professional programmer, just a hobbyist. Maybe this will help some one out...
int i=0;
signed char _status=0;
signed char WriteI2C( unsigned char data_out );
void main() {
I2C1_Init(100000); // Init I2C Bus @ 100Khz
UART1_init(9600); // Setup serial at 9600bps
Delay_ms(100); // Wait for UART module to stabilize
while(1){
char buffer[15];
UART1_Write(10);
UART1_Write(13);
UART1_Write_Text("Start");
UART1_Write(10);
UART1_Write(13);
for ( i=1; i<=127; i++)
{
i2c1_start();
_status = WriteI2C(i<<1);
I2C1_stop();
if (_status==0)
{
sprinti(buffer,"Device at:%X\n", i);
UART1_Write_Text(buffer);
}
}
sprinti(buffer,"Complete.\n", i);
UART1_Write_Text(buffer);
sprinti(buffer,"Pause 5 Sec.\n", i);
UART1_Write_Text(buffer);
Delay_ms(5000);
}
}
signed char WriteI2C( unsigned char data_out )
{
int counter = 0; // Counter used in timeout for I2C operations
SSP1BUF = data_out; // write single byte to SSPBUF
if ( SSPCON1.WCOL ) // test if write collision occurred
return ( -1 ); // if WCOL bit is set return negative #
else
{
if( ((SSPCON1&0x0F)==0x08) || ((SSPCON1&0x0F)==0x0B) ) //master mode only
{
counter=0;
while( SSPSTAT.BF ) // wait until write cycle is complete
{
// Setup timer so that we don't wait forever if there is an error
counter +=1;
if (counter >= 1000)
{
return ( -99 ); // Time out after 1000 clock cycles
}
}
I2C1_Is_Idle(); // ensure module is idle
if ( SSPCON2.ACKSTAT ) // test for ACK condition received
return ( -2 ); // return NACK
else return ( 0 ); // return ACK
}
}
}