import network
import urequests
import time
from machine import Pin
import dht
SSID = 'Wokwi-GUEST' # Use this if you are using Wokwi's built-in WiFi
PASSWORD = '' # No password for Wokwi-GUEST
# ThingSpeak Configuration
THINGSPEAK_API_KEY = 'UX2E6JSCNH8PAZE8' # Replace with your actual API Key
THINGSPEAK_URL = 'https://api.thingspeak.com/update'
# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(4, Pin.IN, Pin.PULL_UP)) # Enable internal pull-up
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Connecting to WiFi...')
wlan.connect(SSID, PASSWORD)
timeout = 10 # Timeout for connection
while not wlan.isconnected() and timeout > 0:
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print('Connected to WiFi')
else:
print('Failed to connect to WiFi')
def send_to_thingspeak(temperature, humidity):
url = f'{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={temperature}&field2={humidity}'
try:
response = urequests.get(url)
print(f'Data sent to ThingSpeak: Temp={temperature}, Humidity={humidity}')
response.close()
except Exception as e:
print(f'Error sending data: {e}')
connect_wifi()
time.sleep(2) # Allow time for WiFi connection
while True:
try:
print("Taking measurement...")
sensor.measure()
temp = sensor.temperature()
humidity = sensor.humidity()
print(f'Temperature: {temp}C, Humidity: {humidity}%')
# Send data to ThingSpeak every cycle
send_to_thingspeak(temp, humidity)
time.sleep(10) # Delay between measurements
# Reconnect WiFi if disconnected
if not network.WLAN(network.STA_IF).isconnected():
connect_wifi()
except Exception as e:
print(f'Error: {e}')
time.sleep(5) # Wait before retrying