diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index 81295d68..54c9d3d4 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -39,6 +39,18 @@ extern "C" { #define I2C_TWIM_TIMEOUT_MS 100 #endif +// After a timeout the TWIM can stay wedged even once the bus is released (seen with +// SCL held low, then let go: every later call timed out until a reboot). A disable/ +// enable cycle resets its state machine; PSEL and FREQUENCY are kept. +static void twim_recover(NRF_TWIM_Type* twim) +{ + twim->ENABLE = (TWIM_ENABLE_ENABLE_Disabled << TWIM_ENABLE_ENABLE_Pos); + twim->EVENTS_STOPPED = 0x0UL; + twim->EVENTS_SUSPENDED = 0x0UL; + twim->EVENTS_ERROR = 0x0UL; + twim->ENABLE = (TWIM_ENABLE_ENABLE_Enabled << TWIM_ENABLE_ENABLE_Pos); +} + static volatile uint32_t* pincfg_reg(uint32_t pin) { NRF_GPIO_Type * port = nrf_gpio_pin_port_decode(&pin); @@ -191,7 +203,7 @@ uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) _p_twim->TASKS_STOP = 0x1UL; wait_start = millis(); while(!_p_twim->EVENTS_STOPPED) { - if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break; + if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; } } _p_twim->EVENTS_STOPPED = 0x0UL; } @@ -200,7 +212,7 @@ uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) _p_twim->TASKS_SUSPEND = 0x1UL; wait_start = millis(); while(!_p_twim->EVENTS_SUSPENDED) { - if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break; + if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; } } _p_twim->EVENTS_SUSPENDED = 0x0UL; } @@ -213,6 +225,7 @@ uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit) // on timeout nothing was actually clocked in - report 0 bytes rather than // whatever stale RXD.AMOUNT is left over from a previous transaction if (timed_out) { + twim_recover(_p_twim); return 0; } @@ -276,7 +289,9 @@ uint8_t TwoWire::endTransmission(bool stopBit) _p_twim->TASKS_STOP = 0x1UL; wait_start = millis(); while(!_p_twim->EVENTS_STOPPED) { - if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break; + // a STOP that never completes (SCL held low) is a failed transaction too: + // without this an empty probe on a stuck bus returned 0, "device ACKed" + if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; } } _p_twim->EVENTS_STOPPED = 0x0UL; } @@ -285,7 +300,7 @@ uint8_t TwoWire::endTransmission(bool stopBit) _p_twim->TASKS_SUSPEND = 0x1UL; wait_start = millis(); while(!_p_twim->EVENTS_SUSPENDED) { - if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break; + if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; } } _p_twim->EVENTS_SUSPENDED = 0x0UL; } @@ -317,6 +332,7 @@ uint8_t TwoWire::endTransmission(bool stopBit) // bus for a device that ACKed. See adafruit/Adafruit_nRF52_Arduino#771. if (timed_out) { + twim_recover(_p_twim); return 4; }