import machine
from utime import sleep
# Constants
V_in = 3.3
ADC_MAX_VALUE = 65535
R_fixed = 10000 # Fixed resistor value in ohms
threshold = 5000 # ADC threshold
# Initialize the LED and ADC pins
led_pin = machine.Pin(27, machine.Pin.OUT)
ldr = machine.ADC(28)
def adc_to_voltage(adc_value):
"""Convert ADC reading to voltage."""
return adc_value * V_in / ADC_MAX_VALUE
def voltage_to_resistance(voltage):
"""Convert voltage to LDR resistance."""
return R_fixed * (V_in / voltage - 1)
def resistance_to_lux(resistance):
"""Convert LDR resistance to lux value."""
return 500 / (resistance / 1000) # Example conversion, adjust based on LDR datasheet
while True:
# Read the LDR value
ldr_value = ldr.read_u16()
voltage = adc_to_voltage(ldr_value)
resistance = voltage_to_resistance(voltage)
lux = resistance_to_lux(resistance)
if ldr_value > threshold:
led_pin.on()
elif ldr_value < threshold:
led_pin.off()
sleep(0.25)