import time
import dht
import network
from machine import Pin
# ==============================
# DHT22
# DATA -> GPIO 4
# ==============================
sensor = dht.DHT22(Pin(4))
# ==============================
# Wokwi WiFi
# ==============================
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ==============================
# WiFi connection
# ==============================
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Connecting to WiFi...")
if not wlan.isconnected():
wlan.connect(SSID, PASSWORD)
for i in range(15):
if wlan.isconnected():
break
print("Waiting for WiFi...")
time.sleep(1)
if wlan.isconnected():
print("WiFi connected!")
print("IP address:", wlan.ifconfig()[0])
else:
print("WiFi connection failed")
return wlan
# ==============================
# MAIN PROGRAM
# ==============================
print("")
print("==============================")
print("ESP32 DHT22 EXPERIMENT")
print("==============================")
wlan = connect_wifi()
sample = 0
print("")
print("time_ms,temperature_C,humidity_%")
while True:
try:
# Read DHT22
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
sample += 1
timestamp = time.ticks_ms()
# CSV output
print(
"STREAM,{},{},{}".format(
timestamp,
temperature,
humidity
)
)
# WiFi status
if wlan.isconnected():
print(
"WiFi: OK | IP:",
wlan.ifconfig()[0]
)
else:
print("WiFi: DISCONNECTED")
# Wait 5 seconds
time.sleep(5)
except Exception as e:
print("DHT22 ERROR:", e)
time.sleep(3)