Failed to find MPU6050 chip

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

*/

// ----------------------------------------------------------------------------------
// :satellite_antenna: 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;

// ----------------------------------------------------------------------------------
// :face_with_head_bandage: 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: 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

// ----------------------------------------------------------------------------------
// :radio_button: 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?

// ----------------------------------------------------------------------------------
// :stopwatch: 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

// ----------------------------------------------------------------------------------
// :gear: 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...");
}

// ----------------------------------------------------------------------------------
// :repeat_button: 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(":police_car_light: 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(":bell_with_slash: 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())
{
// :police_car_light: Upload fall immediately
if (fallJustDetected)
{
fallJustDetected = false;
if (Firebase.RTDB.setInt(&fbdo, "/patient/fallStatus", fallStatus))
{
Serial.print(":police_car_light: Uploaded FALL DETECTED: ");
Serial.println(fallStatus);
}
else
{
Serial.println(":cross_mark: 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
}
`

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

Posting your code using code tags prevents parts of it being interpreted as HTML coding and makes it easier to copy for examination

In my experience the easiest way to tidy up the code and add the code tags is as follows

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

It is also helpful to post full error messages in code tags as it makes it easier to scroll through them and copy them for examination

What is the exact ESP32 you are using? SPI and I2C Pins vary a lot.

What is the serial printout from the setup sequence?

Does the other SPO2 sensor work?

How did you wired everything up?

What does the AI said, which wrote the code for you?

Xiao esp32 c3

Hi, @adibzikri
Welcome to the forum.

What is your electronics, programming, arduino, hardware experience?

Have you tried the example code that comes with the MPU6050 Library.

That looks like a lot of code to find this problem, did you write it yourself?
Did you write it in stages, testing each stage as you went?

Who is,

Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.

Thanks.. Tom.... :smiley: :+1: :coffee: :australia:

Maybe you also want to remove the credentials/keys etc. from your post.
You may need the help of a moderator to delete these from the earlier version of your post which will be created once you make the changes.

There is also a similar thread here which may give some trouble shooting tips: ESP32 not finding MPU6050 Gyroscope

The C3 Supermini has two different pinouts going around in the wild.

So maybe check if SDA = 8 and SCL = 9 works or SDA = 8 und SCL = 7.

Then try the ideas from the other posts. Reduce the code to the bare minimum or use a demo script to check the functionality.

I would suggest you start small, proving out pieces of code.

I usually start with a sensor, running the library example code. If that works move on to the next piece of hardware.

don't have a Xiao esp32 c3 but do have a ESP32C3 supermini
tried following code to test a MPU6050 using I2C GPIO4 SDA and GPIO5 SCL

// ESP32C3 Super Mini  Basic demo for accelerometer readings from Adafruit MPU6050

// select USB CDC on Boot: Enabled to enable Serial IO

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_MPU6050 mpu;

#define I2C_SDA 4
#define I2C_SCL 5

void setup() {
  Wire.begin(I2C_SDA, I2C_SCL);
  Serial.begin(115200);
  while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit MPU6050 test!");

  // Try to initialize!
  if (!mpu.begin(0x68)) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");

  mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
  Serial.print("Accelerometer range set to: ");
  switch (mpu.getAccelerometerRange()) {
  case MPU6050_RANGE_2_G:
    Serial.println("+-2G");
    break;
  case MPU6050_RANGE_4_G:
    Serial.println("+-4G");
    break;
  case MPU6050_RANGE_8_G:
    Serial.println("+-8G");
    break;
  case MPU6050_RANGE_16_G:
    Serial.println("+-16G");
    break;
  }
  mpu.setGyroRange(MPU6050_RANGE_500_DEG);
  Serial.print("Gyro range set to: ");
  switch (mpu.getGyroRange()) {
  case MPU6050_RANGE_250_DEG:
    Serial.println("+- 250 deg/s");
    break;
  case MPU6050_RANGE_500_DEG:
    Serial.println("+- 500 deg/s");
    break;
  case MPU6050_RANGE_1000_DEG:
    Serial.println("+- 1000 deg/s");
    break;
  case MPU6050_RANGE_2000_DEG:
    Serial.println("+- 2000 deg/s");
    break;
  }

  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.print("Filter bandwidth set to: ");
  switch (mpu.getFilterBandwidth()) {
  case MPU6050_BAND_260_HZ:
    Serial.println("260 Hz");
    break;
  case MPU6050_BAND_184_HZ:
    Serial.println("184 Hz");
    break;
  case MPU6050_BAND_94_HZ:
    Serial.println("94 Hz");
    break;
  case MPU6050_BAND_44_HZ:
    Serial.println("44 Hz");
    break;
  case MPU6050_BAND_21_HZ:
    Serial.println("21 Hz");
    break;
  case MPU6050_BAND_10_HZ:
    Serial.println("10 Hz");
    break;
  case MPU6050_BAND_5_HZ:
    Serial.println("5 Hz");
    break;
  }

  Serial.println("");
  delay(100);
}

void loop() {

  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  /* Print out the values */
  Serial.print("Acceleration X: ");
  Serial.print(a.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(a.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(a.acceleration.z);
  Serial.println(" m/s^2");

  Serial.print("Rotation X: ");
  Serial.print(g.gyro.x);
  Serial.print(", Y: ");
  Serial.print(g.gyro.y);
  Serial.print(", Z: ");
  Serial.print(g.gyro.z);
  Serial.println(" rad/s");

  Serial.print("Temperature: ");
  Serial.print(temp.temperature);
  Serial.println(" degC");

  Serial.println("");
  delay(5000);
}

appears to work OK - serial monitor output as it is moved around

Adafruit MPU6050 test!
MPU6050 Found!
Accelerometer range set to: +-8G
Gyro range set to: +- 500 deg/s
Filter bandwidth set to: 21 Hz

Acceleration X: -3.44, Y: -1.02, Z: 7.12 m/s^2
Rotation X: 0.35, Y: 1.58, Z: 0.07 rad/s
Temperature: 21.50 degC

Acceleration X: -9.56, Y: -0.65, Z: 0.73 m/s^2
Rotation X: -0.27, Y: 1.48, Z: 0.13 rad/s
Temperature: 22.02 degC

Acceleration X: 0.61, Y: -1.03, Z: -12.06 m/s^2
Rotation X: -0.04, Y: 0.54, Z: -0.15 rad/s
Temperature: 22.14 degC

Acceleration X: 1.01, Y: 9.10, Z: -5.94 m/s^2
Rotation X: -0.07, Y: 0.01, Z: 0.02 rad/s
Temperature: 22.25 degC

Acceleration X: 0.46, Y: -10.07, Z: 0.08 m/s^2
Rotation X: 0.26, Y: -0.60, Z: -0.18 rad/s
Temperature: 22.34 degC

Acceleration X: -8.76, Y: 1.94, Z: 0.97 m/s^2
Rotation X: 0.71, Y: -0.16, Z: -0.38 rad/s
Temperature: 22.38 degC

Acceleration X: -0.27, Y: 0.28, Z: 8.34 m/s^2
Rotation X: 0.15, Y: 0.03, Z: 0.00 rad/s
Temperature: 22.40 degC

Acceleration X: -0.27, Y: 0.29, Z: 8.36 m/s^2
Rotation X: 0.15, Y: 0.03, Z: 0.00 rad/s
Temperature: 22.42 degC