import network
import urequests
import time
import random
from machine import Pin, I2C
from mpu6050 import MPU6050
# --- 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())
# --- ThingSpeak Setup ---
THINGSPEAK_API_KEY = "1C5R1X7JPJXM709I"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# --- MPU Setup ---
i2c = I2C(0, scl=Pin(21), sda=Pin(20))
mpu = MPU6050(i2c)
# --- GPIO Setup ---
buzzer = Pin(15, Pin.OUT)
led = Pin(14, Pin.OUT) # Single LED for safe/danger indication
# --- Safe Zone Definition ---
SAFE_LAT_MIN = 12.9711
SAFE_LAT_MAX = 12.9721
SAFE_LON_MIN = 77.5941
SAFE_LON_MAX = 77.5951
# --- Check Safe Zone ---
def in_safe_zone(lat, lon):
return (SAFE_LAT_MIN <= lat <= SAFE_LAT_MAX) and (SAFE_LON_MIN <= lon <= SAFE_LON_MAX)
# --- Posture Classification ---
def classify_posture(ax, ay, az):
threshold_fall = 15.0
magnitude = (ax**2 + ay**2 + az**2)**0.5
if magnitude > threshold_fall:
return 3
if abs(az) > 9 and abs(ax) < 2 and abs(ay) < 2:
return 0
if abs(az) < 6 and (abs(ax) > 3 or abs(ay) > 3):
return 1
if abs(az) < 3 and (abs(ax) > 6 or abs(ay) > 6):
return 2
return 1
# --- Data Upload ---
def post_to_thingspeak(posture_value, gps_lat, gps_lon):
payload = (
f"api_key={THINGSPEAK_API_KEY}"
f"&pos={posture_value}"
f"&field2={gps_lat}"
f"&field3={gps_lon}"
)
response = urequests.post(THINGSPEAK_URL, data=payload)
print("Response:", response.text)
response.close()
# --- Main Loop ---
while True:
accel = mpu.get_accel_data()
ax = accel['x']
ay = accel['y']
az = accel['z']
posture_value = classify_posture(ax, ay, az)
temp = random.uniform(25.0, 70.0)
humidity = random.uniform(30.0, 90.0)
gps_lat = 12.9716 + random.uniform(-0.0005, 0.0005)
gps_lon = 77.5946 + random.uniform(-0.0005, 0.0005)
print(f"Sending → Posture={posture_value}, GPS=({gps_lat},{gps_lon})")
# --- Buzzer Logic ---
if posture_value == 2 or posture_value == 3:
buzzer.value(1)
else:
buzzer.value(0)
# --- Single LED Safe Zone Logic ---
if in_safe_zone(gps_lat, gps_lon):
led.value(1) # LED ON = Safe zone
else:
led.value(0) # LED OFF = Danger zone
# --- Send to ThingSpeak ---
post_to_thingspeak(posture_value, gps_lat, gps_lon)
time.sleep(5)