import network
import urequests
import utime
from machine import Pin
import dht
# Wi-Fi Credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# ThingSpeak API Key
THINGSPEAK_API_KEY = "NQ4HKHC2H153I8XY"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Initialize DHT22 Sensor
dht_pin = Pin(27) # DHT22 connected to GPIO 27
sensor = dht.DHT22(dht_pin)
# GPIO Setup for Push Button (MOSFET Control)
button = Pin(26, Pin.IN, Pin.PULL_UP) # GPIO 26 with pull-up resistor
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Connecting to Wi-Fi", end="")
while not wlan.isconnected():
print(".", end="")
utime.sleep(0.5)
print("\nConnected! IP:", wlan.ifconfig()[0])
# Read DHT22 Data (with retries)
def read_dht():
for _ in range(5): # Retry up to 5 times
try:
sensor.measure()
return sensor.temperature(), sensor.humidity()
except OSError as e:
print("Sensor error, retrying...")
utime.sleep(5)
return None, None # Return None if still failing
# Send Data to ThingSpeak
def send_to_thingspeak(temp, hum, state):
if temp is None or hum is None:
print("Skipping data send due to sensor failure.")
return
query = f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}&field3={state}"
try:
response = urequests.get(query)
print(f"Temperature: {temp}°C, Humidity: {hum}%, MOSFET State: {state} | Data Sent! Response:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
# Main Loop
connect_wifi()
while True:
temperature, humidity = read_dht()
button_state = not button.value() # Button is active LOW
if temperature is not None and humidity is not None:
print(f"Temperature: {temperature}°C, Humidity: {humidity}%, MOSFET State: {button_state}")
else:
print("DHT22 sensor error, skipping this cycle.")
send_to_thingspeak(temperature, humidity, int(button_state))
utime.sleep(5) # Send data every 5 seconds