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.
Right
#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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro