import machine
import utime
# Pin setup for Raspberry Pi Pico
PIR_PIN = machine.Pin(17, machine.Pin.IN) # PIR sensor on GPIO 17
RELAY_PIN = machine.Pin(8, machine.Pin.OUT) # Relay control on GPIO 27
LDR_PIN = machine.ADC(28) # LDR connected to ADC pin (GPIO 26)
# Function to read LDR value
def read_ldr():
# Read the analog value from the LDR
ldr_value = LDR_PIN.read_u16()
return ldr_value
# Main loop
try:
while True:
# Check if motion is detected by PIR sensor
if PIR_PIN.value() == 1: # Motion detected
print("Motion Detected!")
# Read LDR value to check light level
light_level = read_ldr()
print("LDR value:", light_level)
# If the light level is below a threshold (dark), turn on the light
if light_level < 30000: # Adjust threshold as needed
print("It's dark, turning ON the light.")
RELAY_PIN.on() # Turn on the light
else:
print("It's bright, keeping the light OFF.")
RELAY_PIN.off() # Turn off the light
else:
print("No motion detected, keeping the light OFF.")
RELAY_PIN.off() # Turn off the light when no motion is detected
utime.sleep(1) # Wait for 1 second before checking again
except KeyboardInterrupt:
print("Program terminated.")
RELAY_PIN.off() # Turn off the light on exit