<from machine import Pin, I2C
import time, math
import random , fonctions
# Fonction équivalente à random.uniform(a, b)
def uniform(a, b):
return a + (random.getrandbits(16) / 65535) * (b - a)
# === Détection du capteur MPU6050 ===
SIMULATION = False
try:
import mpu6050
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
print("MPU6050 détecté.")
mpu = mpu6050.MPU6050(i2c)
mpu.wake()
except Exception as e:
print("MPU6050 non détecté, passage en mode simulation.")
SIMULATION = True
# === Seuils de détection ===
CHUTE_SEUIL = 2.0 * 9.81 # Chute détectée si magnitude > 2g
INCLINAISON_SEUIL = 30 # Inclinaison angulaire pour posture
# === Calcul des angles pitch/roll ===
def calculer_orientation(ax, ay, az):
pitch = math.atan2(ax, math.sqrt(ay**2 + az**2)) * 180 / math.pi
roll = math.atan2(ay, math.sqrt(ax**2 + az**2)) * 180 / math.pi
return abs(pitch), abs(roll)
# === Simulation de données (si capteur absent) ===
def read_simulated_accel():
ax = uniform(-2, 2) * 9.81
ay = uniform(-2, 2) * 9.81
az = uniform(0.5, 1.5) * 9.81
return ax, ay, az
# === Lecture des données accélération ===
def lire_acceleration():
if SIMULATION:
return read_simulated_accel()
else:
accel = mpu.read_accel_data()
ax = accel[0] / 16384 * 9.81
ay = accel[1] / 16384 * 9.81
az = accel[2] / 16384 * 9.81
return ax, ay, az
# ===================================== Programme principal ==============================
etat_precedent = None
# si la connexion wifi est établie
if fonctions.connect_wifi() : wifi = True
else: wifi = False
while True:
ax, ay, az = lire_acceleration()
magnitude = math.sqrt(ax**2 + ay**2 + az**2)
if magnitude > CHUTE_SEUIL:
print("Chute détectée !");etat = "chute" ; delay = 1
else:
pitch, roll = calculer_orientation(ax, ay, az)
if pitch < INCLINAISON_SEUIL and roll < INCLINAISON_SEUIL:
print("La personne est debout."); etat = "debout" ; delay = 1
elif pitch > INCLINAISON_SEUIL or roll > INCLINAISON_SEUIL:
if pitch > 45 or roll > 45:
print("La personne est allongée."); etat = "allonge"; delay = 8
else:
print("La personne est assise.");etat = "assise"; delay = 5
else:
print("Mouvement normal.");etat = "assise"; delay = 1
# Affiche changement d'état seulement s'il y en a un
if etat != etat_precedent:
print(f"[INFO] Changement d'état: {etat_precedent} → {etat}")
etat_precedent = etat
if wifi : fonctions.send_to_thingspeak(etat, magnitude)
print("------------------------------------------\n")
time.sleep(delay)