from machine import Pin, ADC
import time
import math
# Constant
GAMMA = 0.7
RL10 = 50 # Resistance at 10 lux
led1 = Pin(17, Pin.OUT)
led2 = Pin(16, Pin.OUT)
led3 = Pin(15, Pin.OUT)
state = True
# Configure the LDR pin (ADC channel)
ldr_pin = ADC(Pin(34)) # GPIO 34
ldr_pin.atten(ADC.ATTN_11DB) # Full-scale voltage 0-3.3V
ldr_pin.width(ADC.WIDTH_12BIT) # 12-bit resolution (0-4095)
def calculate_lux(analog_value):
# Convert the analog value into voltage (assuming 12-bit ADC and 3.3V range)
voltage = analog_value / 4095.0 * 3.3
# Calculate the resistance of the LDR
resistance = 2000 * voltage / (1 - voltage / 3.3)
# Calculate lux value using the formula
lux = math.pow(RL10 * 1e3 * math.pow(10, GAMMA) / resistance, (1 / GAMMA))/1.808
return lux
while True:
# Read the analog value from the LDR
analog_value = ldr_pin.read()
# Calculate the lux value
lux = calculate_lux(analog_value)
print("Lux:", lux)
# Print lighting condition
if (lux < 1000):
print("Oscuro")
led1.value(state)
led2.value(not state)
led3.value(not state)
elif (lux < 10000):
print("Parcialmente iluminado")
led1.value(not state)
led2.value(state)
led3.value(not state)
else:
print("Totalmente iluminado")
led1.value(not state)
led2.value(not state)
led3.value(state)
time.sleep(1)