I2C stuck/hanging occasionally with I2C Scanner & Wire library

Dear Arduino-fellows,

I'm just a custom-made PCB with an ATMEGA328P that works quite reliably.

I've hooked up a SHT21 temperature/humidity sensor from sensirion with following library:

The pullups are 5.1kOhm for both SDA and SCL to VCC (checked), no shorts between GND, VCC, SDA or SCL (checked).

My problem is that occasionally (rarely but very frustrating), the code stucks at opening the I2C communication. I'm using an I2C scanner to check if the sensor is plugged in each time before measuring:

for (address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    Serial.print("Scanning address: ");
    Serial.print(address);
    Serial.print(", ");
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address < 16)
      Serial.print("0");
      Serial.println(address, HEX);
      byte sensoraddress = address;
      if (sensoraddress == 64)
      {
      state = 1;
      Serial.print("SHT21 from sensirion found with internal address ");
      Serial.println(sensoraddress);
      }
      nDevices++;
    }
    else if (error == 4)
    {
      Serial.print("Unknown error at address 0x");
      if (address < 16)
      Serial.print("0");
      Serial.println(address, HEX);
    }
  }

The code clearly hangs after Wire.beginTransmission. The problem only seems to occur when I plug off the sensor and plug it back (but not always).

Have you got any ideas?

Do you use long wires ?

At what voltage and frequency is the ATmega328P running ?
At what voltage is the SHT21 running ?
What voltage is VCC ?

Can you show a photo of the pcb ? so we can check where the decoupling capacitors are and if the crystal/resonator with the 22pF capacitors is close to the ATmega328P.

Can you show a schematic ? All GNDs and all VCCs of the ATmega328P should be connected and AREF should not be connected to VCC.

Starting from version Arduino IDE 1.8.13 the Wire libary has timeouts. That should make it possible to recover from a bad I2C bus.

I'm sorry to say, but the library by e-radionicacom is written by someone who does not understand the Wire library. I see only two harmless mistakes, so it should be no problem.

Before running your bus scan routine, it would be good to Wire.end() and Wire.begin() to reset the module since you most likely got some glitches on the bus during the disconnect/re-connect. And yes, make sure you are using 1.8.13 so you get timeouts vs. infinite hangs