import network
import urequests
import time
import machine
import random
# Blynk credentials
BLYNK_AUTH_TOKEN = "ZqU7wIAYsIgv5CCQTj5l1xgZbXpRPfO6"
# Use HTTP (not HTTPS) because MicroPython urequests SSL is unstable
BLYNK_BASE_URL = "http://blynk.cloud/external/api"
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# Pump pin
RELAY_PIN = machine.Pin(26, machine.Pin.OUT)
# Pump state
pumpState = 0 # 0=OFF, 1=ON
# Connect WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected:", wlan.ifconfig())
# Send value to Blynk
def blynk_virtual_write(pin, value):
try:
url = f"{BLYNK_BASE_URL}/update?token={BLYNK_AUTH_TOKEN}&V{pin}={value}"
r = urequests.get(url)
print("Write V{}={} -> {}".format(pin, value, r.text))
r.close()
except Exception as e:
print("Error sending to Blynk:", e)
# Get value from Blynk
def blynk_virtual_read(pin):
try:
url = f"{BLYNK_BASE_URL}/get?token={BLYNK_AUTH_TOKEN}&V{pin}"
r = urequests.get(url)
val = r.text.strip()
r.close()
print("Read V{} -> {}".format(pin, val))
return val
except Exception as e:
print("Error reading from Blynk:", e)
return None
# Main data loop
def sendData():
global pumpState
# Voltage random (220–230V)
voltage = random.randint(220, 230)
if pumpState == 1:
current = random.randint(30, 80) / 10.0 # 3.0 – 8.0 A
flow = random.randint(10, 50) / 10.0 # 1.0 – 5.0 L/min
else:
current = random.randint(1, 2) / 10.0 # 0.1 – 0.2 A
flow = 0.0
# Push values to Blynk
blynk_virtual_write(1, voltage) # V1
blynk_virtual_write(2, current) # V2
blynk_virtual_write(3, flow) # V3
blynk_virtual_write(5, pumpState) # V5 Pump indicator
# Debug
print("-------------------------")
print("Pump:", "ON" if pumpState else "OFF")
print("Voltage:", voltage, "V")
print("Current:", current, "A")
print("Flow:", flow, "L/min")
# Check pump control from Blynk (V4)
def checkPumpControl():
global pumpState
val = blynk_virtual_read(4) # V4 = Pump switch
if val == "1":
pumpState = 1
RELAY_PIN.value(1)
else:
pumpState = 0
RELAY_PIN.value(0)
# ---------------- MAIN ----------------
connect_wifi()
while True:
checkPumpControl()
sendData()
time.sleep(2) # every 2s