Hi, im trying to run my coding using mpu6050.
Failed to find MPU6050 chip. Can someone help me? '/*
Project Code - Protected by Warranty
Created by: Mumu Service Centre
Contact: 010820431
Date : 29 Aug 2025
Note: This watermark acts as a warranty seal for the project.
Removing or altering this comment will void the warranty.
Library Used:
1. SparkFun MAX3010x Pulse and Proximity Sensor Library by SparkFun Electronics
2. Adafruit MPU6050 by Adafruit
3. Firebase Arduino Client Library for ESP8266 and ESP32 by Mobizt
4. Firebase Client by Mobizt
Safe Changes:
1. WIFI & Password
#define WIFI_SSID "Xiaomi14" // WiFi name
#define WIFI_PASSWORD "takdapassword1" // WiFi password
2. Upload Interval - changing this to less than 5 sec = will upload in less
than 5 sec & the fall detection has a period less than 5 sec to check.
const unsigned long uploadInterval = 5000; // 5000 = 5 Seconds
3. Led to Buzzer
For the sake of sanity, buzzer is set to pin 2
which is the built-in led pin.
You can also plug buzzer at pin 2 without changing the code.
If you do decide to check, please change it here.
#define LED_PIN 2
*/
// ----------------------------------------------------------------------------------
//
WIFI + FIREBASE CREDENTIALS
// ----------------------------------------------------------------------------------
#include <WiFi.h> // WiFi library for ESP32
#include <Firebase_ESP_Client.h> // Firebase library
#include <Adafruit_MPU6050.h> // For fall detection sensor (accelerometer/gyro)
#include <Adafruit_Sensor.h> // General sensor support
#include <Wire.h> // I2C communication
#include "MAX30105.h" // Heart rate sensor
#include "heartRate.h" // Helper for detecting beats
// --- WiFi details ---
#define WIFI_SSID "Xiaomi14" // WiFi name
#define WIFI_PASSWORD "takdapassword1" // WiFi password
// --- Firebase details ---
#define API_KEY "AIzaSyC4kD5a9mhwuKdA5rg5fUlL4lodf6fNCPw" // Firebase API key
#define DATABASE_URL "https://vitalchecker-7ae1c-default-rtdb.asia-southeast1.firebasedatabase.app/"
#define USER_EMAIL "staff0001@gmail.com" // Firebase login email
#define USER_PASSWORD "123456" // Firebase login password
// Firebase objects (for connection & data handling)
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;
// ----------------------------------------------------------------------------------
//
FALL DETECTION (MPU6050 ACCELEROMETER)
// ----------------------------------------------------------------------------------
Adafruit_MPU6050 mpu; // create MPU6050 sensor object
const float FREEFALL_THRESHOLD = 0.5; // threshold when falling (low G)
const float IMPACT_THRESHOLD = 1.0; // threshold when hitting ground (high G)
const unsigned long FALL_CHECK_WINDOW = 500; // time window to confirm fall (ms)
bool possibleFall = false; // flag if fall might be happening
unsigned long possibleFallTime = 0;// record time of suspected fall
// Fall status: 0 = no fall, 1 = fall detected, 2 = emergency button pressed
int fallStatus = 0;
bool fallJustDetected = false; // flag to upload fall to Firebase only once
int appPingPongState; // variable for ping-pong check with app
// ----------------------------------------------------------------------------------
//
HEART RATE + SpO2 (MAX30105 SENSOR)
// ----------------------------------------------------------------------------------
MAX30105 particleSensor; // create heart rate sensor object
long lastBeat = 0; // last heartbeat time
float beatsPerMinute = 0; // BPM from last beat
int beatAvg = 0; // smoothed BPM
int fakeSpO2 = 0; // fake oxygen % (since MAX30105 alone cannot measure real SpO₂)
String fingerStatus = "Not Detected"; // check if finger is on sensor
int lastBeatAvg = 0; // store BPM for Firebase
int lastSpO2 = 0; // store SpO₂ for Firebase
// ----------------------------------------------------------------------------------
//
BUTTON + LED CONTROL
// ----------------------------------------------------------------------------------
// KALAU ESP32 BUTTON 26, BUZZER 2
// KALAU XIAO BUTTON D9, BUZZER D10
#define EMERGENCY_BUTTON D9 // button pin <--------------------------------------------------------------------------------- Tukar kat sini
#define LED_PIN D10 // LED pin (onboard LED for ESP32 is GPIO2) <--------------------------------------------------------------------------------- Tukar kat sini
unsigned long lastButtonPress = 0; // last button press time
const unsigned long buttonDebounce = 500; // debounce time for button
unsigned long buzzerStartTime = 0; // when buzzer/LED was activated
bool buzzerActive = false; // is buzzer/LED on?
// ----------------------------------------------------------------------------------
//
TIMING CONTROL
// ----------------------------------------------------------------------------------
unsigned long lastUpload = 0; // last time we uploaded HR/SpO₂
const unsigned long uploadInterval = 5000; // upload every 5 sec
unsigned long lastBuzzerCheck = 0; // last time we checked buzzer state
const unsigned long buzzerCheckInterval = 1000; // check buzzer state every 1 sec
// ----------------------------------------------------------------------------------
//
SETUP FUNCTION
// ----------------------------------------------------------------------------------
void setup()
{
Serial.begin(115200); // start serial monitor
pinMode(LED_PIN, OUTPUT); // set LED as output
digitalWrite(LED_PIN, LOW); // keep LED off initially
pinMode(EMERGENCY_BUTTON, INPUT_PULLUP); // set button with internal pull-up resistor
// --- Connect to WiFi ---
Serial.print("Connecting to WiFi: ");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(300); // wait 300ms
Serial.print("."); // print dots until connected
}
Serial.println("\nWiFi connected!"); // WiFi success
// --- Setup Firebase ---
config.api_key = API_KEY;
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;
config.database_url = DATABASE_URL;
Firebase.reconnectNetwork(true); // auto reconnect WiFi
Firebase.begin(&config, &auth); // start Firebase
Serial.println("Firebase initialized");
// --- Init MPU6050 (fall sensor) ---
Wire.begin();
if (!mpu.begin())
{
Serial.println("Failed to find MPU6050 chip");
while (1) { delay(10); } // stop here if not found
}
mpu.setAccelerometerRange(MPU6050_RANGE_8_G); // set sensitivity
Serial.println("MPU6050 Ready (Fall Detection)");
// --- Init MAX30105 (HR sensor) ---
if (!particleSensor.begin(Wire, I2C_SPEED_FAST))
{
Serial.println("MAX30105 not found. Check wiring!");
while (1); // stop here if not found
}
// configure HR sensor
byte ledBrightness = 0x1F;
byte sampleAverage = 4;
byte ledMode = 2;
int sampleRate = 400;
int pulseWidth = 411;
int adcRange = 4096;
particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange);
Serial.println("MAX30105 Ready (HR + SpO2). Place finger...");
}
// ----------------------------------------------------------------------------------
//
MAIN LOOP
// ----------------------------------------------------------------------------------
void loop()
{
unsigned long now = millis(); // current time in ms
// ---------------- EMERGENCY BUTTON ----------------
if (digitalRead(EMERGENCY_BUTTON) == LOW && (now - lastButtonPress > buttonDebounce))
{
lastButtonPress = now; // save time
fallStatus = 2; // mark as emergency
Serial.println("
Emergency button pressed! Setting status=2");
Firebase.RTDB.setInt(&fbdo, "/patient/fallStatus", 2); // send to Firebase
digitalWrite(LED_PIN, HIGH); // turn on LED
}
// ---------------- FALL DETECTION ----------------
if (fallStatus == 0) // only detect if no fall/emergency already
{
sensors_event_t a, g, temp; // accel, gyro, temp events
mpu.getEvent(&a, &g, &temp); // read MPU6050
// calculate total acceleration (3D vector)
float totalAcc = sqrt(pow(a.acceleration.x, 2) +
pow(a.acceleration.y, 2) +
pow(a.acceleration.z, 2));
// check for free fall
if (totalAcc < FREEFALL_THRESHOLD * 9.81)
{
if (!possibleFall)
{
possibleFall = true;
possibleFallTime = now; // start timing possible fall
}
}
// check if impact follows free fall within time window
if (possibleFall)
{
if (now - possibleFallTime < FALL_CHECK_WINDOW)
{
if (totalAcc > IMPACT_THRESHOLD * 9.81)
{
fallStatus = 1; // mark as fall detected
fallJustDetected = true;
possibleFall = false;
digitalWrite(LED_PIN, HIGH); // turn on LED
}
}
else
{
possibleFall = false; // reset if no impact found
}
}
}
// ---------------- HEART RATE + SPO2 ----------------
long irValue = particleSensor.getIR(); // read infrared from HR sensor
if (irValue < 70000)
{
fingerStatus = "Not Detected"; // no finger
}
else
{
fingerStatus = "Detected"; // finger detected
if (checkForBeat(irValue)) // detect heartbeat
{
long delta = now - lastBeat; // time since last beat
lastBeat = now;
beatsPerMinute = 60.0 / (delta / 1000.0); // calculate BPM
if (beatsPerMinute > 20 && beatsPerMinute < 250)
{
beatAvg = (beatAvg * 3 + beatsPerMinute) / 4; // smooth BPM
fakeSpO2 = 94 + (beatAvg % 6); // fake oxygen level
lastBeatAvg = beatAvg; // save for Firebase
lastSpO2 = fakeSpO2;
}
}
}
// ---------------- BUZZER/LED CONTROL FROM APP ----------------
if (Firebase.ready() && (now - lastBuzzerCheck >= buzzerCheckInterval))
{
lastBuzzerCheck = now; // save time
int buzzerState;
if (Firebase.RTDB.getInt(&fbdo, "/Buzzer/state", &buzzerState))
{
if (buzzerState == 1 && !buzzerActive)
{
buzzerActive = true;
buzzerStartTime = now;
digitalWrite(LED_PIN, HIGH); // turn on LED
Serial.println("🔔 Buzzer/LED triggered by app!");
}
}
}
// Auto turn off LED after 5s
if (buzzerActive && (now - buzzerStartTime >= 5000))
{
buzzerActive = false;
digitalWrite(LED_PIN, LOW); // turn off LED
Firebase.RTDB.setInt(&fbdo, "/Buzzer/state", 0); // reset in Firebase
Serial.println("
Buzzer/LED OFF after 5s, reset state in Firebase");
}
// ---------------- SERIAL OUTPUT (DEBUG) ----------------
Serial.print("[Status] FallStatus=");
Serial.print(fallStatus);
Serial.print(" | Finger=");
Serial.print(fingerStatus);
Serial.print(" | Avg BPM=");
Serial.print(lastBeatAvg);
Serial.print(" | SpO2=");
Serial.print(lastSpO2);
Serial.println("%");
// ---------------- FIREBASE UPLOAD ----------------
if (Firebase.ready())
{
//
Upload fall immediately
if (fallJustDetected)
{
fallJustDetected = false;
if (Firebase.RTDB.setInt(&fbdo, "/patient/fallStatus", fallStatus))
{
Serial.print("
Uploaded FALL DETECTED: ");
Serial.println(fallStatus);
}
else
{
Serial.println("
Fall upload failed: " + fbdo.errorReason());
}
}
// Upload HR/SpO₂ every 5 sec
if (now - lastUpload > uploadInterval)
{
lastUpload = now;
Firebase.RTDB.setInt(&fbdo, "/patient/heartRate", lastBeatAvg);
Firebase.RTDB.setInt(&fbdo, "/patient/bloodOxygen", lastSpO2);
// ---- PING PONG FEATURE ----
if (Firebase.RTDB.getInt(&fbdo, "/app_ping_pong", &appPingPongState))
{
if (appPingPongState == 0)
{
Serial.println("Received ping from app, sending pong...");
Firebase.RTDB.setInt(&fbdo, "/app_ping_pong", 1);
}
}
// ---- RESET FALL STATUS FROM APP ----
int fbFallValue;
if (Firebase.RTDB.getInt(&fbdo, "/patient/fallStatus", &fbFallValue))
{
if (fbFallValue == 0 && fallStatus != 0)
{
Serial.println("🟢 Firebase reset received. Clearing fall/emergency status.");
fallStatus = 0;
digitalWrite(LED_PIN, LOW); // turn off LED too
}
}
}
}
delay(5); // short pause so ESP32 is not overloaded
}
`
