#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
Adafruit_MPU6050 mpu;
int buzzerPin = 26;
int freq = 1000; // frequência inicial
int freqAlta = 5000; // frequência depois de 10s
int intervalo = 500; // intervalo de beep em ms
unsigned long tempoAnterior = 0;
unsigned long tempoInicio = 0;
bool buzzerLigado = false;
bool quedaDetectada = false;
void setup() {
Serial.begin(115200);
if (!mpu.begin()) {
Serial.println("Não foi possível encontrar o MPU6050!");
while (1) delay(10);
}
Serial.println("MPU6050 encontrado!");
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
Serial.print("Y: ");
Serial.println(a.acceleration.y);
// Simulação de queda quando Y >= 15
if (a.acceleration.y >= 15) {
if (!quedaDetectada) {
quedaDetectada = true;
tempoInicio = millis(); // marca o início da queda
}
unsigned long agora = millis();
// alterna o estado do buzzer a cada "intervalo"
if (agora - tempoAnterior >= intervalo) {
tempoAnterior = agora; // 🔑 IMPORTANTE: atualizar o marcador!
if (buzzerLigado) {
noTone(buzzerPin);
buzzerLigado = false;
} else {
// escolhe frequência de acordo com tempo de queda
if (agora - tempoInicio >= 10000) {
tone(buzzerPin, freqAlta);
Serial.println("⚠️ O IDOSO TA MORRENDO CARA VAI AJUDAAAA!");
} else {
tone(buzzerPin, freq);
Serial.println("⚠️ O idoso caiu, ajuda ele!");
}
buzzerLigado = true;
}
}
} else {
noTone(buzzerPin);
buzzerLigado = false;
quedaDetectada = false;
}
delay(50);
}