import network
import urequests
import time
from machine import Pin, ADC
import dht
# WiFi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API
API_KEY = "3FCR0QQ46TML8R08"
URL = "https://api.thingspeak.com/update"
# Sensors
dht_sensor = dht.DHT22(Pin(15))
gas_sensor = ADC(Pin(34))
gas_sensor.atten(ADC.ATTN_11DB)
# Connect WiFi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(SSID, PASSWORD)
while not wifi.isconnected():
time.sleep(1)
print("✅ WiFi Connected")
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
gas_value = gas_sensor.read()
# Simple AQI logic: scale gas + humidity
aqi = (gas_value / 40) + (hum * 0.2)
print("Temp:", temp, "°C | Humidity:", hum, "% | Gas:", gas_value, "| AQI:", aqi)
# Send to ThingSpeak
url = f"{URL}?api_key={API_KEY}&field1={temp}&field2={hum}&field3={gas_value}&field4={aqi}"
response = urequests.get(url)
print("ThingSpeak Response:", response.text)
response.close()
except Exception as e:
print("Error:", e)
time.sleep(15) # ThingSpeak minimum interval