from machine import Pin, I2C
from imu import MPU6050
import network
import time
import math
import urequests
# ---------- WiFi ----------
WIFI_SSID = "Wokwi-GUEST" # Change if needed
WIFI_PASS = ""
# ---------- Blynk ----------
BLYNK_AUTH = "OXm2NIHwzwDbcDwt6q5CbN-yJPLiS2W7" # <-- Put your Blynk token here
BLYNK_URL = "http://blynk.cloud/external/api/update?token=" + BLYNK_AUTH
# Virtual Pins (configure these in Blynk app)
VPIN_X = "V0"
VPIN_Y = "V1"
VPIN_Z = "V2"
VPIN_TEMP = "V4"
VPIN_VIBRATION = "V3"
VPIN_ALERT = "V6"
# ---------- Threshold ----------
VIBRATION_THRESHOLD = 1.5 # g
# ---------- LED ----------
led = Pin(2, Pin.OUT) # ESP32 onboard LED
# ---------- WiFi Connect ----------
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 to WiFi:", wlan.ifconfig())
# ---------- Send Data to Blynk ----------
def blynk_update(pin, value):
try:
url = "{}&{}={}".format(BLYNK_URL, pin, value)
urequests.get(url)
except Exception as e:
print("⚠ Blynk Error:", e)
# ---------- Sensor Setup ----------
i2c = I2C(1, sda=Pin(21), scl=Pin(22), freq=400000)
mpu = MPU6050(i2c)
# ---------- Main Program ----------
connect_wifi()
print("📡 MPU6050 → Blynk Monitoring Started...")
while True:
try:
# Read MPU6050 data
ax = mpu.accel.x
ay = mpu.accel.y
az = mpu.accel.z
temp = mpu.temperature
# Calculate vibration magnitude (remove gravity on Z)
vibration = math.sqrt(ax**2 + ay**2 + (az - 1.0)**2)
# Print locally
print("X:{:.3f}, Y:{:.3f}, Z:{:.3f}, Temp:{:.2f}°C, Vib:{:.3f} g".format(ax, ay, az, temp, vibration))
# ---------- Send to Blynk ----------
blynk_update(VPIN_X, ax)
blynk_update(VPIN_Y, ay)
blynk_update(VPIN_Z, az)
blynk_update(VPIN_TEMP, temp)
blynk_update(VPIN_VIBRATION, vibration)
# ---------- Alert ----------
if vibration > VIBRATION_THRESHOLD:
print("⚠ ALERT: High vibration detected!")
led.on()
blynk_update(VPIN_ALERT, 1) # 1 = Alert
else:
led.off()
blynk_update(VPIN_ALERT, 0) # 0 = Normal
except Exception as e:
print("Error:", e)
time.sleep(1)