import time
from machine import Pin, PWM
import dht
# Component setup
# LEDs
led1 = Pin(15, Pin.OUT) # LED controlled by button
led2 = Pin(14, Pin.OUT) # LED controlled by motion sensor
# Button with pull-down resistor
button = Pin(16, Pin.IN, Pin.PULL_DOWN)
# DHT22 temperature/humidity sensor
dht_sensor = dht.DHT22(Pin(22))
# PIR motion sensor
pir_sensor = Pin(21, Pin.IN)
# Servo motor (simulating humidifier)
humidifier_servo = PWM(Pin(18))
humidifier_servo.freq(50) # 50Hz for servo
# Variables
led1_state = False
last_button_state = 0
humidity_threshold = 60 # Turn on humidifier if below 60%
print("IoT Home Automation System Started")
print("Components:")
print("- LED1 (Pin 15): Button controlled")
print("- LED2 (Pin 14): Motion controlled")
print("- Button (Pin 16): Toggle LED1")
print("- DHT22 (Pin 22): Temperature & Humidity")
print("- PIR (Pin 21): Motion detection")
print("- Servo (Pin 18): Humidifier simulation")
print("-" * 40)
def set_servo_angle(angle):
"""Set servo angle (0-180 degrees)"""
duty = int(40 + (angle / 180) * 75)
humidifier_servo.duty(duty)
def read_sensors():
"""Read temperature and humidity from DHT22"""
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
except OSError as e:
print(f"Sensor read error: {e}")
return None, None
def control_humidifier(humidity):
"""Control humidifier based on humidity level"""
if humidity is not None:
if humidity < humidity_threshold:
set_servo_angle(90) # Turn on humidifier
return True
else:
set_servo_angle(0) # Turn off humidifier
return False
return False
# Main loop
while True:
try:
# Read button state (with debouncing)
current_button_state = button.value()
if current_button_state and not last_button_state:
led1_state = not led1_state
led1.value(led1_state)
print(f"Button pressed - LED1: {'ON' if led1_state else 'OFF'}")
last_button_state = current_button_state
# Read motion sensor
motion_detected = pir_sensor.value()
led2.value(motion_detected)
if motion_detected:
print("Motion detected - LED2: ON")
# Read temperature and humidity
temperature, humidity = read_sensors()
if temperature is not None and humidity is not None:
print(f"Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%")
# Control humidifier
humidifier_on = control_humidifier(humidity)
if humidifier_on:
print(f"Humidity low ({humidity:.1f}%) - Humidifier ON")
time.sleep(1) # Update every second
except KeyboardInterrupt:
print("\nSystem stopped by user")
break
except Exception as e:
print(f"Error: {e}")
time.sleep(1)
# Cleanup
led1.value(0)
led2.value(0)
set_servo_angle(0)
print("System shutdown complete")