Arduino freeze protection in case of device failure on i2c bus?

Hi,

There are several i2c devices in my project (I2C LCD -> PCF8574, I2C EEPROM -> 24LC256, I2C IO Extender -> PCA9534PW).
I noticed that if these devices are disconnected from the i2c bus, then the Arduino UNO, which is the master, may hang in void setup() when trying to connect to these devices.
The question is, what is the reason and is it possible to protect the Arduino from freezing in case of loss of communication with i2c devices?

In I2C Bus, the data exchange happens on pure handshaking basis. The Master sends a data byte to Slave and waits for ACK (acknowledgement). While the ACK has yet to arrive, and in the meantime, the target Slave has gone down -- the Master will hang! The solution is to set a timeout time so that the Master can come out from the infinite time waiting loop.

bool i2cReady(uint8_t adr) (untested)
{
  uint32_t timeout = millis();
  bool ready = false;
  while((millis() - timeout < 100) && (!ready))  //100 ms timeout time
  {
     Wire.beginTransmission(adr);   //slave address = adr
     int err = Wire.endTransmission();
     ready = (err == 0)? true : false?
  }
  return ready;
}

GolamMostafa,

Thank you!!!