from machine import ADC, Pin
import math,time
led_pins = [13,12,14,27,26,25,33,32,23,22]
leds = [Pin(pin, Pin.OUT) for pin in led_pins]
def clear_leds():
for led in leds:
led.value(0)
def light_up_to(n):
clear_leds()
for i in range(n):
leds[i].value(1)
adc = ADC(Pin(2))
adc.atten(ADC.ATTN_11DB)
rl10 = 50e3 #LDR resistance at 10lux
gamma = 0.7 #log(Ra/Rb) / log(La/Lb)
#R2 = R1 * Vout / (Vin - Vout)
def calculate_resistance():
value = adc.read()
voltage_ratio = value / (4095 - value)
return 10e3 * voltage_ratio
#R = R_10 * (lux / 10) ^ -γ => R10/R=(10/lux)^−γ => R/R10=(10/lux)^γ => (R10/R)^(1/γ)=10/lux => lux=10*(R10/R)^(1/γ)
def calculate_lux(resistance):
return 10 * math.pow(rl10/resistance, 1/gamma)
points = [
(0.1, 1.25e6),
(1, 250e3),
(10, 50e3),
(50, 16.2e3),
(100, 9.98e3),
(400, 3.78e3),
(1000, 1.99e3),
(10000, 397),
(100000, 79)
]
#y = y1 + ((x - x1) / (x2 - x1)) * (y2 - y1)
def linear_interpolation(resistance):
if resistance >= 1.25e6:
light_up_to(1)
return 0.1
elif resistance <= 79:
light_up_to(10)
return 100000
for i in range(len(points) - 1):
if points[i+1][1] <= resistance <= points[i][1]:
x1, y1 = points[i]
x2, y2 = points[i + 1]
light_up_to(i + 2)
return x1 + ((resistance - y1) / (y2 - y1)) * (x2 - x1)
while 1:
resistance = calculate_resistance()
print('Lux:', round(calculate_lux(resistance),1) ,'\tInterpolated Lux:', round(linear_interpolation(resistance),1))
time.sleep(1)