Library for BH1750 I2C light sensor. Supports autoranging! True to datasheet. (beware: calls are blocking at the moment)

So there is this light sensor (like the one present in any phone), BH1750. I got mine soldered to some nice breakout board.

Few facts about this library: it is very true to the datasheet. it takes advantage of MTreg (time of measurement), which lets you to increase resolution up to 3.86 times at the cost of time it takes to perform a measurement. Measurement is blocking ! I've also implemented an autoranging feature. Just like in those fancy multimeters! It works as follows, thresholds are hard-coded:

  1. <5 lx switches to Hi-res2 and to max MTreg (so measurement time is like 500ms)
  2. <1000 lx Hi-res, MTreg default.
  3. above there is no real need for Hi-res, so Low-res mode is used.

Last note: I greatly recommend you to use log10 value of the luminosity data. it makes much more sense, because it becomes linear.

Revision:
0:a7280a6c3c9b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/BH1750.h	Tue Aug 22 00:29:50 2017 +0000
@@ -0,0 +1,46 @@
+#include "mbed.h"
+
+#ifndef BH1750_h
+#define BH1750_h
+
+class BH1750
+{
+private:
+    static const char ADDRESS_LOW = 0x23;
+    static const char ADDRESS_HIGH = 0x5C;
+    static const char powerOn_cmd = 0b00000001;
+    static const char powerDown_cmd = 0b00000000;
+    static const char reset_cmd = 0b00000111;
+
+    static const char L_RES_MEASUREMENT_TIME = 12; // ms
+    static const char H_RES_MEASUREMENT_TIME = 120; // ms
+
+    char _address;
+    char _currentMode;
+    char _currentMtreg;
+    unsigned int _waitForMeasurement;
+    bool _autoModeAdjustSwitch;
+    I2C &_i2c_inst;
+
+    void _sendCommand(char);
+
+    unsigned int _readRaw();
+    bool _autoModeAdjust(float measurement); // returns if adjusted or left alone      
+    float _readSingle();
+public:
+    static const char CONTINOUS_L_RES_CMD =  0b00010011;
+    static const char CONTINOUS_H_RES_CMD =  0b00010000;
+    static const char CONTINOUS_H2_RES_CMD = 0b00010001;
+    static const char ONETIME_L_RES_CMD = 0b01000011;
+    static const char ONETIME_H_RES_CMD = 0b01000000;
+    static const char ONETIME_H2_RES_CMD = 0b01000001;
+    static const char DEFAULTMTREG = 69;
+
+    BH1750(I2C & , bool autoRange = false, bool addressPinState = false);
+    void power(bool); // power on or off.
+    float read();   // main function to read a value (or rather perform a read when in one_time mode)
+    void setMode(const char); // set mode. datasheet lists L, H, H2 resolution modes in continous and one_time versions
+    void setMtreg(char);    // correcting measurement time. can be used to increase precision by a factor of 3.86 at the cost of time
+};
+
+#endif
\ No newline at end of file