import machine
import time
import dht
from machine import Pin
# Define pins
DHT_PIN = 15
RELAY_PIN = 5
LED_PIN = 2
SENSOR_PIN = 14
# Initialize DHT22 sensor
dht22 = dht.DHT22(machine.Pin(DHT_PIN))
# Initialize relay module
relay = machine.Pin(RELAY_PIN, machine.Pin.OUT)
relay.value(0) # Ensure the relay is off initially
# Initialize LED and motion sensor
led = Pin(LED_PIN, Pin.OUT)
sensor = Pin(SENSOR_PIN, Pin.IN)
while True:
try:
# Read temperature and humidity from DHT22
dht22.measure()
temperature = dht22.temperature()
humidity = dht22.humidity()
# Print temperature and humidity to the console
print("Temperature: {:.1f}°C Humidity: {:.1f}%".format(temperature, humidity))
# Control the relay based on temperature
if temperature > 25.0: # Set your own threshold
relay.value(1) # Turn the relay on
else:
relay.value(0) # Turn the relay off
except OSError as e:
print("Failed to read sensor data: ", e)
# Detect motion
detection = sensor.value()
if detection == 1:
led.value(1)
print("Movement detected")
else:
led.value(0)
print("Motion Not Detected")
# Wait a few seconds between measurements
time.sleep(2)