from machine import Pin, I2C, time_pulse_us
import ssd1306
import time
from blynk_lib import Blynk
try:
IOError
except NameError:
IOError = OSError
# Define pins
TRIG_PIN = 32
ECHO_PIN = 33
BUZZER_PIN = 4
GREEN_LED_PIN = 27
YELLOW_LED_PIN = 26
RED_LED_PIN = 25
# Initialize pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
green_led = Pin(GREEN_LED_PIN, Pin.OUT)
yellow_led = Pin(YELLOW_LED_PIN, Pin.OUT)
red_led = Pin(RED_LED_PIN, Pin.OUT)
# Initialize I2C for OLED display
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Blynk Auth Token (your own)
BLYNK_AUTH_TOKEN = '5MLW9RMNk8-KytxzhedXEqoboKaK780l'
blynk = Blynk(BLYNK_AUTH_TOKEN)
def measure_distance():
trig.value(0) # Ensure TRIG is low
time.sleep_us(2)
trig.value(1) # Send a pulse
time.sleep_us(10)
trig.value(0) # Stop pulse
duration = time_pulse_us(echo, 1) # Read echo pin duration
distance = (duration * 0.0343) / 2 # Calculate distance in cm
return distance
def update_display(distance):
oled.fill(0) # Clear display
oled.text("Distance: {} cm".format(distance), 0, 0)
oled.show()
def control_alerts(distance):
# Control the LEDs and buzzer based on the distance
if distance > 200:
# Green LED: Distance > 200
green_led.on()
yellow_led.off()
red_led.off()
buzzer.off()
# Update Blynk LEDs
try:
blynk.virtual_write(2, 255) # Green LED on (V2)
blynk.virtual_write(1, 0) # Yellow LED off (V1)
blynk.virtual_write(0, 0) # Red LED off (V0)
except Exception as e:
print("Error updating Blynk LED V2:", e)
elif distance > 100:
# Yellow LED: 101 < Distance <= 200
green_led.off()
yellow_led.on()
red_led.off()
buzzer.off()
# Update Blynk LEDs
try:
blynk.virtual_write(2, 0) # Green LED off (V2)
blynk.virtual_write(1, 255) # Yellow LED on (V1)
blynk.virtual_write(0, 0) # Red LED off (V0)
except Exception as e:
print("Error updating Blynk LED V1:", e)
else:
# Red LED: Distance <= 100
green_led.off()
yellow_led.off()
red_led.on()
buzzer.on() # Sound alarm when too close
# Update Blynk LEDs
try:
blynk.virtual_write(2, 0) # Green LED off (V2)
blynk.virtual_write(1, 0) # Yellow LED off (V1)
blynk.virtual_write(0, 255) # Red LED on (V0)
except Exception as e:
print("Error updating Blynk LED V0:", e)
# Blynk event for V3 gauge widget
@blynk.handle_event('write V3')
def handle_v3(pin, value):
# Send the ultrasonic sensor's distance value to V3 gauge
distance = measure_distance()
try:
blynk.virtual_write(3, distance) # Send to V3 (gauge)
except Exception as e:
print("Error updating Blynk gauge V3:", e)
update_display(distance)
control_alerts(distance)
# Main loop
while True:
distance = measure_distance()
update_display(distance)
control_alerts(distance)
time.sleep(0.5) # Delay before next measurement
blynk.run() # Keep Blynk connection alive