import network
import urequests
import dht
from machine import Pin
import time
# Configuration
SSID = "Wokwi-GUEST" # Change to your WiFi name
PASSWORD = "" # Change to your WiFi password
THINGSPEAK_API_KEY = "06A0ELNLZVBQBBMN" # Replace with your actual API key
# Hardware setup
sensor = dht.DHT22(Pin(4)) # DHT22 connected to GPIO 4
# 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]) # Fixed: removed ^
return wlan
# Send data to ThingSpeak
def send_to_thingspeak(temp, hum):
try:
# Fixed: Complete the URL string properly
url = f"https://api.thingspeak.com/update?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}"
print(f"Sending to ThingSpeak: Temp={temp}°C, Humidity={hum}%")
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 with error handling
def read_sensor():
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Validate readings
if temperature is None or humidity is None:
print("⚠ Invalid sensor reading")
return None, None
if temperature < -40 or temperature > 80:
print("⚠ Temperature reading out of range")
return None, None
if humidity < 0 or humidity > 100:
print("⚠ Humidity reading out of range")
return None, None
return temperature, humidity
except Exception as e:
print(f"❌ Sensor reading error: {e}")
return None, None
# Main program
print("🌡 DHT22 ThingSpeak Data Logger")
print("=" * 40)
# Connect to WiFi
wlan = connect_wifi()
print(f"\n📡 Starting data logging to ThingSpeak...")
print(f"🔑 API Key: {THINGSPEAK_API_KEY}")
print("=" * 40)
# Data logging loop
reading_count = 0
while True:
try:
# Check WiFi connection
if not wlan.isconnected():
print("📶 WiFi disconnected, reconnecting...")
wlan = connect_wifi()
# Read sensor data
temperature, humidity = read_sensor()
if temperature is not None and humidity is not None:
reading_count += 1
print(f"\n📊 Reading #{reading_count}")
print(f"🌡 Temperature: {temperature}°C")
print(f"💧 Humidity: {humidity}%")
# Send to ThingSpeak
if send_to_thingspeak(temperature, humidity):
print("✅ Data logged successfully!")
else:
print("❌ Failed to log data")
else:
print("⚠ Skipping invalid sensor reading")
print("-" * 30)
print("⏳ Waiting 20 seconds for next reading...")
time.sleep(20) # ThingSpeak free accounts: minimum 15 seconds between updates
except KeyboardInterrupt:
print("\n🛑 Program stopped by user")
break
except Exception as e:
print(f"❌ Main loop error: {e}")
time.sleep(5)