from machine import Pin, ADC
from time import sleep
import math
# === Pin Configuration ===
LDR_PIN = 34 # LDR analog output connected to GPIO34
PIR_PIN = 27 # PIR sensor output pin
LED_PIN = 26 # LED output pin
# === Initialize Components ===
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB) # allows full 0–3.3V range
pir = Pin(PIR_PIN, Pin.IN)
led = Pin(LED_PIN, Pin.OUT)
# === Thresholds (you can tune based on Wokwi LDR readings) ===
LIGHT_THRESHOLD = 2000 # Lower = brighter
AI_DECISION_FACTOR = 0.6 # Used for pseudo AI prediction
def get_light_level():
"""Read and return light intensity from LDR."""
return ldr.read()
def get_motion():
"""Return True if motion detected by PIR."""
return pir.value() == 1
def ai_predict_light(time_hour, last_light, motion):
"""
Simple AI-like logic:
Predict light requirement based on time, previous light, and motion.
(Can be later replaced by ML model)
"""
# simulate AI logic: higher chance to turn ON in evening + motion
base_need = 1 if 18 <= time_hour or time_hour <= 6 else 0 # night time
light_factor = 1 if last_light < LIGHT_THRESHOLD else 0
motion_factor = 1 if motion else 0
decision_value = (base_need + light_factor + motion_factor) / 3
return decision_value > AI_DECISION_FACTOR
# === Main Loop ===
print("Smart Light Control (AI + IoT) system started...")
hour = 18 # simulate evening time; change manually for testing
while True:
light_value = get_light_level()
motion_detected = get_motion()
# Simulate AI-based prediction
ai_decision = ai_predict_light(hour, light_value, motion_detected)
if ai_decision:
led.value(1)
print(f"[AI] Light ON | Light={light_value} | Motion={motion_detected}")
else:
led.value(0)
print(f"[AI] Light OFF | Light={light_value} | Motion={motion_detected}")
sleep(1)