How to detect that an i2c slave doesn't respond to the master on PIC18f [closed]

StackOverflow https://stackoverflow.com/questions/16444271

  •  14-04-2022
  •  | 
  •  

Frage

I have an PIC18f i2c Master and some other devices as slaves.

I want to detect if a slave is not on the bus or if he doesn't responds.

Right now, the communication Master<->Slaves works well except when a slave doesn't responds. When this happens, the PIC stays in a waiting state and the whole program is stopped.

How can I detect and fix that ? (In a software way)

For information, I'm working on a PIC18f25k22.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top