Skip to content

Ard Wire Timeout

DodaTech 1 min read

In this tutorial, you'll learn about Arduino I2C Bus Hangs. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

The I2C bus locks up and the program stops responding.

Quick Fix

Wrong

Wire.beginTransmission(addr);  // Hangs if slave not responding
Program freezes when the I2C bus is locked.
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin();
  Wire.setWireTimeout(50000, true);  // 50 ms timeout, reset on timeout
}

void safeI2CWrite(byte addr, byte reg, byte val) {
  Wire.beginTransmission(addr);
  Wire.write(reg);
  Wire.write(val);
  byte err = Wire.endTransmission();
  if (err) {
    Serial.print("I2C error: ");
    Serial.println(err);
    Wire.clearWireTimeoutFlag();  // Clear timeout flag
  }
}

void loop() {
  safeI2CWrite(0x3C, 0x00, 0x01);
  delay(100);
}
I2C error: 2  (or success). Program continues running.

Prevention

Modern Wire libraries (Arduino SAMD, ESP32) support setWireTimeout(). On AVR, the Wire library does not have timeout support. Use a watchdog timer on AVR: enable WDT and reset if the I2C operation takes too long. Alternatively, use a state machine with timeouts.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Does AVR Wire library have timeout?

No. The standard AVR Wire library blocks indefinitely if the bus hangs. External watchdog or manual reset is needed.

What is Wire.setWireTimeout()?

A SAMD/ESP32-specific function. Arguments: timeout in microseconds, resetBus (bool). If the bus is hung for longer than timeout, it resets the peripheral.

How do I recover from I2C hang?

Call Wire.end() then Wire.begin() to reinitialize. Toggle SCL pin manually 10 times to release stuck slaves. Or reset the device.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro