from machine import Pin
import time
import math
import network
from umqtt.simple import MQTTClient
# ---------- WiFi Configuration ----------
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# ---------- MQTT Configuration ----------
MQTT_BROKER = "broker.hivemq.com"
MQTT_CLIENT_ID = "ESP32_MPU6050_SUB"
MQTT_TOPIC = b"sensordata"
# ---------- Vibration Threshold ----------
VIBRATION_THRESHOLD = 1.5 # in g
# ---------- LED Setup ----------
led = Pin(2, Pin.OUT) # Use onboard LED (GPIO2) or connect external LED
# ---------- 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 to WiFi:", wlan.ifconfig())
# ---------- MQTT Callback ----------
def sub_callback(topic, msg):
data = msg.decode().split(",")
ax, ay, az, temp = map(float, data)
# Calculate vibration magnitude
vibration = (ax**2 + ay**2 + (az-1.0)**2) ** 0.5
print("Received → Ax:{:.3f}, Ay:{:.3f}, Az:{:.3f}, Temp:{:.2f}°C, Vib:{:.3f}g".format(ax, ay, az, temp, vibration))
# Alert LED control
if vibration > VIBRATION_THRESHOLD:
print("⚠ ALERT: Significant vibration detected!")
led.on()
else:
led.off()
# ---------- Main Program ----------
connect_wifi()
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(sub_callback)
client.connect()
client.subscribe(MQTT_TOPIC)
print("Subscribed to topic:", MQTT_TOPIC)
while True:
client.check_msg() # Wait for new messages
time.sleep(0.2)