from machine import Pin, ADC
import time
# ---------------- PIN CONFIG ----------------
LDR_PIN = 34
PIR_PIN = 27
TOUCH_PIN = 14
RELAY_PIN = 26
# ---------------- SETTINGS ----------------
DARK_THRESHOLD = 1500 # Adjust after testing
INTERACTION_TIME = 30 # seconds
# ---------------- HARDWARE INIT ----------------
pir = Pin(PIR_PIN, Pin.IN)
touch = Pin(TOUCH_PIN, Pin.IN)
relay = Pin(RELAY_PIN, Pin.OUT)
relay.value(0)
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB)
ldr.width(ADC.WIDTH_12BIT)
# ---------------- STATE VARIABLES ----------------
system_active = False
lamp_on = False
pir_start_time = 0
print("Smart Study Table – Smart Lamp Module Started")
# ---------------- FUNCTIONS ----------------
def lamp_on_fn():
global lamp_on
relay.value(1)
lamp_on = True
print("Lamp ON (Dark detected)")
def lamp_off_fn():
global lamp_on
relay.value(0)
lamp_on = False
print("Lamp OFF")
# ---------------- MAIN LOOP ----------------
while True:
pir_state = pir.value()
touch_state = touch.value()
ldr_value = ldr.read()
is_dark = ldr_value < DARK_THRESHOLD
current_time = time.time()
# ---- PIR ACTIVATES SYSTEM ----
if pir_state == 1 and not system_active:
system_active = True
pir_start_time = current_time
print("PIR detected → System ON (30s window started)")
# ---- SYSTEM ACTIVE WINDOW ----
if system_active:
elapsed = current_time - pir_start_time
# ---- TOUCH PRESSED WITHIN 30s ----
if touch_state == 1 and elapsed <= INTERACTION_TIME:
if is_dark:
lamp_on_fn()
else:
print("Enough light → System OFF")
lamp_off_fn()
system_active = False
time.sleep(0.5) # debounce
# ---- TIMEOUT (NO TOUCH) ----
elif elapsed > INTERACTION_TIME:
print("No interaction → System OFF after 30s")
lamp_off_fn()
system_active = False
# ---- PIR LOST → TURN OFF LAMP ----
if pir_state == 0 and lamp_on:
print("No motion → Lamp OFF")
lamp_off_fn()
# ---- DEBUG (optional) ----
print("PIR:", pir_state,
"TOUCH:", touch_state,
"LDR:", ldr_value,
"SYSTEM:", system_active)
time.sleep(0.2)