58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
import network
|
|
import time
|
|
import urequests
|
|
import machine
|
|
import dht
|
|
from secrets import WIFI_SSID, WIFI_PASSWORD, AIO_USERNAME, AIO_KEY
|
|
|
|
# DHT11 setup (GP14)
|
|
sensor = dht.DHT11(machine.Pin(14))
|
|
|
|
# Connect to Wi-Fi
|
|
wlan = network.WLAN(network.STA_IF)
|
|
wlan.active(True)
|
|
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
|
|
|
|
print("Connecting to Wi-Fi...")
|
|
while not wlan.isconnected():
|
|
time.sleep(1)
|
|
|
|
print("Connected:", wlan.ifconfig())
|
|
|
|
# Adafruit IO URLs
|
|
temp_url = "https://io.adafruit.com/api/v2/{}/feeds/temperature/data".format(AIO_USERNAME)
|
|
hum_url = "https://io.adafruit.com/api/v2/{}/feeds/humidity/data".format(AIO_USERNAME)
|
|
|
|
headers = {
|
|
"X-AIO-Key": AIO_KEY,
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
while True:
|
|
try:
|
|
sensor.measure()
|
|
temp_c = sensor.temperature()
|
|
humidity = sensor.humidity()
|
|
|
|
# Convert to Fahrenheit
|
|
temp_f = (temp_c * 9/5) + 32
|
|
|
|
print("Temp: {:.1f}°F Humidity: {}%".format(temp_f, humidity))
|
|
|
|
# Send temperature
|
|
temp_data = {"value": temp_f}
|
|
r = urequests.post(temp_url, json=temp_data, headers=headers)
|
|
r.close()
|
|
|
|
# Send humidity
|
|
hum_data = {"value": humidity}
|
|
r = urequests.post(hum_url, json=hum_data, headers=headers)
|
|
r.close()
|
|
|
|
print("Uploaded to Adafruit IO ✅")
|
|
|
|
except Exception as e:
|
|
print("Error:", e)
|
|
|
|
# Wait 60 seconds
|
|
time.sleep(60)
|