From 2b94642d89ba552c1a9f6fdf9d7da96b51df152a Mon Sep 17 00:00:00 2001 From: merlokk Date: Wed, 25 Jul 2018 12:34:12 +0300 Subject: [PATCH] added i2c recovery code from https://github.com/esp8266/Arduino/issues/1025 --- ESP8266CO2PM25/ESP8266CO2PM25.ino | 49 +++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/ESP8266CO2PM25/ESP8266CO2PM25.ino b/ESP8266CO2PM25/ESP8266CO2PM25.ino index 1102251..46bfb1e 100644 --- a/ESP8266CO2PM25/ESP8266CO2PM25.ino +++ b/ESP8266CO2PM25/ESP8266CO2PM25.ino @@ -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) @@ -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() /////////////////////////////////////////////////////////////////////////// @@ -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"));