import time
import math
import dht
from machine import Pin
# ==============================
# Pin Configuration
# ==============================
DHT_PIN = 4
LED_GREEN_PIN = 5
LED_YELLOW_PIN = 18
LED_RED_PIN = 19
BUZZER_PIN = 21
# ==============================
# Hardware Setup
# ==============================
sensor = dht.DHT22(Pin(DHT_PIN))
led_green = Pin(LED_GREEN_PIN, Pin.OUT)
led_yellow = Pin(LED_YELLOW_PIN, Pin.OUT)
led_red = Pin(LED_RED_PIN, Pin.OUT)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
# ==============================
# AI Model Parameters
# Offline Logistic Regression
# ==============================
W_TEMP = 1.20
W_HUM = 0.80
BIAS = -0.50
TEMP_MEAN = 20.0
TEMP_STD = 15.0
HUM_MEAN = 50.0
HUM_STD = 30.0
# ==============================
# Sigmoid Function
# ==============================
def sigmoid(x):
return 1 / (1 + math.exp(-x))
# ==============================
# AI Inference
# ==============================
def ai_inference(temp_c, humidity):
# Normalize temperature
t_norm = (temp_c - TEMP_MEAN) / TEMP_STD
# Normalize humidity
h_norm = (humidity - HUM_MEAN) / HUM_STD
# Logistic regression equation
z = (W_TEMP * t_norm) + (W_HUM * h_norm) + BIAS
# Probability of HOT condition
probability = sigmoid(z)
return probability
# ==============================
# LED and Buzzer Control
# ==============================
def set_outputs(label):
# Turn everything OFF first
led_green.value(0)
led_yellow.value(0)
led_red.value(0)
buzzer.value(0)
# Comfortable
if label == "COMFORTABLE":
led_green.value(1)
# Warm
elif label == "WARM":
led_yellow.value(1)
# Hot
elif label == "HOT":
led_red.value(1)
buzzer.value(1)
# ==============================
# Startup
# ==============================
print("----------------------------------------")
print("AIoT Temperature Monitoring System")
print("----------------------------------------")
print("AI decision engine ready.")
print("DHT22 connected to GPIO 4")
print("Green LED -> GPIO 5")
print("Yellow LED -> GPIO 18")
print("Red LED -> GPIO 19")
print("Buzzer -> GPIO 21")
print("----------------------------------------")
# ==============================
# Main Loop
# ==============================
while True:
try:
# Read DHT22 sensor
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# AI prediction
hot_probability = ai_inference(
temperature,
humidity
)
# Classify environment
if hot_probability < 0.33:
label = "COMFORTABLE"
elif hot_probability < 0.66:
label = "WARM"
else:
label = "HOT"
# Control LEDs and buzzer
set_outputs(label)
# Display result
print(
"Temperature: {:.1f} C | "
"Humidity: {:.1f}% | "
"HOT Probability: {:.3f} | "
"Decision: {}".format(
temperature,
humidity,
hot_probability,
label
)
)
except Exception as e:
print("Sensor read failed:", e)
# Wait before next reading