# main.py for an ESP32 Temperature Control System
from machine import Pin
import time
import dht
# --- CONFIGURATION CONSTANTS (Tune these for your setup) ---
# Pin Assignments
DHT_PIN = 15 # Pin connected to the DHT22 data line
RELAY_PIN = 26 # Pin connected to the relay module's IN pin
# Temperature Control Logic
TEMP_THRESHOLD_HIGH = 28.0 # Fan turns ON when temperature goes ABOVE this (in Celsius)
HYSTERESIS = 2.0 # How many degrees the temp must drop below the threshold to turn OFF
# So, fan will turn OFF below (28.0 - 2.0) = 26.0 °C
# --- SETUP ---
# Initialize the DHT22 sensor
dht_sensor = dht.DHT22(Pin(DHT_PIN))
# Initialize the relay pin.
# The Wokwi Relay Module is Active LOW, which means sending a LOW signal (0)
# turns the relay ON, and a HIGH signal (1) turns it OFF.
relay = Pin(RELAY_PIN, Pin.OUT)
relay.on() # .on() sets the pin HIGH, so the relay starts in the OFF state.
print("--- Temperature Control System Initialized ---")
print(f"Fan will turn ON above {TEMP_THRESHOLD_HIGH}°C")
print(f"Fan will turn OFF below {TEMP_THRESHOLD_HIGH - HYSTERESIS}°C")
# State variable to remember if the fan is on or off
is_fan_on = False
# --- MAIN LOOP ---
while True:
try:
# 1. Attempt to read sensor data
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
# Check if the reading is valid (sometimes returns unrealistic values on error)
if temp is None or hum is None:
print("Failed to get a valid reading from DHT22 sensor.")
else:
print(f"Temperature: {temp:.1f}°C | Humidity: {hum:.1f}% | Fan State: {'ON' if is_fan_on else 'OFF'}")
# 2. Hysteresis Logic
if temp > TEMP_THRESHOLD_HIGH:
# If temperature is above the high threshold, the fan should be ON.
is_fan_on = True
elif temp < (TEMP_THRESHOLD_HIGH - HYSTERESIS):
# If temperature is below the low threshold, the fan should be OFF.
is_fan_on = False
# If the temperature is between the two thresholds, the state does not change.
# This prevents the fan from rapidly switching on and off.
# 3. Actuate the Relay
if is_fan_on:
relay.on() # Turn relay ON (Active LOW)
else:
relay.off() # Turn relay OFF (Active HIGH)
except OSError as e:
print("Error reading from DHT22 sensor:", e)
# Wait 2 seconds before the next reading. This is the recommended minimum for DHT22.
time.sleep(2)