claws / BH1750

An Arduino library for the digital light sensor breakout boards containing the BH1750FVI IC
MIT License
249 stars 108 forks source link

Better error handling if not two bytes are available for read. #41

Open bjung82 opened 6 years ago

bjung82 commented 6 years ago

Do not tear down I2C bus forever if not 2 bytes are available for read.

This is sometimes the case, and after such an unsuccessful read the I2C bus was held down forever and stopped working (for all other components on the bus, too!)

bjung82 commented 6 years ago

I also changed

include "Wire.h" to

include

I use the sensor on an ESP32 - on arduino it seems like there is no "reset()" available? The "reset" fixed the sporadic issues I had in my setup ESP32+BH1750.

coelner commented 6 years ago

the Wire.reset() is defined in the specific library (https://github.com/espressif/arduino-esp32/pull/678) therefore we need a #ifdeffor each architecture. ESP8266 issue: https://github.com/esp8266/Arduino/issues/1025

But it is nothing we should do in this library. It is part of the SoC and the handling over there. the library for the architecture needs a fix.

Please try this instead:

// Read two bytes from the sensor, which are low and high parts of the sensor
// value
if (Wire.requestFrom(BH1750_I2CADDR, 2) == 2) {
    level = __wire_read();
    level <<= 8;
    level |= __wire_read();
}
else {
//do some error routine like return max uint16 value.
  Serial.print(F("[BH1750] i2c read error. Not enough bytes received! "));
  return 65535;
}
guillaume-dorczynski commented 6 years ago

For anyone having I2C issues on ESP32, try this: https://github.com/stickbreaker/arduino-esp32/issues/16#issuecomment-365801770 . I had problems with reading DS3231, I2C was crashing and required a hardware reset. Since I use his modified files I have yet to see another I2C error! I see some debug message about I2C, but it's always recovered and working.