from machine import Pin, ADC, PWM
from time import sleep
import dht
# ----- Sensors & Actuators -----
ldr = ADC(26) # LDR
led = Pin(15, Pin.OUT) # LED
pir = Pin(16, Pin.IN) # PIR Motion sensor
servo = PWM(Pin(13)) # Servo
sensor = dht.DHT11(Pin(14)) # DHT11
# ----- Servo Setup -----
servo.freq(50)
def set_servo_angle(angle):
duty = int((angle / 18) + 2) # Convert angle to duty cycle
servo.duty_u16(int(duty * 65536 / 100))
# ----- Initialization -----
print("Smart Home Ready!")
# ----- Main Loop -----
while True:
# --- Read LDR ---
light_value = ldr.read_u16()
light_level = light_value / 65535 * 100 # Convert to percentage
# --- Read DHT11 ---
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
except:
temp, hum = 0, 0
# --- Read PIR ---
motion = pir.value()
# --- LED Control ---
if light_value < 30000 or motion == 1:
led.value(1)
else:
led.value(0)
# --- Servo Control ---
if motion == 1:
set_servo_angle(90) # Open
else:
set_servo_angle(0) # Close
# --- Output to Serial Monitor ---
print("Light: {:.0f}% | Temp: {}C | Humidity: {}% | Motion: {}".format(
light_level, temp, hum, motion
))
sleep(1)