import time
import dht
import network
from machine import Pin
# Hardware configuration
DHT_PIN = 4
LED_PIN = 2
# Initialize DHT22 sensor and LED
sensor = dht.DHT22(Pin(DHT_PIN))
status_led = Pin(LED_PIN, Pin.OUT)
# WiFi configuration
SSID = "Wokwi-GUEST"
PASSWORD = ""
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("[NETWORK LAYER] Connecting to WiFi...")
wlan.connect(SSID, PASSWORD)
timeout = 10
while not wlan.isconnected() and timeout > 0:
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print("[NETWORK LAYER] Connected. Device IP:",
wlan.ifconfig()[0])
else:
print("[NETWORK LAYER] WiFi unavailable - "
"continuing in local-only mode.")
return wlan.isconnected()
# Connect to WiFi
wifi_ok = connect_wifi()
print("=====================================================")
print(" IoT ARCHITECTURE DEMO: Perception -> Network -> Application")
print("=====================================================")
while True:
try:
# ---------------- 1) PERCEPTION LAYER ----------------
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
print("[PERCEPTION LAYER] Raw sensor data -> "
"Temp: {} C, Humidity: {} %".format(t, h))
# ---------------- 2) NETWORK LAYER ----------------
if wifi_ok:
print("[NETWORK LAYER] Data packaged and ready "
"for transmission to cloud/server.")
else:
print("[NETWORK LAYER] No connectivity - data stays "
"on the local device only.")
# ---------------- 3) APPLICATION LAYER ----------------
if t > 30:
status_led.value(1)
print("[APPLICATION LAYER] Decision: Temperature high -> "
"Actuator (LED) turned ON")
else:
status_led.value(0)
print("[APPLICATION LAYER] Decision: Temperature normal -> "
"Actuator (LED) turned OFF")
print("-----------------------------------------------------")
time.sleep(2)
except OSError as e:
print("[PERCEPTION LAYER] Sensor read failed:", e)
time.sleep(3)