import machine
import time
# Initialize components
pir_sensor = machine.Pin(14, machine.Pin.IN) # PIR on GPIO 14
ldr = machine.ADC(machine.Pin(34)) # LDR on GPIO 34 (Analog)
ldr.atten(machine.ADC.ATTN_11DB) # Full-range voltage for ESP32
relay = machine.Pin(13, machine.Pin.OUT) # Relay control on GPIO 13
button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP) # Button on GPIO 12
# Thresholds
light_threshold = 2000 # Adjust for your lighting conditions
# Initial states
light_on = False
# Function to turn on the light
def turn_on_light():
global light_on
relay.on() # Activate the relay to turn the light on
light_on = True
print("Light ON")
# Function to turn off the light
def turn_off_light():
global light_on
relay.off() # Deactivate the relay to turn the light off
light_on = False
print("Light OFF")
# Main loop
while True:
# Read the LDR value (light level)
light_level = ldr.read()
print("Light Level:", light_level)
# Detect motion
if pir_sensor.value() == 1 and light_level < light_threshold:
if not light_on:
turn_on_light() # Turn on the light if motion is detected and it's dark
else:
if light_on:
turn_off_light() # Turn off the light if no motion or enough ambient light
# Manual override using the push button
if button.value() == 0: # Button pressed
if light_on:
turn_off_light() # Manually turn off the light
else:
turn_on_light() # Manually turn on the light
time.sleep(0.5) # Debounce delay for the button
time.sleep(0.1) # Short delay for loop