from machine import Pin
import dht
import time
import network
import urequests
# --- CONFIGURATION ---
BLYNK_AUTH_TOKEN = "EY2Rl8ZadD_UzxG-C1kzUTMstyTv9Nqz" # Replace with your Blynk Auth Token
SSID = "Wokwi-GUEST" # Wi-Fi SSID
PASS = "" # Wi-Fi password
DHT_PIN = 14 # DHT sensor pin
LED_PIN = 2 # LED pin (built-in LED on ESP32/ESP8266)
# --- SETUP ---
sensor = dht.DHT22(Pin(DHT_PIN))
led = Pin(LED_PIN, Pin.OUT)
# Connect to Wi-Fi
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
print("Connecting to Wi-Fi...")
sta_if.active(True)
sta_if.connect(SSID, PASS)
while not sta_if.isconnected():
time.sleep(0.5)
print("Connected! IP:", sta_if.ifconfig()[0])
# Send temperature to Blynk
def send_temperature(temp):
try:
urequests.get("https://blr1.blynk.cloud/external/api/update?token={}&V0={}".format(BLYNK_AUTH_TOKEN, temp))
print("Temperature sent to Blynk: {:.2f} °C".format(temp))
except Exception as e:
print("Error sending temperature:", e)
# Check LED switch from Blynk
def check_led():
try:
response = urequests.get("https://blr1.blynk.cloud/external/api/get?token={}&V1".format(BLYNK_AUTH_TOKEN))
state = int(response.text)
led.value(state)
# print("LED State:", state)
except Exception as e:
print("Error getting LED state:", e)
# --- MAIN ---
connect_wifi()
print("Temperature & LED Control Started...")
while True:
try:
sensor.measure()
temp = sensor.temperature() # Celsius
send_temperature(temp)
check_led()
except Exception as e:
print("Error:", e)
time.sleep(2) # Update every 2 seconds