Miceuz / i2c-moisture-sensor

I2C based soil moisture sensor
Apache License 2.0
240 stars 72 forks source link

Reading capacitance fails on esp32 after sleeping #42

Closed ethanhjennings closed 1 year ago

ethanhjennings commented 1 year ago

Hi, loving the sensor. I'm using the I2CSoilMoistureSensor library but I can't get seem to get the sleep() method to work on an esp32. After sleeping all subsequent returned values are 65535 and I get an i2c error: requestFrom(): i2cRead returned Error 263 until I do a hard reset by cutting power to the sensor.

Example code with issue:

Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
Wire.setClock(50000);

I2CSoilMoistureSensor moistureSensor;
moistureSensor.begin(true);

while (true) {
    auto moisture = moistureSensor.getCapacitance();
    Serial.println(moisture);

    moistureSensor.sleep();
    delay(1000);
}

Output:

258
[  4099][E][Wire.cpp:513] requestFrom(): i2cRead returned Error 263
65535
[  8122][E][Wire.cpp:513] requestFrom(): i2cRead returned Error 263
65535
[ 12145][E][Wire.cpp:513] requestFrom(): i2cRead returned Error 263
65535
[ 16167][E][Wire.cpp:513] requestFrom(): i2cRead returned Error 263
65535
...

When I remove the moistureSensor.sleep() line and do a hard reset with a power cut it works fine again. Soft rebooting with moistureSensor.resetSensor() doesn't work either.

Miceuz commented 1 year ago

Hi, thanks for the report,

What version of ESP32 are you using? This might be related to https://github.com/espressif/esp-idf/issues/4173 - 13ms max clock stretching limit on older ESP32 chip versions.

ethanhjennings commented 1 year ago

I think this is indeed the problem because I'm using a regular ESP32 (not ESP32-S2 or S3). I'm going to try working around this with bit banging or a software i2c library (maybe then switching to using hardware i2c once it's awake).