from machine import Pin
import network
import urequests
import time
import sys
from dht import DHT22
# ============================
# DHT22 SETUP (GPIO 12)
# ============================
dht22 = DHT22(Pin(12, Pin.IN, Pin.PULL_UP))
# ============================
# WiFi CONFIG
# ============================
WIFI_SSID = "POCO F1" # <-- your hotspot name
WIFI_PASSWORD = "LAS@gsn989" # <-- your hotspot password
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
# full reset
wifi.active(False)
time.sleep(1)
wifi.active(True)
wifi.disconnect()
# ✅ manual IP (typical Android hotspot range 192.168.43.x)
# if your phone uses different range, adjust here
wifi.ifconfig(('192.168.43.50', '255.255.255.0',
'192.168.43.1', '8.8.8.8'))
print("Connecting to WiFi:", WIFI_SSID)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
status = None
for i in range(20): # wait up to 20 seconds
status = wifi.status()
print(" waiting...", i + 1, "sec | status:", status)
if wifi.isconnected():
break
time.sleep(1)
if wifi.isconnected():
print("✅ WiFi connected!")
print("IP config:", wifi.ifconfig())
return wifi
else:
print("❌ WiFi NOT connected. Final status:", status)
print("Check: SSID, password, hotspot ON, 2.4 GHz band.")
sys.exit()
wifi = connect_wifi()
# ============================
# ThingSpeak CONFIG
# ============================
HTTP_HEADERS = {'Content-Type': 'application/json'}
THINGSPEAK_WRITE_API_KEY = 'NOEDY1PSF82BCDL7'
time.sleep(2) # little delay before first sensor read
while True:
# ---- Read DHT22 with retries ----
ok = False
for _ in range(3):
try:
dht22.measure()
temp = dht22.temperature()
hum = dht22.humidity()
ok = True
break
except OSError as e:
print("DHT22 read error, retrying...", e)
time.sleep(1)
if not ok:
print("DHT22 failed after retries, skipping this cycle")
time.sleep(5)
continue
print("Temperature:", temp)
print("Humidity:", hum)
# ---- Send to ThingSpeak ----
data = {'field1': temp, 'field2': hum}
try:
url = 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY
r = urequests.post(url, json=data, headers=HTTP_HEADERS)
print("HTTP status:", r.status_code)
r.close()
print("Data sent:", data)
print("*******************************")
except Exception as net_err:
print("ThingSpeak Error:", net_err)
time.sleep(15) # ThingSpeak free limit