Arduino I2C Reset

From time to time you may observe that I2C may hang.

This can be a result of reset of your arduino/microcontroller in the middle of a transmission.

Local copy of code (for Arduino)

#define SDAPIN 18
#define CLKPIN 19

#include <Wire.h>

void i2cRecovery()
{
   Serial.println("Starting I2C bus recovery");
  delay(2000);
  //try i2c bus recovery at 100kHz = 5uS high, 5uS low
  pinMode(SDAPIN, OUTPUT);//keeping SDA high during recovery
  digitalWrite(SDAPIN, HIGH);
  pinMode(CLKPIN, OUTPUT);
  for (int i = 0; i < 10; i++) { //9nth cycle acts as NACK
    digitalWrite(CLKPIN, HIGH);
    delayMicroseconds(5);
    digitalWrite(CLKPIN, LOW);
    delayMicroseconds(5);
  }

  //a STOP signal (SDA from low to high while CLK is high)
  digitalWrite(SDAPIN, LOW);
  delayMicroseconds(5);
  digitalWrite(CLKPIN, HIGH);
  delayMicroseconds(2);
  digitalWrite(SDAPIN, HIGH);
  delayMicroseconds(2);
  //bus status is now : FREE

  Serial.println("bus recovery done, starting scan in 2 secs");
  //return to power up mode
  pinMode(SDAPIN, INPUT);
  pinMode(CLKPIN, INPUT);
  delay(2000);
   Wire.begin();
  //only pins: no signal on clk and sda
  //only begin: no signal on clk, no signal on sda


}

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

Another different example

From secondary src there is a little larger code.

I think the code above is ok, but this code is a little bit more robust.

Disclaimer: I have not testet the code below.

(i2creset2.ino: click for open/close)

(i2creset2.ino as raw)