import machine
import time
import dht
import network
# ==========================================
#STEP 1: HARDWARE PIN ALIGNMENT
#==========================================
DHT_PIN_NUMBER = 15 # Pin number where your DHT sensor wire is connected
sensor = dht.DHT22(machine.Pin(DHT_PIN_NUMBER))
#The magic limit number that triggers our automatic system alerts
TEMPERATURE_THRESHOLD = 30
#=========================================
#STEP 3: WI-FI NETWORK SETUP
#=========================================
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD =""
print("--- Connecting to the Smart Grid Network ---")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait until the virtual microchip handshakes with the network
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("/n Connected securely to the network!")
print("Device IP Configuration:", wlan.ifconfig()[0])
# Setting up our background stopwatch timer (in milliseconds)
last_sensor_read = time.ticks_ms()
# ==========================================
# STEP 5: THE CONTINUOUS LIVE LOOP
# ==========================================
while True:
# CRITICAL: This must run constantly to process background heartbeat signals.
# Never use time.sleep() directly inside this loop, or you will freeze the connection!
# Check our stopwatch: Have 2000 milliseconds (2 seconds) passed?
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_sensor_read) >= 2000:
try:
# Ask the sensor to check the air temperature
sensor.measure()
current_temp = sensor.temperature()
# Local IF/THEN Logic: Has the temperature crossed our boundary line?
if current_temp > TEMPERATURE_THRESHOLD:
print("⚠ Alert! Threshold limit crossed!")
else: print("Live Temperature Reading:", current_temp, "°C")
except OSError as e:
print("Error: Sensor reading delayed. Checking circuit pathways...")
# Reset our background stopwatch tracking point for the next 2 seconds
last_sensor_read = current_time