Error handling Wire.endTransmission() hang

Hi all,

I'm trying to find a way to handle the Wire.endTransmission() hang.

In essence, in my current script, I wish to enact some error handling during setup where if my IMU doesn't respond on the I2C bus, I simply accept and move on with an error value.

Currently, my script freezes at the Wire.endTransmission() part as it doesn't print the error status.
I understand the Wire library doesn't have a timeout function and can get stuck in a while loop, hence the hang.

const int MPU = 0x68;
Wire.beginTransmission(MPU);
errorIMU = Wire.endTransmission();
Serial.println(errorIMU);

I know this is a common issue so I am just looking for either an alternative Wire library or a function I can wrap around this to act as a timeout.

I've come across a lot of threads discussing this issue with no timeouts in the Wire library itself and even reference to an updated library with a timeout function (though no links worked to it so I haven't been able to find it) but not really clear as to a specific solution.

Thanks in advance!

1 Like

If you can't find a version of Wire with timeouts, you can add them yourself.

I found it much easier to start with simpler I2C libraries (collections of simple routines) and add the required timeouts, but here is someone else's work.

Depends on the type of Arduino, of course, which you forgot to mention.

The I2C bus should work, it was not designed to be fault tolerant.
That means you first have to fix the I2C bus.

What is wrong with your I2C bus ? Are the wires too long ? Wrong value pullup resistors ? Using a cable ? Crosstalk between SDA and SCL ? Voltage mismatch ? Is a sensor powered down ? A bug in the sketch ? A weird sensor doing silly things ? Two Masters on the bus ?

With Arduino IDE 1.8.13 (the current newest version) a low-level timeout for the I2C bus was added for the AVR family boards (Arduino Uno) :sunglasses:
It is not turned on by default yet, and you have to look into the source to read how to use it.

Timeout explained at line 90: ArduinoCore-avr/Wire.cpp at master · arduino/ArduinoCore-avr · GitHub.

The update for the Wire function in Arduini IDE1.8.13 (plus the link) has proved helpful - so thank you very much! I've made use of the Wire.setTimeout, Wire.getWireTimeoutFlag and Wire.clearWireTimeoutFlag.

My particular case is the MPU is now broken (or at least only works intermittently - I think it got a voltage surge during some testing). At the moment I won't be replacing it, however, I thought it prudent to find a solution for the future for handling it going down during use for safety reasons.
It is not function critical as it is simply another option for controlling a transmitter over joysticks and buttons (i.e. tilting the controller for traction/braking and steering).