- Code: Select all | TOGGLE FULL SIZE
from Adafruit_I2C import Adafruit_I2C
import time
import math
address = 0x39
i2c = Adafruit_I2C(address)
control_on = 0x03
control_off = 0x00
def enable():
print("enabling")
i2c.write8(0x80, control_on)
def disable():
print("disabling")
i2c.write8(0x80, control_off)
def getLight():
ch0 = i2c.readU16(0xAC) ##Broad spectrum photo-diode
ch1 = i2c.readU16(0xAE) ##IR spectrum photo-diode
return ch0,ch1
def getLux():
ch0,ch1 = getLight()
ratio = 0
lux = 0
tag = 0
if ch0 > 0:
ratio = float(ch1)/float(ch0)
if ch0 == 0:
ratio = 1.35
if ratio > 1.30:
lux = 0
tag = 0
elif ratio > 0.80:
lux = (0.00146 * ch0) - (0.00112 * ch1)
tag = 4
elif ratio > 0.61:
lux = (0.0128 * ch0) - (0.0153 * ch1)
tag =3
elif ratio > 0.50:
lux = (0.0224 * ch0) - (0.031 * ch1)
tag = 2
elif ratio <= 0.50:
lux = (0.0304 * ch0) - (0.062 * ch0 * ((ch1/ch0) ** 1.4))
tag =1
return lux, ratio, tag, ch0, ch1
enable()
#time.sleep(0.4)
light = getLight()
lux = getLux()
print(light)
print(lux)
#disable()
getLux() returns lux, ratio, a debugging tag, and the channel0 and channel1 raw values. I'm getting some bizarre readings at times. If I shine my lights directly on the sensor, occasionally I get readings of 0 lux. One of the lights is a SureFire, a pretty bright light.
I need to clean the code up, and implement DriverBlock's suggestion of implementing constants. I'm pretty sure the if/elif loop describes the function in the datasheet.
I wrote this in Python 3. I think the only thing that needs to be changed for Python 2.x functionality is to switch the print() statements to Python 2.x print statements.