import time
import dht
import network
import socket
from machine import Pin
sensor = dht.DHT22(Pin(4))
SSID = "Wokwi-GUEST"
PASSWORD = ""
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("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("WiFi connected:", wlan.ifconfig()[0])
return True
else:
print("WiFi not connected - streaming over Serial only.")
return False
def send_http_post(temp, hum, sample):
try:
addr = socket.getaddrinfo("httpbin.org", 80)[0][-1]
s = socket.socket()
s.connect(addr)
body = (
'{{"device":"ESP32-01",'
'"temperature":{:.2f},'
'"humidity":{:.2f},'
'"sample":{}}}'
).format(temp, hum, sample)
request = (
"POST /post HTTP/1.1\r\n"
"Host: httpbin.org\r\n"
"Content-Type: application/json\r\n"
"Content-Length: {}\r\n"
"Connection: close\r\n"
"\r\n"
"{}"
).format(len(body), body)
s.sendall(request.encode())
resp = s.recv(200)
print("HTTP response:", resp[:40])
s.close()
except Exception as e:
print("HTTP POST failed:", e)
wifi_ok = connect_wifi()
sample_count = 0
print("time_ms,temperature_C,humidity_%")
while True:
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
sample_count += 1
timestamp = time.ticks_ms()
print(
"STREAM,{},{},{}".format(
timestamp,
temperature,
humidity
)
)
if wifi_ok:
send_http_post(
temperature,
humidity,
sample_count
)
except OSError as e:
print("Sensor read failed:", e)
time.sleep(2)