Skip to content

Commit

Permalink
added i2c recovery code from esp8266/Arduino#1025
Browse files Browse the repository at this point in the history
  • Loading branch information
merlokk committed Jul 25, 2018
1 parent c114de6 commit 2b94642
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions ESP8266CO2PM25/ESP8266CO2PM25.ino
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
#define LED2 14 // led 2
#define LEDON LOW
#define LEDOFF HIGH
#define SDAPIN 4
#define CLKPIN 5

// objects
SoftwareSerial mSerial1(13, 15); // RX, TX (13,15)
Expand All @@ -62,6 +64,49 @@ piTimer ptimer;
hdc1080 hdc;
bme280 bme;

void i2crecovery() {
DEBUG_PRINTLN(F("I2C bus recovery..."));
delay(500);
//try i2c bus recovery at 100kHz = 5uS high, 5uS low
pinMode(SDAPIN, OUTPUT_OPEN_DRAIN);//keeping SDA high during recovery
pinMode(CLKPIN, OUTPUT_OPEN_DRAIN);
digitalWrite(SDAPIN, HIGH);
digitalWrite(CLKPIN, HIGH);

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

//return to power up mode
pinMode(SDAPIN, INPUT_PULLUP);
pinMode(CLKPIN, INPUT_PULLUP);
delay(500);

bool isok = digitalRead(SDAPIN) && digitalRead(CLKPIN);
if (!digitalRead(SDAPIN))
DEBUG_PRINTLN(F("I2C bus error: SDA still LOW."));
if (!digitalRead(CLKPIN))
DEBUG_PRINTLN(F("I2C bus error: CLK still LOW."));

Wire.pins(SDAPIN, CLKPIN);
Wire.begin(SDAPIN, CLKPIN);

if (isok)
DEBUG_PRINTLN(F("I2C bus recovery complete."));
}

///////////////////////////////////////////////////////////////////////////
// Setup() and loop()
///////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -100,8 +145,8 @@ void setup() {
DEBUG_PRINTLN(str);

// hdc1080
Wire.pins(4, 5); // (SDA, SCL) changes default values
Wire.begin(4, 5); // (SDA, SCL)
Wire.pins(SDAPIN, CLKPIN); // (SDA, SCL) changes default values
Wire.begin(SDAPIN, CLKPIN); // (SDA, SCL)
hdc.begin(&logger);
hdc.SetMQTT(&mqtt, SF("THConnected"), SF("Temperature"), SF("Humidity"), SF("Heater"));

Expand Down

0 comments on commit 2b94642

Please sign in to comment.