from machine import Pin, ADC
import time
# Define pin for LDR (Light Dependent Resistor) and LED
ldr_pin = 27 # GPIO pin connected to the LDR
led_pin = 1 # GPIO pin connected to the LED
# Initialize ADC for reading analog values from LDR
adc = ADC(Pin(ldr_pin))
# Initialize LED pin as an output
led = Pin(led_pin, Pin.OUT)
# Function to check ambient light level
def check_light_level():
# Read analog value from LDR
light_value = adc.read_u16()
# Convert analog value to a light level (adjust the threshold as needed)
if light_value > 20000: # Adjust threshold based on your environment
return True # Low light condition
else:
return False # Sufficient light condition
# Main loop
while True:
# Check ambient light level
low_light = check_light_level()
# If low light condition detected, turn on the LED
if low_light:
led.value(1) # Turn on the LED
else:
led.value(0) # Turn off the LED
time.sleep(0.5) # Adjust delay as needed