import network
import utime
from machine import Pin
import BlynkLib
# ---------------- WIFI DETAILS ----------------
SSID = "home4"
PASSWORD = "12345687"
BLYNK_AUTH = "Z7ZkClkkw9VbmFrLkmvvPBvTZxDX5YAF"
# ---------------- ULTRASONIC PINS ----------------
trig1 = Pin(5, Pin.OUT)
echo1 = Pin(4, Pin.IN)
trig2 = Pin(19, Pin.OUT)
echo2 = Pin(18, Pin.IN)
# ---------------- WIFI CONNECT FUNCTION ----------------
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
wlan.connect(SSID, PASSWORD)
print("Connecting to WiFi...")
while not wlan.isconnected():
utime.sleep(1)
print("WiFi Connected:", wlan.ifconfig()[0])
return wlan
# ---------------- BLYNK CONNECT FUNCTION ----------------
def connect_blynk():
print("Connecting to Blynk...")
while True:
try:
blynk = BlynkLib.Blynk(BLYNK_AUTH)
print("Blynk Connected!")
return blynk
except:
print("Blynk Retry...")
utime.sleep(3)
# ---------------- DISTANCE FUNCTION ----------------
def get_distance(trig, echo):
trig.low()
utime.sleep_us(2)
trig.high()
utime.sleep_us(10)
trig.low()
timeout = utime.ticks_ms()
# Wait for echo HIGH
while echo.value() == 0:
if utime.ticks_diff(utime.ticks_ms(), timeout) > 50:
return 0
start = utime.ticks_us()
# Wait for echo LOW
while echo.value() == 1:
if utime.ticks_diff(utime.ticks_ms(), timeout) > 50:
return 0
end = utime.ticks_us()
duration = utime.ticks_diff(end, start)
distance = (duration * 0.0343) / 2
return distance
# ---------------- INITIAL CONNECTION ----------------
wlan = connect_wifi()
blynk = connect_blynk()
# ---------------- MAIN LOOP ----------------
last_send = utime.ticks_ms()
while True:
try:
blynk.run()
# Send every 2 seconds (NON-BLOCKING)
if utime.ticks_diff(utime.ticks_ms(), last_send) > 2000:
last_send = utime.ticks_ms()
d1 = get_distance(trig1, echo1)
d2 = get_distance(trig2, echo2)
# SLOT 1 STATUS
if 0 < d1 < 200:
status1 = "NOT AVAILABLE"
else:
status1 = "AVAILABLE"
# SLOT 2 STATUS
if 0 < d2 < 200:
status2 = "NOT AVAILABLE"
else:
status2 = "AVAILABLE"
print("Slot 1:", status1)
print("Slot 2:", status2)
print("----------------------")
# Send to Blynk
blynk.virtual_write(2, status1)
blynk.virtual_write(1, status2)
except OSError as e:
print("Network Error:", e)
print("Reconnecting...")
wlan = connect_wifi()
blynk = connect_blynk()
except Exception as e:
print("Error:", e)
utime.sleep(2)Loading
pi-pico-w
pi-pico-w