#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
#define BUZZER_PIN 18 // Buzzer actif
#define BUTTON_PIN 19 // Bouton pour arrêter l’alerte
bool alerteActive = false;
unsigned long tempsAlerte = 0;
const unsigned long DUREE_ALERTE = 5000; // 5 s max (optionnel)
void setup() {
Serial.begin(115200);
while (!Serial) delay(10);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
// Bouton avec résistance pull-up interne
pinMode(BUTTON_PIN, INPUT_PULLUP); // Repos = HIGH, appui = LOW[web:21][web:24]
Serial.println("MPU6050 + Buzzer + Bouton stop");
if (!mpu.begin()) {
Serial.println("Erreur: MPU6050 non trouvé!");
while (1) delay(10);
}
Serial.println("MPU6050 détecté!");
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
float accel_total = sqrt(a.acceleration.x*a.acceleration.x +
a.acceleration.y*a.acceleration.y +
a.acceleration.z*a.acceleration.z);
// Détection de chute
if (!alerteActive) {
if (accel_total < 2.0 || abs(a.acceleration.z) > 15.0) {
Serial.println("ALERTE: Chute détectée! Buzzer activé.");
digitalWrite(BUZZER_PIN, HIGH);
alerteActive = true;
tempsAlerte = millis();
}
}
// Lecture bouton (appui = LOW)
int etatBouton = digitalRead(BUTTON_PIN); // [web:28]
if (alerteActive && etatBouton == LOW) {
// L’utilisateur annule l’alarme
Serial.println("Alerte arrêtée par l'utilisateur.");
digitalWrite(BUZZER_PIN, LOW);
alerteActive = false;
delay(200); // anti-rebond simple
}
// Arrêt auto après DUREE_ALERTE (sécurité)
if (alerteActive && (millis() - tempsAlerte > DUREE_ALERTE)) {
Serial.println("Alerte arrêtée (timeout).");
digitalWrite(BUZZER_PIN, LOW);
alerteActive = false;
}
delay(50);
}