from machine import Pin, ADC
import time
# Setup ADC for LDR sensor
ldr_sensor = ADC(Pin(26)) # LDR AO connected to GPIO26 (ADC0)
# Setup digital input pin for PIR sensor
pir_sensor = Pin(14, Pin.IN) # PIR DO connected to GPIO14
# Setup LED on GPIO16
led = Pin(16, Pin.OUT)
# Function to convert ADC reading to lux (simple linear conversion, needs calibration)
def adc_to_lux(adc_value):
# This is a placeholder conversion. Calibration needed for accurate lux measurement.
# For example: lux = 1000 / (adc_value / 65535) (Not actual formula)
return (65535 - adc_value) / 65535 * 1000
# Main loop
while True:
# Read the analog value from the LDR
ldr_value = ldr_sensor.read_u16() # Read ADC value (0 to 65535)
# Convert ADC value to lux
lux = adc_to_lux(ldr_value)
# Read the digital output from PIR sensor
pir_value = pir_sensor.value()
# Print sensor values (for debugging)
print('LDR Light Level (Lux):', lux)
print('PIR Sensor Output:', pir_value)
# Control LED based on sensor values
# Turn LED ON if the light level is below a certain threshold or if PIR sensor detects motion
if lux < 200 or pir_value == 1: # Adjust lux threshold as needed
led.value(1) # Turn LED ON
else:
led.value(0) # Turn LED OFF
time.sleep(1) # Delay to avoid rapid toggling