import network
import urequests
import dht
from machine import Pin, ADC
import time
# Configuration
SSID = "Wokwi-GUEST" # Change to your WiFi name
PASSWORD = "" # Change to your WiFi password
THINGSPEAK_API_KEY = "ZP9ZJJOBXNTPT57S" # Replace with your actual API key
# Hardware setup
sensor = dht.DHT22(Pin(4)) # DHT22 connected to GPIO 4
mq2_aout = ADC(Pin(34)) # MQ2 analog output (AOUT) -> GPIO34
mq2_aout.atten(ADC.ATTN_11DB) # Full range: 0 - 3.3V
mq2_aout.width(ADC.WIDTH_12BIT) # 12-bit resolution (0-4095)
# WiFi connection
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to WiFi...")
while not wlan.isconnected():
print(".", end="")
time.sleep(1)
print("\nConnected to WiFi successfully!")
print("IP Address:", wlan.ifconfig()[0])
return wlan
# Send data to ThingSpeak
def send_to_thingspeak(temp, hum, gas):
try:
url = f"https://api.thingspeak.com/update?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}&field3={gas}"
print(f"Sending to ThingSpeak: Temp={temp}°C, Humidity={hum}%, MQ2={gas}")
response = urequests.get(url)
if response.status_code == 200:
entry_id = response.text
print(f"✅ Data sent successfully! Entry ID: {entry_id}")
response.close()
return True
else:
print(f"❌ ThingSpeak error: HTTP {response.status_code}")
response.close()
return False
except Exception as e:
print(f"❌ Error sending to ThingSpeak: {e}")
return False
# Read sensor data
def read_sensors():
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
gas_analog = mq2_aout.read() # Analog value (0–4095)
# Validation
if temperature is None or humidity is None:
print("⚠️ Invalid DHT22 reading")
return None, None, None
if temperature < -40 or temperature > 80:
print("⚠️ Temperature out of range")
return None, None, None
if humidity < 0 or humidity > 100:
print("⚠️ Humidity out of range")
return None, None, None
return temperature, humidity, gas_analog
except Exception as e:
print(f"❌ Sensor error: {e}")
return None, None, None
# Main program
print("🌡️ DHT22 + MQ2 (Analog) ThingSpeak Data Logger")
print("=" * 50)
wlan = connect_wifi()
print("\n📡 Starting data logging to ThingSpeak...")
print(f"🔑 API Key: {THINGSPEAK_API_KEY}")
print("=" * 50)
reading_count = 0
while True:
try:
if not wlan.isconnected():
print("📶 WiFi disconnected, reconnecting...")
wlan = connect_wifi()
temperature, humidity, gas_analog = read_sensors()
if temperature is not None and humidity is not None and gas_analog is not None:
reading_count += 1
print(f"\n📊 Reading #{reading_count}")
print(f"🌡️ Temperature: {temperature}°C")
print(f"💧 Humidity: {humidity}%")
print(f"📈 MQ2 Gas Level (AOUT): {gas_analog} (0–4095)")
if send_to_thingspeak(temperature, humidity, gas_analog):
print("✅ Data logged successfully!")
else:
print("❌ Failed to log data")
else:
print("⚠️ Skipping invalid sensor reading")
print("-" * 40)
print("⏳ Waiting 20 seconds for next reading...")
time.sleep(20)
except KeyboardInterrupt:
print("\n🛑 Program stopped by user")
break
except Exception as e:
print(f"❌ Main loop error: {e}")
time.sleep(5)