Created
April 23, 2021 16:27
-
-
Save jeremysinger/3e1dfa1722cea434ac8e2b2df6fed5ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from machine import Pin, I2C | |
import time | |
_DEVICE_ADDR = 0x23 # default I2C address for BH1750 light sensor | |
class LightSensor(): | |
#Light Modes | |
OP_SINGLE_HRES1 = 0x20 | |
OP_SINGLE_HRES2 = 0x21 | |
OP_SINGLE_LRES = 0x23 | |
DELAY_HMODE = 180 # 180ms in H-mode | |
DELAY_LMODE = 24 # 24ms in L-mode | |
i2c = None | |
i2c_address = 0 | |
i2c_transaction_length = 0 | |
mode = None | |
def get_sensor_value(self): | |
if self.i2c != None: | |
self.i2c.writeto(self.i2c_address, b"\x00") # power off | |
self._power_up() | |
self.set_mode(self.OP_SINGLE_HRES2) # highest accuracy | |
results = self.i2c.readfrom(self.i2c_address, self.i2c_transaction_length) | |
if results != None and len(results) == self.i2c_transaction_length: | |
ch0 = results[0] | |
ch1 = results[1] | |
return self._data_to_lux(ch0, ch1) | |
else: | |
print ("Problem with response from i2c service: %s" % results) | |
return None | |
def _power_up(self): | |
self.i2c.writeto(self.i2c_address, b"\x01") # power on | |
self.i2c.writeto(self.i2c_address, b"\x07") # reset | |
def set_mode(self, mode): | |
self.mode = mode | |
self.i2c.writeto(self.i2c_address, bytes([self.mode])) # set measurement mode | |
time.sleep_ms(self.DELAY_LMODE if mode == self.OP_SINGLE_LRES else self.DELAY_HMODE) | |
def _data_to_lux(self, ch0, ch1): | |
lux = 0 | |
if (ch0 == 0): | |
return lux | |
factor = 2.0 if self.mode==self.OP_SINGLE_HRES2 else 1.0 | |
lux = (ch0<<8 | ch1) / (1.2 * factor) | |
return lux | |
def __init__(self): | |
self.i2c = I2C(scl=Pin(5), sda=Pin(4)) | |
self.i2c_address = _DEVICE_ADDR | |
self.i2c_transaction_length = 2 | |
def main(): | |
while True: | |
time.sleep(5) | |
sensor = LightSensor() | |
print (sensor.get_sensor_value()) | |
if (__name__ == "__main__"): | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment