import machine
import time
import dht
import network
import BlynkLib # Official Blynk Python engine library
# ==========================================
# STEP 1: BLYNK CONFIGURATION
# ==========================================
# MicroPython only needs your direct Auth Token to handshake with the cloud:
BLYNK_AUTH_TOKEN = "FGf8sr6XZYmB5sfpab89UPCDvS3B84cz"
# ==========================================
# STEP 2: HARDWARE PIN ALIGNMENT
# ==========================================
DHT_PIN_NUMBER = 15 # Pin number where your DHT sensor wire is connected
sensor = dht.DHT22(machine.Pin(DHT_PIN_NUMBER))
# The magic limit number that triggers our automatic system alerts
TEMPERATURE_THRESHOLD = 40
# ==========================================
# STEP 3: WI-FI NETWORK SETUP
# ==========================================
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
print("--- Connecting to the Smart Grid Network ---")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait until the virtual microchip handshakes with the network
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\n Connected securely to the network!")
print("Device IP Configuration:", wlan.ifconfig()[0])
# ==========================================
# STEP 4: INITIALIZE OFFICIAL BLYNK ENGINE
# ==========================================
print("Connecting to live Blynk Cloud Matrix...")
# Change this line in your code:
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN, insecure=True)
print(" Live Connection Established! Dashboard badge is now GREEN (Online).")
# Setting up our background stopwatch timer (in milliseconds)
last_sensor_read = time.ticks_ms()
# ==========================================
# STEP 5: THE CONTINUOUS LIVE LOOP
# ==========================================
while True:
# CRITICAL: This must run constantly to process background heartbeat signals.
# Never use time.sleep() directly inside this loop, or you will freeze the connection!
blynk.run()
# Check our stopwatch: Have 2000 milliseconds (2 seconds) passed?
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_sensor_read) >= 2000:
try:
# Ask the sensor to check the air temperature
sensor.measure()
current_temp = sensor.temperature()
# Local IF/THEN Logic: Has the temperature crossed our boundary line?
if current_temp > TEMPERATURE_THRESHOLD:
print("⚠ Alert! Threshold limit crossed!")
else:
print("Live Temperature Reading:", current_temp, "°C")
# ------------------------------------------
# CLOUD STREAMING: Push data packet to V1
# ------------------------------------------
blynk.virtual_write(1, current_temp)
print(" Successfully pushed data packet to Blynk Pin V1.")
except OSError as e:
print("Error: Sensor reading delayed. Checking circuit pathways...")
# Reset our background stopwatch tracking point for the next 2 seconds
last_sensor_read = current_time