from machine import Pin, I2C
from imu import MPU6050
import time
import math
import urequests
import network
BLYNK_AUTH_TOKEN = "Kxd7tjVXDHFFxcl3-U8DS53gC_jC-DXV" # Replace with your Blynk Auth Token
SSID = "Wokwi-GUEST" # Replace with your Wi-Fi SSID
PASS = "" # Replace with your Wi-Fi password
i2c = I2C(1, sda=Pin(21), scl=Pin(22), freq=400000)
mpu = MPU6050(i2c)
# Vibration detection parameters
VIBRATION_THRESHOLD = 1.5 # Threshold for significant vibration (in g)
WINDOW_SIZE = 5 # Moving average window size for smoothing
SCALE_FACTOR = 10 # Scaling factor for Blynk gauge (e.g., 1.5 g -> 150 units)
# Connect to Wi-Fi
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
print('Connecting to network...')
sta_if.active(True)
sta_if.connect(SSID, PASS)
while not sta_if.isconnected():
time.sleep(0.5)
print('Network config:', sta_if.ifconfig())
# Calculate vibration magnitude with gravity compensation
def calculate_vibration():
ax = mpu.accel.x
ay = mpu.accel.y
az = mpu.accel.z - 1.0 # Subtract 1g from Z-axis to remove gravity
# Calculate magnitude of acceleration vector
vibration = math.sqrt(ax * ax + ay * ay + az * az)
return vibration
# Moving average to smooth vibration data
def moving_average(new_value, prev_avg, window_size):
return (prev_avg * (window_size - 1) + new_value) / window_size
# Send data to Blynk
def send_to_blynk(vibration, temperature):
try:
# Scale vibration for Blynk
scaled_vibration = vibration * SCALE_FACTOR
# Send scaled vibration to V1
urequests.get("https://blr1.blynk.cloud/external/api/update?token={}&V1={}".format(BLYNK_AUTH_TOKEN, scaled_vibration))
# Send temperature to V0
urequests.get("https://blr1.blynk.cloud/external/api/update?token={}&V0={}".format(BLYNK_AUTH_TOKEN, temperature))
print("Sent to Blynk - Scaled Vibration: {:.1f} units, Temperature: {:.2f} °C".format(scaled_vibration, temperature))
except Exception as e:
print("Error sending to Blynk:", e)
# Initialize variables
vibration_avg = 0.0
# Connect to Wi-Fi
connect_wifi()
print("Vibration Testing Started...")
# Main loop
while True:
try:
vibration = calculate_vibration()
# Update moving average
vibration_avg = moving_average(vibration, vibration_avg, WINDOW_SIZE)
# Print sensor data
print("-" * 50)
print("Accel X: {:.3f}, Y: {:.3f}, Z: {:.3f} g".format(mpu.accel.x, mpu.accel.y, mpu.accel.z))
print("Gyro X: {:.3f}, Y: {:.3f}, Z: {:.3f} deg/s".format(mpu.gyro.x, mpu.gyro.y, mpu.gyro.z))
print("Temperature: {:.2f} °C".format(mpu.temperature))
print("Vibration: {:.3f} g (smoothed)".format(vibration_avg))
print("Raw Vibration: {:.3f} g".format(vibration))
if vibration > VIBRATION_THRESHOLD:
print("⚠ ALERT: Significant vibration detected!")
else:
print("Vibration within normal range.")
# Send data to Blynk
send_to_blynk(vibration_avg, mpu.temperature)
except Exception as e:
print("Error:", e)
time.sleep(1) # Update every 1 second