I2C is it possible to catch error "no bus" or "no slave"?

I happily stole a chunk of Nick Gammon’s I2C scanner for a sanity-checker during boot of my multi duino system.

boolean testI2C(byte addr) {
  boolean success = 0;
  for (int attempt = 0; attempt < 10; attempt++) {
    Serial.print("Try to transmit to address ");
  Wire.beginTransmission (addr);
  byte error = Wire.endTransmission();
  if (error == 0)
     Serial.print("Found slave alive and listening on try: ");
     success = 1;
  } else {
     Serial.print("Slave contact attempt: ");
 if (!success) {
  digitalWrite(redLight,HIGH);    // signal distress for I2C bus
  epicFail = 1;

called as follows from setup():

// join i2c bus as master
// now start up the numeric display so we can say "Init"
// let's not have weirdness downstream if we can't get a response from led matrix.  check first...
// any i2c slave MIA is grounds for distress signal and no boot.
  bool i2cOK = testI2C(0x71);  
  if (!i2cOK) {return;}

This is brand new code, so I may have made some logic errors… but what I am finding is that when the i2c bus is not powered (i.e. the pullups are not happening at the far end), this code hangs cold on the first write attempt. The last breadcrumb in the serial output is

Try to transmit to address 113

and after that, my master duino is out to lunch.

So, it seems that one can check for the presence of a slave on a healthy i2c bus; but if the bus itself is dark, it’s possible to disappear down a black hole on the first write attempt. Is this the case, or have I done summat foolish? I’m still pretty much a novice, so it’s quite possible :slight_smile:

Right now the 2 duinos power 2 separate 5v power busses. The i2c termination is powered by duino2, for various reasons not really relevant here. I am trying to cover the case where user plugs in duino1 before duino2, and half the system is missing; also trying to cover any race conditions during boot. This hang may be the final argument for one external 9v power supply for both duinos and the entire box of tricks. If a dark i2c bus is lethal to the master duino, then I need to make sure that the i2c bus is always powered when the master is powered…

The best "solution" I have found is check if the I2C bus lines are HIGH before starting the communication.. If not, the I2C bus communication will fail. The pins to check depend on the model Arduino.

aha! that had actually occurred to me today, after a little time away from the problem. I just tried it and yes, it works -- I can detect the absence of pullup voltage, forestall the hang and blink a trouble light if there is no i2c bus at all. great!