import machine
import dht
import time
# Pin Definitions
led_pin = machine.Pin(23, machine.Pin.OUT) # LED connected to GPIO 23
relay_pin = machine.Pin(12, machine.Pin.OUT) # Relay connected to GPIO 12
button_pin = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_DOWN) # Button on GPIO 13
dht_sensor = dht.DHT22(machine.Pin(15)) # DHT22 data pin on GPIO 15
# Initial States
led_state = False
relay_state = False
# Function to toggle LED and relay
def toggle_devices():
global led_state, relay_state
led_state = not led_state
relay_state = not relay_state
led_pin.value(led_state)
relay_pin.value(relay_state)
print(f"LED {'ON' if led_state else 'OFF'}, Relay {'ON' if relay_state else 'OFF'}")
# Function to determine air quality
def get_air_quality(temp, humidity):
temp_quality = "Normal"
humidity_quality = "Normal"
# Temperature Ranges (adjust as needed)
if temp <= 15:
temp_quality = "Cold"
elif temp > 15 and temp <= 30:
temp_quality = "Pleasant"
else:
temp_quality = "Hot"
# Humidity Ranges (adjust as needed)
if humidity <=30:
humidity_quality = "Bad"
elif humidity > 30 and humidity <= 50:
humidity_quality = "Good"
else:
humidity_quality="worst"
return temp_quality, humidity_quality
# Main Loop
print("Home Automation System Starting...")
while True:
# Check button press
if button_pin.value() == 1:
toggle_devices()
time.sleep(0.5) # Debounce delay to avoid multiple toggles
# Read temperature and humidity every 5 seconds
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Get air quality ranges
temp_quality, humidity_quality = get_air_quality(temp, humidity)
# Print readings with range indicators
print(f"Temperature: {temp}°C - {temp_quality}")
print(f"Humidity: {humidity}% - {humidity_quality}")
except Exception as e:
print("Error reading DHT22 sensor:", e)
# Wait and repeat
time.sleep(5)