import machine, time
from machine import Pin, ADC
import dht
# ---------------------
# Pins
# ---------------------
lamp = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_UP)
ldr = ADC(Pin(26))
pir = Pin(13, Pin.IN)
buzzer = Pin(9, Pin.OUT)
# ---------------------
# State
# ---------------------
lamp_state = False
# ---------------------
# Helper functions
# ---------------------
def toggle_lamp():
global lamp_state
lamp_state = not lamp_state
lamp.value(lamp_state)
print("Lamp is", "ON" if lamp_state else "OFF")
def read_environment():
light = ldr.read_u16() # 0-65535
motion = pir.value()
print(f"Light: {light}, Motion: {motion}")
return light, motion
def notify():
buzzer.value(1)
time.sleep(0.2)
buzzer.value(0)
# ---------------------
# Main Loop
# ---------------------
while True:
# Manual toggle
if button.value() == 0:
toggle_lamp()
time.sleep(0.3) # debounce
# Automatic light control
light, motion = read_environment()
if light < 30000 and motion: # Dark and someone present
if not lamp_state:
lamp.value(1)
lamp_state = True
notify()
else:
if lamp_state:
lamp.value(0)
lamp_state = False
time.sleep(0.5)