SOLUTION: Arduino freezes if I2C device gets disconnected (using Wire.h)

Hi,

by default the Wire.h library uses while-loops without a timeout. So if you disconnect the I2C device during an ongoing communication the programm is likely to get stuck in a while loop.

To fix this issue just open the twi.c file with the editor of your choice.

The file is located at: {Arduino install}/hardware/arduino/avr/libraries/Wire/src/utility/twi.c

Look for this line (around line 54):

static volatile uint32_t twi_timeout_us = 0ul;

and change it to the timeout you want (in my case 20ms /20000us):

static volatile uint32_t twi_timeout_us = 20000ul;

Save the file and recompile your project. It should not freeze anymore.
Hope this helped.

Your filepath to twi.c suggests that you work on an Arduino from the avr platform, such as an Arduino Uno R3.
On that platform, there is no need to hack the twi.c file, because the time-out functionality is exposed with the function
Wire.setWireTimeout(uint32_t timeout, bool reset_with_timeout);

Unfortunately, on other platforms, such as the megaavr (with the Arduino Uno WiFi Rev2 as an example), the time-out functionality is not implemented, the twi.c does not have this twi_timeout_us variable and the Wire library does not have the setWireTimeout function.