Files
Adafruit_nRF52_Arduino/libraries/Wire/Wire_nRF52.cpp
T
strasharo 45188a647f Wire (nRF52): add timeout to endTransmission()/requestFrom() poll loops
endTransmission() and requestFrom() both spin on unbounded while(!EVENT)
loops waiting on the TWIM peripheral. Several of these loops - notably
the EVENTS_STOPPED wait - have no EVENTS_ERROR escape at all, so if the
hardware never raises the expected event (e.g. probing an I2C address
on a bus with nothing attached and no pull-ups), the call never
returns and the whole single-threaded firmware hangs forever.

Reported in #771 with the same root cause already identified in the
issue thread. Also affects boards that probe for an optional/absent
I2C device at boot before anything else initializes - e.g. MeshCore's
Xiao_nrf52 target, which runs an RTC autodiscovery scan in radio_init()
and hangs on every cold boot when no RTC is wired up (no serial, no
BLE - see meshcore-dev/MeshCore#2068).

Adds a bounded I2C_TWIM_TIMEOUT_MS (default 100ms, overridable) to
every wait loop in both functions. A timeout that occurs before the
hardware transaction actually completed is surfaced as a proper error
return (endTransmission: 4 "other error"; requestFrom: 0 bytes read)
rather than silently falling through to a success path - a timeout on
the address/data phase must not be reported as if a device ACKed.

Tested on a Seeed XIAO nRF52840 + Wio-SX1262 board that reliably hung
at boot (via MeshCore's RTC autodiscovery probe) after every power
cycle. With this patch the same probe now completes (with a timeout)
in well under a second per address instead of hanging indefinitely,
and the board boots and runs normally.
2026-12-02 12:22:38 +01:00

496 lines
13 KiB
C++
Executable File

/*
* TWI/I2C library for nRF5x
* Copyright (c) 2015 Arduino LLC. All rights reserved.
* Copyright (c) 2016 Sandeep Mistry All right reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(NRF52) || defined(NRF52_SERIES)
extern "C" {
#include <string.h>
}
#include <Arduino.h>
#include <wiring_private.h>
#include "Wire.h"
#include <Adafruit_TinyUSB.h> // for Serial
// Guards against a permanent MCU hang in the EVENTS_* poll loops below: on some
// boards, probing an I2C address with nothing attached (or without pull-ups)
// can leave the TWIM peripheral never raising the expected event or EVENTS_ERROR,
// so an unbounded while(!event) spins forever. See adafruit/Adafruit_nRF52_Arduino#771.
#ifndef I2C_TWIM_TIMEOUT_MS
#define I2C_TWIM_TIMEOUT_MS 100
#endif
static volatile uint32_t* pincfg_reg(uint32_t pin)
{
NRF_GPIO_Type * port = nrf_gpio_pin_port_decode(&pin);
return &port->PIN_CNF[pin];
}
TwoWire::TwoWire(NRF_TWIM_Type * p_twim, NRF_TWIS_Type * p_twis, IRQn_Type IRQn, uint8_t pinSDA, uint8_t pinSCL)
{
this->_p_twim = p_twim;
this->_p_twis = p_twis;
this->_IRQn = IRQn;
this->_uc_pinSDA = g_ADigitalPinMap[pinSDA];
this->_uc_pinSCL = g_ADigitalPinMap[pinSCL];
transmissionBegun = false;
}
void TwoWire::begin(void) {
//Main Mode
master = true;
*pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos)
| ((uint32_t)GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos)
| ((uint32_t)GPIO_PIN_CNF_PULL_Pullup << GPIO_PIN_CNF_PULL_Pos)
| ((uint32_t)GPIO_PIN_CNF_DRIVE_S0D1 << GPIO_PIN_CNF_DRIVE_Pos)
| ((uint32_t)GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
*pincfg_reg(_uc_pinSDA) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos)
| ((uint32_t)GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos)
| ((uint32_t)GPIO_PIN_CNF_PULL_Pullup << GPIO_PIN_CNF_PULL_Pos)
| ((uint32_t)GPIO_PIN_CNF_DRIVE_S0D1 << GPIO_PIN_CNF_DRIVE_Pos)
| ((uint32_t)GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
_p_twim->FREQUENCY = TWIM_FREQUENCY_FREQUENCY_K100;
_p_twim->ENABLE = (TWIM_ENABLE_ENABLE_Enabled << TWIM_ENABLE_ENABLE_Pos);
_p_twim->PSEL.SCL = _uc_pinSCL;
_p_twim->PSEL.SDA = _uc_pinSDA;
NVIC_ClearPendingIRQ(_IRQn);
NVIC_SetPriority(_IRQn, 3);
NVIC_EnableIRQ(_IRQn);
}
void TwoWire::begin(uint8_t address) {
//Secondary mode
master = false;
*pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos)
| ((uint32_t)GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos)
| ((uint32_t)GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos)
| ((uint32_t)GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos)
| ((uint32_t)GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
*pincfg_reg(_uc_pinSDA) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos)
| ((uint32_t)GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos)
| ((uint32_t)GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos)
| ((uint32_t)GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos)
| ((uint32_t)GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos);
_p_twis->ADDRESS[0] = address;
_p_twis->CONFIG = TWIS_CONFIG_ADDRESS0_Msk;
_p_twis->PSEL.SCL = _uc_pinSCL;
_p_twis->PSEL.SDA = _uc_pinSDA;
_p_twis->ORC = 0xff;
_p_twis->INTENSET = TWIS_INTEN_STOPPED_Msk | TWIS_INTEN_ERROR_Msk | TWIS_INTEN_WRITE_Msk | TWIS_INTEN_READ_Msk;
NVIC_ClearPendingIRQ(_IRQn);
NVIC_SetPriority(_IRQn, 3);
NVIC_EnableIRQ(_IRQn);
_p_twis->ENABLE = (TWIS_ENABLE_ENABLE_Enabled << TWIS_ENABLE_ENABLE_Pos);
}
void TwoWire::setClock(uint32_t baudrate) {
if (master) {
_p_twim->ENABLE = (TWIM_ENABLE_ENABLE_Disabled << TWIM_ENABLE_ENABLE_Pos);
uint32_t frequency;
if (baudrate <= 100000)
{
frequency = TWIM_FREQUENCY_FREQUENCY_K100;
}
else if (baudrate <= 250000)
{
frequency = TWIM_FREQUENCY_FREQUENCY_K250;
}
else
{
frequency = TWIM_FREQUENCY_FREQUENCY_K400;
}
_p_twim->FREQUENCY = frequency;
_p_twim->ENABLE = (TWIM_ENABLE_ENABLE_Enabled << TWIM_ENABLE_ENABLE_Pos);
}
}
void TwoWire::setPins(uint8_t pinSDA, uint8_t pinSCL)
{
this->_uc_pinSDA = g_ADigitalPinMap[pinSDA];
this->_uc_pinSCL = g_ADigitalPinMap[pinSCL];
}
void TwoWire::end() {
if (master)
{
_p_twim->ENABLE = (TWIM_ENABLE_ENABLE_Disabled << TWIM_ENABLE_ENABLE_Pos);
}
else
{
_p_twis->ENABLE = (TWIS_ENABLE_ENABLE_Disabled << TWIS_ENABLE_ENABLE_Pos);
}
}
uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit)
{
if(quantity == 0)
{
return 0;
}
size_t byteRead = 0;
rxBuffer.clear();
_p_twim->ADDRESS = address;
_p_twim->TASKS_RESUME = 0x1UL;
_p_twim->RXD.PTR = (uint32_t)rxBuffer._aucBuffer;
_p_twim->RXD.MAXCNT = quantity;
_p_twim->TASKS_STARTRX = 0x1UL;
bool timed_out = false;
uint32_t wait_start = millis();
while(!_p_twim->EVENTS_RXSTARTED && !_p_twim->EVENTS_ERROR) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; }
}
_p_twim->EVENTS_RXSTARTED = 0x0UL;
if (!timed_out) {
wait_start = millis();
while(!_p_twim->EVENTS_LASTRX && !_p_twim->EVENTS_ERROR) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; }
}
}
_p_twim->EVENTS_LASTRX = 0x0UL;
if (stopBit || _p_twim->EVENTS_ERROR || timed_out)
{
_p_twim->TASKS_STOP = 0x1UL;
wait_start = millis();
while(!_p_twim->EVENTS_STOPPED) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break;
}
_p_twim->EVENTS_STOPPED = 0x0UL;
}
else
{
_p_twim->TASKS_SUSPEND = 0x1UL;
wait_start = millis();
while(!_p_twim->EVENTS_SUSPENDED) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break;
}
_p_twim->EVENTS_SUSPENDED = 0x0UL;
}
if (_p_twim->EVENTS_ERROR)
{
_p_twim->EVENTS_ERROR = 0x0UL;
}
// 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) {
return 0;
}
byteRead = rxBuffer._iHead = _p_twim->RXD.AMOUNT;
return byteRead;
}
uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity)
{
return requestFrom(address, quantity, true);
}
void TwoWire::beginTransmission(uint8_t address) {
// save address of target and clear buffer
txAddress = address;
txBuffer.clear();
transmissionBegun = true;
}
// Errors:
// 0 : Success
// 1 : Data too long
// 2 : NACK on transmit of address
// 3 : NACK on transmit of data
// 4 : Other error
uint8_t TwoWire::endTransmission(bool stopBit)
{
transmissionBegun = false ;
// Start I2C transmission
_p_twim->ADDRESS = txAddress;
// just in case twi is stopped by bus error such as secondary device reset/stalled without replying ACK/NACK
_p_twim->EVENTS_STOPPED = 0x0UL;
_p_twim->TASKS_RESUME = 0x1UL;
_p_twim->TXD.PTR = (uint32_t)txBuffer._aucBuffer;
_p_twim->TXD.MAXCNT = txBuffer.available();
_p_twim->TASKS_STARTTX = 0x1UL;
bool timed_out = false;
uint32_t wait_start = millis();
while(!_p_twim->EVENTS_TXSTARTED && !_p_twim->EVENTS_ERROR) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; }
}
_p_twim->EVENTS_TXSTARTED = 0x0UL;
if (!timed_out && txBuffer.available()) {
wait_start = millis();
while(!_p_twim->EVENTS_LASTTX && !_p_twim->EVENTS_ERROR) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) { timed_out = true; break; }
}
}
_p_twim->EVENTS_LASTTX = 0x0UL;
if (stopBit || _p_twim->EVENTS_ERROR || timed_out)
{
_p_twim->TASKS_STOP = 0x1UL;
wait_start = millis();
while(!_p_twim->EVENTS_STOPPED) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break;
}
_p_twim->EVENTS_STOPPED = 0x0UL;
}
else
{
_p_twim->TASKS_SUSPEND = 0x1UL;
wait_start = millis();
while(!_p_twim->EVENTS_SUSPENDED) {
if (millis() - wait_start > I2C_TWIM_TIMEOUT_MS) break;
}
_p_twim->EVENTS_SUSPENDED = 0x0UL;
}
if (_p_twim->EVENTS_ERROR)
{
_p_twim->EVENTS_ERROR = 0x0UL;
uint32_t error = _p_twim->ERRORSRC;
_p_twim->ERRORSRC = error;
if (error == TWIM_ERRORSRC_ANACK_Msk)
{
return 2;
}
else if (error == TWIM_ERRORSRC_DNACK_Msk)
{
return 3;
}
else
{
return 4;
}
}
// hardware never raised EVENTS_ERROR but also never completed the transaction -
// report it as a failure so callers (e.g. an I2C bus scan) don't mistake a dead
// bus for a device that ACKed. See adafruit/Adafruit_nRF52_Arduino#771.
if (timed_out)
{
return 4;
}
return 0;
}
uint8_t TwoWire::endTransmission()
{
return endTransmission(true);
}
size_t TwoWire::write(uint8_t ucData)
{
// No writing, without begun transmission or a full buffer
if ( !transmissionBegun || txBuffer.isFull() )
{
return 0 ;
}
txBuffer.store_char( ucData ) ;
return 1 ;
}
size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
//Try to store all data
for(size_t i = 0; i < quantity; ++i)
{
//Return the number of data stored, when the buffer is full (if write return 0)
if(!write(data[i]))
return i;
}
//All data stored
return quantity;
}
int TwoWire::available(void)
{
return rxBuffer.available();
}
int TwoWire::read(void)
{
return rxBuffer.read_char();
}
int TwoWire::peek(void)
{
return rxBuffer.peek();
}
void TwoWire::flush(void)
{
// Do nothing, use endTransmission(..) to force
// data transfer.
}
void TwoWire::onReceive(void(*function)(int))
{
onReceiveCallback = function;
}
void TwoWire::onRequest(void(*function)(void))
{
onRequestCallback = function;
}
void TwoWire::onService(void)
{
if (_p_twis->EVENTS_WRITE)
{
_p_twis->EVENTS_WRITE = 0x0UL;
receiving = true;
rxBuffer.clear();
_p_twis->RXD.PTR = (uint32_t)rxBuffer._aucBuffer;
_p_twis->RXD.MAXCNT = sizeof(rxBuffer._aucBuffer);
_p_twis->TASKS_PREPARERX = 0x1UL;
}
if (_p_twis->EVENTS_READ)
{
_p_twis->EVENTS_READ = 0x0UL;
receiving = false;
transmissionBegun = true;
txBuffer.clear();
if (onRequestCallback)
{
onRequestCallback();
}
transmissionBegun = false;
_p_twis->TXD.PTR = (uint32_t)txBuffer._aucBuffer;
_p_twis->TXD.MAXCNT = txBuffer.available();
_p_twis->TASKS_PREPARETX = 0x1UL;
}
if (_p_twis->EVENTS_STOPPED)
{
_p_twis->EVENTS_STOPPED = 0x0UL;
if (receiving)
{
int rxAmount = _p_twis->RXD.AMOUNT;
rxBuffer._iHead = rxAmount;
if (onReceiveCallback)
{
onReceiveCallback(rxAmount);
}
}
}
if (_p_twis->EVENTS_ERROR)
{
_p_twis->EVENTS_ERROR = 0x0UL;
uint32_t error = _p_twis->ERRORSRC;
_p_twis->ERRORSRC = error;
_p_twis->TASKS_STOP = 0x1UL;
}
}
#if WIRE_INTERFACES_COUNT > 0
TwoWire Wire(NRF_TWIM0, NRF_TWIS0, SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQn, PIN_WIRE_SDA, PIN_WIRE_SCL);
extern "C"
{
void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler(void)
{
#if CFG_SYSVIEW
SEGGER_SYSVIEW_RecordEnterISR();
#endif
Wire.onService();
#if CFG_SYSVIEW
SEGGER_SYSVIEW_RecordExitISR();
#endif
}
}
#endif
#if WIRE_INTERFACES_COUNT > 1
TwoWire Wire1(NRF_TWIM1, NRF_TWIS1, SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQn, PIN_WIRE1_SDA, PIN_WIRE1_SCL);
extern "C"
{
void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler(void)
{
#if CFG_SYSVIEW
SEGGER_SYSVIEW_RecordEnterISR();
#endif
Wire1.onService();
#if CFG_SYSVIEW
SEGGER_SYSVIEW_RecordExitISR();
#endif
}
}
#endif
#endif // NRF52_SERIES