import network
import time
import random
from machine import Pin, I2C
from mpu6050 import MPU6050 # Works for MPU6500 too!
# --- WiFi Setup ---
ssid = "Wokwi-GUEST"
password = ""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Connecting to WiFi...")
while not wlan.isconnected():
time.sleep(1)
print("Connected:", wlan.ifconfig())
# --- MPU6050/MPU6500 Setup ---
i2c = I2C(0, scl=Pin(21), sda=Pin(20)) # Adjust pins if needed
mpu = MPU6050(i2c) # Also works with MPU6500
# --- GPIO Setup ---
led = Pin(13, Pin.OUT) # Single LED (Red recommended)
buzzer = Pin(15, Pin.OUT) # Buzzer
# --- Posture Classification Function ---
def classify_posture(ax, ay, az):
"""
0 → Standing upright
1 → Sitting / bending forward
2 → Lying down
3 → Fall detected
"""
threshold_fall = 15.0
magnitude = (ax**2 + ay**2 + az**2)**0.5
if magnitude > threshold_fall:
return 3 # Fall detected
if abs(az) > 9 and abs(ax) < 2 and abs(ay) < 2:
return 0 # Standing
if abs(az) < 6 and (abs(ax) > 3 or abs(ay) > 3):
return 1 # Sitting / Bending
if abs(az) < 3 and (abs(ax) > 6 or abs(ay) > 6):
return 2 # Lying down
return 1 # Default → sitting / bending
# --- Safe Zone Definition ---
SAFE_LAT_MIN = 12.9710
SAFE_LAT_MAX = 12.9722
SAFE_LON_MIN = 77.5940
SAFE_LON_MAX = 77.5952
def in_safe_zone(lat, lon):
return (SAFE_LAT_MIN <= lat <= SAFE_LAT_MAX) and (SAFE_LON_MIN <= lon <= SAFE_LON_MAX)
# --- Main Loop ---
while True:
# 1️⃣ Read MPU Data
accel = mpu.get_accel_data()
ax = accel['x']
ay = accel['y']
az = accel['z']
print(f"Accel: X={ax:.2f}, Y={ay:.2f}, Z={az:.2f}")
# 2️⃣ Posture Classification
posture_value = classify_posture(ax, ay, az)
print(f"Posture Value: {posture_value}")
# 3️⃣ Simulated Sensor Data
temp = random.uniform(25.0, 70.0)
humidity = random.uniform(30.0, 90.0)
# 4️⃣ Simulated GPS Data
gps_lat = 12.9716 + random.uniform(-0.0005, 0.0005)
gps_lon = 77.5946 + random.uniform(-0.0005, 0.0005)
print(f"GPS: ({gps_lat}, {gps_lon})")
# 5️⃣ LED and Buzzer Logic (1 LED version)
danger_posture = posture_value in [2, 3] # lying or fall
danger_zone = not in_safe_zone(gps_lat, gps_lon)
if danger_posture or danger_zone:
led.value(1) # LED ON
else:
led.value(0) # LED OFF
if danger_posture:
buzzer.value(1) # Buzzer ON
else:
buzzer.value(0) # Buzzer OFF
# 6️⃣ Wait before next cycle
time.sleep(3)