# HOME AUTOMATION - RASPBERRY PI PICO W
# Light ON only when button is pressed
# Fan controlled by temperature (DHT22)
import time
from machine import Pin
import dht
# ---------------- PIN CONFIGURATION -----------------
LIGHT_PIN = 15 # LED (Light)
FAN_PIN = 14 # LED (Fan)
BUTTON_PIN = 16 # Push Button
DHT_PIN = 13 # DHT22 Data
# ---------------- INITIALIZATION --------------------
light = Pin(LIGHT_PIN, Pin.OUT)
fan = Pin(FAN_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_DOWN)
sensor = dht.DHT22(Pin(DHT_PIN))
# Initial states
light.value(0)
fan.value(0)
print("Home Automation System Started")
# ---------------- MAIN LOOP ----------------
while True:
try:
# ---------- BUTTON CONTROLS LIGHT ----------
if button.value() == 1:
light.value(1) # Button pressed → Light ON
print("Button Pressed → Light ON")
else:
light.value(0) # Button released → Light OFF
# ---------- DHT22 CONTROLS FAN ----------
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
print("Temperature:", temperature, "°C")
print("Humidity:", humidity, "%")
if temperature > 30:
fan.value(1)
print("Fan ON (High Temperature)")
else:
fan.value(0)
print("Fan OFF")
print("--------------------------------")
time.sleep(1)
except Exception as e:
print("Sensor Error:", e)
time.sleep(2)