### Get Clock Source Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current clock source setting. Use this to verify the sensor's clock configuration. ```cpp mpu.getClock(); ``` -------------------------------- ### Example: Read Temperature Sensor Metadata Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Demonstrates how to obtain temperature sensor metadata and print its name, operating range, and resolution. This helps in understanding the precision and limits of the temperature readings. ```cpp Adafruit_Sensor *temp = mpu.getTemperatureSensor(); sensor_t sensor_data; temp->getSensor(&sensor_data); Serial.print("Sensor name: "); Serial.println(sensor_data.name); Serial.print("Range: "); Serial.print(sensor_data.min_value); Serial.print(" to "); Serial.print(sensor_data.max_value); Serial.println(" °C"); Serial.print("Resolution: "); Serial.print(sensor_data.resolution); Serial.println(" °C per LSB"); ``` -------------------------------- ### Set MPU6050 Cycle Rate Example Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/types.md Demonstrates how to configure the sensor to wake up at a specific rate for measurements. Ensure sleep mode is disabled and cycle mode is enabled after setting the rate. ```cpp mpu.enableSleep(false); // Must disable sleep first mpu.setCycleRate(MPU6050_CYCLE_5_HZ); mpu.enableCycle(true); // Wake every 200 ms to measure ``` -------------------------------- ### Minimal MPU6050 Initialization and Reading Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/README.md This minimal example demonstrates how to initialize the MPU6050 sensor and read accelerometer data. It includes basic error checking for sensor initialization. The loop continuously reads and prints X-axis acceleration. ```cpp Adafruit_MPU6050 mpu; void setup() { Serial.begin(115200); if (!mpu.begin()) { Serial.println("Failed to find MPU6050"); while (1) delay(10); } } void loop() { sensors_event_t accel, gyro, temp; mpu.getEvent(&accel, &gyro, &temp); Serial.print("Accel X: "); Serial.println(accel.acceleration.x); delay(100); } ``` -------------------------------- ### Example: Read Gyroscope Sensor Metadata Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Demonstrates how to obtain gyroscope sensor metadata and print its name, maximum value, and resolution. This is useful for verifying sensor configuration and understanding its output range. ```cpp Adafruit_Sensor *gyro = mpu.getGyroSensor(); sensor_t sensor_data; gyro->getSensor(&sensor_data); Serial.print("Sensor name: "); Serial.println(sensor_data.name); Serial.print("Max value: "); Serial.print(sensor_data.max_value); Serial.println(" rad/s"); Serial.print("Resolution: "); Serial.print(sensor_data.resolution); Serial.println(" rad/s per LSB"); ``` -------------------------------- ### Unified Sensor Interface Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Utilize the Adafruit_Sensor interface for abstract sensor access. This example retrieves pointers to the accelerometer, gyroscope, and temperature sensors, queries their metadata, and reads data through the unified interface. ```cpp #include #include #include Adafruit_MPU6050 mpu; // Store sensor pointers Adafruit_Sensor *accel_sensor; Adafruit_Sensor *gyro_sensor; Adafruit_Sensor *temp_sensor; void setup() { Serial.begin(115200); while (!Serial) delay(10); if (!mpu.begin()) { while (1) delay(10); } // Get unified sensor interfaces accel_sensor = mpu.getAccelerometerSensor(); gyro_sensor = mpu.getGyroSensor(); temp_sensor = mpu.getTemperatureSensor(); if (!accel_sensor || !gyro_sensor || !temp_sensor) { Serial.println("Failed to get sensor interfaces"); while (1) delay(10); } // Query sensor metadata sensor_t accel_info; accel_sensor->getSensor(&accel_info); Serial.print("Accelerometer: "); Serial.println(accel_info.name); Serial.print(" Range: "); Serial.print(accel_info.min_value); Serial.print(" to "); Serial.print(accel_info.max_value); Serial.println(" m/s²"); } void loop() { // Can now read sensors via unified interface sensors_event_t accel_event, gyro_event, temp_event; if (accel_sensor->getEvent(&accel_event)) { Serial.print("Acceleration: "); Serial.println(accel_event.acceleration.x); } if (gyro_sensor->getEvent(&gyro_event)) { Serial.print("Rotation: "); Serial.println(gyro_event.gyro.z); } if (temp_sensor->getEvent(&temp_event)) { Serial.print("Temperature: "); Serial.println(temp_event.temperature); } delay(500); } ``` -------------------------------- ### Set MPU6050 FSYNC Output Example Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/types.md Configures the FSYNC pin to output the LSB of temperature data. This allows an external system to trigger actions based on temperature readings. ```cpp // Output temperature LSB on FSYNC pin for external sync mpu.setFsyncSampleOutput(MPU6050_FSYNC_OUT_TEMP); ``` -------------------------------- ### Checking Sensor Type with SENSOR_TYPE_ACCELEROMETER Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/types.md Example demonstrating how to retrieve sensor metadata using getSensor() and check if the sensor type is an accelerometer using the SENSOR_TYPE_ACCELEROMETER constant. ```cpp sensor_t info; mpu.getAccelerometerSensor()->getSensor(&info); if (info.type == SENSOR_TYPE_ACCELEROMETER) { Serial.println("This is an accelerometer"); } ``` -------------------------------- ### Example: Read Temperature Sensor Event Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Shows how to retrieve temperature sensor event data and print the die temperature in Celsius. This is useful for monitoring the chip's temperature for thermal management or compensation. ```cpp Adafruit_Sensor *temp = mpu.getTemperatureSensor(); sensors_event_t event; if (temp->getEvent(&event)) { Serial.print("Die temperature: "); Serial.print(event.temperature); Serial.println(" °C"); } ``` -------------------------------- ### Read Individual Sensors Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Provides examples for reading data from the accelerometer, gyroscope, and temperature sensors individually. This pattern is useful when you only need data from specific sensors. ```cpp // Read only accelerometer sensors_event_t accel_event; Adafruit_Sensor *accel = mpu.getAccelerometerSensor(); accel->getEvent(&accel_event); // Read only gyroscope sensors_event_t gyro_event; Adafruit_Sensor *gyro = mpu.getGyroSensor(); gyro->getEvent(&gyro_event); // Read only temperature sensors_event_t temp_event; Adafruit_Sensor *temp = mpu.getTemperatureSensor(); temp->getEvent(&temp_event); ``` -------------------------------- ### Get Accelerometer High-Pass Filter Setting Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current high-pass filter setting for the accelerometer. Use this to verify the current filter configuration. ```cpp mpu.getHighPassFilter(); ``` -------------------------------- ### Get Temperature Sensor Interface Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Retrieves an Adafruit_Sensor compatible interface for the temperature sensor. This allows integration with other libraries expecting the standard Adafruit_Sensor interface. ```cpp Adafruit_Sensor *getTemperatureSensor(void); ``` ```cpp Adafruit_Sensor *sensor = mpu.getTemperatureSensor(); sensor_t temp_sensor_info; sensor->getSensor(&temp_sensor_info); Serial.print("Temperature sensor name: "); Serial.println(temp_sensor_info.name); ``` -------------------------------- ### Get Digital Low-Pass Filter Bandwidth Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current Digital Low-Pass Filter bandwidth setting. Use this to check the current filtering configuration. ```cpp mpu6050_bandwidth_t bw = mpu.getFilterBandwidth(); switch (bw) { case MPU6050_BAND_260_HZ: Serial.println("Bandwidth is 260 Hz"); break; case MPU6050_BAND_184_HZ: Serial.println("Bandwidth is 184 Hz"); break; // ... other cases } ``` -------------------------------- ### begin() Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Sets up the hardware and initializes I2C communication. Returns `true` if initialization is successful, `false` otherwise. ```APIDOC ## begin() ### Description Sets up the hardware and initializes I2C communication. Returns `true` if initialization is successful, `false` otherwise. ### Method `bool begin(uint8_t i2c_addr = MPU6050_I2CADDR_DEFAULT, TwoWire *wire = &Wire, int32_t sensorID = 0);` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **i2c_addr** (uint8_t) - Optional - I2C address of the sensor (0x68 with AD0 low, 0x69 with AD0 high). Default: 0x68 - **wire** (TwoWire*) - Optional - Pointer to the Wire object for I2C communication. Default: &Wire - **sensorID** (int32_t) - Optional - User-defined ID to differentiate between multiple sensors. Default: 0 ### Returns `true` if initialization successful, `false` if chip not found or I2C communication failed ### Request Example ```cpp Adafruit_MPU6050 mpu; void setup() { if (!mpu.begin()) { Serial.println("Failed to find MPU6050 chip"); while (1) delay(10); } Serial.println("MPU6050 initialized!"); } ``` ``` -------------------------------- ### Get Accelerometer Event Data Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Reads the latest accelerometer data and populates a sensors_event_t structure. Use this to get X, Y, and Z acceleration values. ```cpp Adafruit_Sensor *accel = mpu.getAccelerometerSensor(); sensors_event_t event; if (accel->getEvent(&event)) { Serial.print("Acceleration (m/s²): "); Serial.print(event.acceleration.x); Serial.print(", "); Serial.print(event.acceleration.y); Serial.print(", "); Serial.println(event.acceleration.z); } ``` -------------------------------- ### Typical Usage Flow Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/API-SUMMARY.md Demonstrates the standard workflow for initializing, configuring, and reading data from the MPU6050 sensor. Ensure proper error handling during initialization. ```cpp #include #include #include Adafruit_MPU6050 mpu; void setup() { Serial.begin(115200); // 1. Initialize if (!mpu.begin()) { Serial.println("Failed to find MPU6050"); while (1) delay(10); } // 2. Configure mpu.setAccelerometerRange(MPU6050_RANGE_8_G); mpu.setGyroRange(MPU6050_RANGE_500_DEG); mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); } void loop() { // 3. Read sensors sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); // 4. Use data Serial.print("Accel X: "); Serial.println(a.acceleration.x); delay(100); } ``` -------------------------------- ### Get Gyroscope Event Data Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Reads the latest gyroscope data and populates a sensors_event_t structure. Use this to get X, Y, and Z angular velocity values in radians per second. ```cpp Adafruit_Sensor *gyro = mpu.getGyroSensor(); sensors_event_t event; if (gyro->getEvent(&event)) { Serial.print("Rotation (rad/s): "); Serial.print(event.gyro.x); Serial.print(", "); Serial.print(event.gyro.y); Serial.print(", "); Serial.println(event.gyro.z); } ``` -------------------------------- ### Get Gyroscope Measurement Range Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current gyroscope measurement range. Use this to determine the sensitivity of the gyroscope readings. ```cpp mpu6050_gyro_range_t range = mpu.getGyroRange(); switch (range) { case MPU6050_RANGE_250_DEG: Serial.println("Range is ±250 deg/s"); break; case MPU6050_RANGE_500_DEG: Serial.println("Range is ±500 deg/s"); break; case MPU6050_RANGE_1000_DEG: Serial.println("Range is ±1000 deg/s"); break; case MPU6050_RANGE_2000_DEG: Serial.println("Range is ±2000 deg/s"); break; } ``` -------------------------------- ### Detecting Initialization Failure with begin() Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Check the boolean return value of the begin() function to detect if the MPU6050 sensor failed to initialize. If initialization fails, consider handling the error by stopping, waiting, and retrying, or falling back to alternative operations. ```cpp Adafruit_MPU6050 mpu; if (!mpu.begin()) { Serial.println("MPU6050 initialization failed!"); // Handle error: // - Stop initialization // - Wait and retry // - Fall back to alternative operation while (1) delay(10); // Halt execution } ``` -------------------------------- ### Get Gyroscope Sensor Interface Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Retrieves an Adafruit_Sensor compatible interface for the gyroscope. This allows access to rotation data in a standardized format. ```cpp Adafruit_Sensor *getGyroSensor(void); ``` ```cpp Adafruit_Sensor *gyro_sensor = mpu.getGyroSensor(); sensors_event_t gyro_event; gyro_sensor->getEvent(&gyro_event); Serial.print("Rotation Z: "); Serial.println(gyro_event.gyro.z); ``` -------------------------------- ### Basic MPU6050 Initialization and Reading Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Initializes the MPU6050 sensor and continuously reads acceleration, gyroscope, and temperature data. Requires Wire, Adafruit_Sensor, and Adafruit_MPU6050 libraries. Prints data to the serial monitor every 500ms. ```cpp #include #include #include Adafruit_MPU6050 mpu; void setup() { Serial.begin(115200); while (!Serial) delay(10); if (!mpu.begin()) { Serial.println("Failed to find MPU6050"); while (1) delay(10); } Serial.println("MPU6050 initialized"); } void loop() { sensors_event_t accel, gyro, temp; mpu.getEvent(&accel, &gyro, &temp); Serial.print("Acceleration (m/s²): "); Serial.print(accel.acceleration.x); Serial.print(", "); Serial.print(accel.acceleration.y); Serial.print(", "); Serial.println(accel.acceleration.z); Serial.print("Rotation (rad/s): "); Serial.print(gyro.gyro.x); Serial.print(", "); Serial.print(gyro.gyro.y); Serial.print(", "); Serial.println(gyro.gyro.z); Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" °C"); Serial.println("---"); delay(500); } ``` -------------------------------- ### Get Accelerometer Sensor Interface Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Retrieves an Adafruit_Sensor compatible interface for the accelerometer. This is useful for accessing acceleration data in a standardized format. ```cpp Adafruit_Sensor *getAccelerometerSensor(void); ``` ```cpp Adafruit_Sensor *accel_sensor = mpu.getAccelerometerSensor(); sensors_event_t accel_event; accel_sensor->getEvent(&accel_event); Serial.print("Acceleration X: "); Serial.println(accel_event.acceleration.x); ``` -------------------------------- ### Get Sample Rate Divisor Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current sample rate divisor. This value is used to calculate the current measurement rate. ```cpp uint8_t divisor = mpu.getSampleRateDivisor(); int sampleRate = 1000 / (1 + divisor); Serial.print("Sample rate: "); Serial.print(sampleRate); Serial.println(" Hz"); ``` -------------------------------- ### Get Gyroscope Sensor Metadata Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Retrieves static metadata about the gyroscope sensor. Use this to understand the sensor's capabilities and limitations. ```cpp void getSensor(sensor_t *sensor); ``` -------------------------------- ### Create Adafruit_MPU6050 Instance Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Instantiates the MPU6050 sensor object. The sensor must be initialized using the begin() method before it can be used. ```cpp Adafruit_MPU6050 mpu; ``` -------------------------------- ### Get Current Cycle Rate Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current cycle rate setting of the sensor. This function returns the currently configured `mpu6050_cycle_rate_t` value. ```cpp mpu6050_cycle_rate_t getCycleRate(void); ``` -------------------------------- ### Adafruit_MPU6050 Constructor Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Creates a new MPU6050 instance. The sensor must be initialized with `begin()` before use. ```APIDOC ## Adafruit_MPU6050() ### Description Creates a new MPU6050 instance. The sensor must be initialized with `begin()` before use. ### Method Constructor ### Parameters None ``` -------------------------------- ### Include Required Libraries Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/README.md Include the necessary header files for the Adafruit MPU6050 library, the unified sensor framework, and the Wire library for I2C communication. ```cpp #include #include #include ``` -------------------------------- ### Configuring Multiple MPU6050 Sensors Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Demonstrates how to initialize and configure two MPU6050 sensors on the same I2C bus, each at a different address. Shows independent configuration of accelerometer ranges for each sensor. ```cpp #include #include #include // Two sensors on same I2C bus at different addresses Adafruit_MPU6050 mpu_0x68; // Default address Adafruit_MPU6050 mpu_0x69; // AD0 pulled HIGH void setup() { Serial.begin(115200); while (!Serial) delay(10); // Initialize first sensor if (!mpu_0x68.begin(0x68)) { Serial.println("Failed to find MPU6050 at 0x68"); while (1) delay(10); } Serial.println("Found MPU6050 at 0x68"); // Initialize second sensor if (!mpu_0x69.begin(0x69)) { Serial.println("Failed to find MPU6050 at 0x69"); while (1) delay(10); } Serial.println("Found MPU6050 at 0x69"); // Configure each independently mpu_0x68.setAccelerometerRange(MPU6050_RANGE_8_G); mpu_0x69.setAccelerometerRange(MPU6050_RANGE_16_G); } void loop() { sensors_event_t a0, g0, t0; sensors_event_t a1, g1, t1; mpu_0x68.getEvent(&a0, &g0, &t0); mpu_0x69.getEvent(&a1, &g1, &t1); Serial.print("Sensor 0x68 - Accel X: "); Serial.print(a0.acceleration.x); Serial.print(" | Sensor 0x69 - Accel X: "); Serial.println(a1.acceleration.x); delay(500); } ``` -------------------------------- ### Get Current Accelerometer Range Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Retrieves the current accelerometer measurement range setting. This is useful for understanding the sensitivity and maximum measurable values. ```cpp mpu6050_accel_range_t range = mpu.getAccelerometerRange(); switch (range) { case MPU6050_RANGE_2_G: Serial.println("Range is ±2G"); break; case MPU6050_RANGE_4_G: Serial.println("Range is ±4G"); break; case MPU6050_RANGE_8_G: Serial.println("Range is ±8G"); break; case MPU6050_RANGE_16_G: Serial.println("Range is ±16G"); break; } ``` -------------------------------- ### Handling I2C Errors During MPU6050 Initialization Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Provides a robust method for initializing the MPU6050, including error checking and troubleshooting steps for I2C communication failures. It attempts initialization and retries if the initial attempt fails. ```cpp // Safe initialization with I2C debugging Serial.begin(115200); delay(100); Adafruit_MPU6050 mpu; Serial.println("Attempting to initialize MPU6050..."); // Attempt initialization if (!mpu.begin()) { Serial.println("Failed to communicate with MPU6050"); Serial.println("Troubleshooting steps:"); Serial.println("1. Check I2C address (0x68 default, 0x69 if AD0=HIGH)"); Serial.println("2. Check power supply (3.3V or 5V)"); Serial.println("3. Check SDA/SCL wiring"); Serial.println("4. Check for I2C pull-ups (4.7kΩ recommended)"); Serial.println("5. Verify sensor is MPU6050, not similar part"); // Retry after delay delay(2000); if (mpu.begin()) { Serial.println("Initialization successful on retry!"); } else { Serial.println("Still failing. Check hardware."); while (1) delay(10); // Halt } } ``` -------------------------------- ### Get Accelerometer Sensor Metadata Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Retrieves static metadata about the accelerometer sensor, such as its name, version, and value ranges. Useful for understanding sensor capabilities. ```cpp Adafruit_Sensor *accel = mpu.getAccelerometerSensor(); sensor_t sensor_data; accel->getSensor(&sensor_data); Serial.print("Sensor name: "); Serial.println(sensor_data.name); Serial.print("Max value: "); Serial.print(sensor_data.max_value); Serial.println(" m/s²"); Serial.print("Resolution: "); Serial.print(sensor_data.resolution); Serial.println(" mg/LSB"); ``` -------------------------------- ### Include Adafruit MPU6050 and Sensor Headers Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Include the necessary headers for using the Adafruit MPU6050 unified sensor classes and the general Adafruit sensor library. ```cpp #include #include ``` -------------------------------- ### Add Startup Delay for Sensor Stabilization Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Implement a delay after initializing the MPU6050 to allow the sensor's oscillator to stabilize, preventing erroneous readings during the initial power-on period. ```cpp if (!mpu.begin()) { while (1) delay(10); } // Wait for stabilization delay(100); // Now read stable data sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); ``` -------------------------------- ### Configure FSYNC Sample Output Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Sets which sensor data's LSB is stored in the FSYNC pin output register for external synchronization. Use this to select temperature, gyro, or accelerometer data for FSYNC output. ```cpp mpu.setFsyncSampleOutput(MPU6050_FSYNC_OUT_TEMP); Serial.println("FSYNC output set to temperature LSB"); ``` -------------------------------- ### Format C++ and Header Files Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/README.md Use clang-format to standardize the formatting of .cpp and .h files. The -i flag modifies files in place. Running without -i prints the formatted version. ```bash clang-format -i *.cpp *.h ``` -------------------------------- ### Get Temperature Sensor Event Data Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md Reads the latest temperature data from the MPU6050's internal die sensor and populates a sensors_event_t structure. This function is essential for obtaining real-time temperature readings. ```cpp bool getEvent(sensors_event_t *event); ``` -------------------------------- ### MPU6050 Responsive Configuration Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Configures the MPU6050 for maximum responsiveness with moderate noise filtering. Uses a narrow measurement range and minimal filtering (184 Hz bandwidth) for fast response times. ```cpp void setup() { Serial.begin(115200); while (!Serial) delay(10); if (!mpu.begin()) { while (1) delay(10); } // Narrow range for high sensitivity mpu.setAccelerometerRange(MPU6050_RANGE_2_G); mpu.setGyroRange(MPU6050_RANGE_250_DEG); // Minimal filtering for fast response mpu.setFilterBandwidth(MPU6050_BAND_184_HZ); // Full sample rate mpu.setSampleRateDivisor(0); } ``` -------------------------------- ### Configure FSYNC Sample Output and Clock Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/configuration.md Set the FSYNC sample output to the Z-axis gyro LSB and use the Z-axis for timing. This allows an external system to capture data synchronized to Z-axis rotation. ```cpp mpu.setFsyncSampleOutput(MPU6050_FSYNC_OUT_GYROZ); mpu.setClock(MPU6050_PLL_GYROZ); ``` -------------------------------- ### Check Motion Interrupt Status and Get Sensor Data Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Checks if a motion interrupt has occurred and retrieves sensor events (acceleration, gyro, temperature) if it has. The interrupt status remains set until the sensor is read or reinitialized. ```cpp if (mpu.getMotionInterruptStatus()) { sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); Serial.println("Motion detected!"); Serial.print("Accel X: "); Serial.println(a.acceleration.x); } ``` -------------------------------- ### MPU6050 Initialization Retry Logic Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md The library includes automatic I2C detection retries to accommodate MPU6050 power-up stabilization. This snippet shows the internal retry mechanism. ```cpp bool mpu_found = false; for (uint8_t tries = 0; tries < 5; tries++) { mpu_found = i2c_dev->begin(); if (mpu_found) break; delay(10); } if (!mpu_found) return false; ``` -------------------------------- ### getFsyncSampleOutput() Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Queries the current FSYNC output source configuration. Returns the current mpu6050_fsync_out_t value. ```APIDOC ## getFsyncSampleOutput() ### Description Queries the current FSYNC output source. ### Method mpu6050_fsync_out_t ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Return Value** (mpu6050_fsync_out_t) - The current mpu6050_fsync_out_t FSYNC output configuration #### Response Example None ``` -------------------------------- ### Set MPU6050 I2C Address Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/configuration.md Demonstrates how to initialize the MPU6050 sensor with its default I2C address (0x68) or a custom address (0x69) if the AD0 pin is pulled high. It also shows how to specify a custom Wire interface. ```cpp Adafruit_MPU6050 mpu; // Use default address (0x68) mpu.begin(); // Or specify custom address explicitly mpu.begin(0x69); // If AD0 is pulled HIGH // With custom Wire interface mpu.begin(0x68, &Wire); ``` -------------------------------- ### Configure MPU6050 for Motion Detection Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/configuration.md Sets up the MPU6050 to detect motion by configuring the high-pass filter, motion detection threshold, and duration. Interrupts are enabled to signal detected motion. ```cpp mpu.setHighPassFilter(MPU6050_HIGHPASS_0_63_HZ); // Remove gravity mpu.setMotionDetectionThreshold(10); // ~20 mg threshold mpu.setMotionDetectionDuration(20); // 20 ms debounce mpu.setInterruptPinPolarity(true); // Active low mpu.setInterruptPinLatch(true); // Pin stays low until cleared mpu.setMotionInterrupt(true); // Enable interrupt // Now getMotionInterruptStatus() triggers on motion, INT pin goes LOW ``` -------------------------------- ### Safe MPU6050 Wrapper Class Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md This C++ class provides a safe interface for the MPU6050 sensor. It includes methods for initialization and reading sensor data, with built-in checks for initialization status, stale data, and acceleration range. ```cpp class SafeMPU6050 { Adafruit_MPU6050 mpu; bool initialized = false; uint32_t last_valid_read = 0; public: bool init() { if (!mpu.begin()) { Serial.println("MPU6050 initialization failed"); return false; } mpu.setAccelerometerRange(MPU6050_RANGE_8_G); mpu.setGyroRange(MPU6050_RANGE_500_DEG); initialized = true; delay(100); // Stabilization time return true; } bool readSafely(sensors_event_t &a, sensors_event_t &g, sensors_event_t &t) { if (!initialized) { Serial.println("ERROR: MPU not initialized"); return false; } mpu.getEvent(&a, &g, &t); // Validate timestamp advances if (a.timestamp <= last_valid_read) { Serial.println("WARNING: Stale sensor data"); return false; } // Validate acceleration is reasonable float mag = sqrt(a.acceleration.x * a.acceleration.x + a.acceleration.y * a.acceleration.y + a.acceleration.z * a.acceleration.z); if (mag < 5 || mag > 50) { Serial.println("WARNING: Acceleration out of expected range"); return false; // Could also warn without returning false } last_valid_read = a.timestamp; return true; } }; ``` -------------------------------- ### Detecting Null Temperature Sensor Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Checks if the temperature sensor is initialized by verifying the return value of getTemperatureSensor(). Call mpu.begin() before attempting to access sensors. ```cpp Adafruit_Sensor *temp = mpu.getTemperatureSensor(); if (temp == NULL) { Serial.println("Temperature sensor not initialized!"); // Call mpu.begin() first } else { sensors_event_t event; temp->getEvent(&event); } ``` -------------------------------- ### reset() Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Performs a complete reset of the MPU6050, clearing all registers to factory defaults and resetting both the digital and analog signal paths. ```APIDOC ## reset() ### Description Performs a complete reset of the MPU6050, clearing all registers to factory defaults and resetting both the digital and analog signal paths. Note: After calling `reset()`, the sensor is not immediately ready. The `begin()` method calls this function internally and includes necessary delays. ### Method ```cpp void reset(void) ``` ``` -------------------------------- ### Configure MPU6050 for Ultra-Low-Power Monitoring Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/configuration.md Configures the MPU6050 for ultra-low-power consumption by enabling cycle mode at a low rate and disabling unnecessary sensors. This is ideal for battery-powered applications. ```cpp mpu.enableSleep(false); mpu.setCycleRate(MPU6050_CYCLE_1_25_HZ); // 1.25 Hz measurement rate mpu.enableCycle(true); // Sleep between measurements mpu.setAccelerometerStandby(false, false, false); // All accel axes active mpu.setGyroStandby(true, true, true); // Gyro in standby (not needed) mpu.setTemperatureStandby(true); // Disable temperature // ~15-30 µA average current with 0.8 second measurement period ``` -------------------------------- ### I2C Scanner and MPU6050 Initialization Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md This code snippet initializes the I2C bus, scans for connected I2C devices, and attempts to initialize the MPU6050 sensor at common addresses (0x68 and 0x69). It's useful for diagnosing 'Failed to find MPU6050 chip' errors. ```cpp #include #include void setup() { Serial.begin(115200); delay(100); // Initialize I2C Wire.begin(); delay(100); Adafruit_MPU6050 mpu; // Debug: scan for I2C devices Serial.println("I2C Scanner:"); for (int addr = 0; addr < 128; addr++) { Wire.beginTransmission(addr); if (Wire.endTransmission() == 0) { Serial.print("Device found at 0x"); Serial.println(addr, HEX); } } // Try both addresses if (mpu.begin(0x68)) { Serial.println("Found at 0x68"); } else if (mpu.begin(0x69)) { Serial.println("Found at 0x69"); } else { Serial.println("MPU6050 not responding - check power and wiring"); while (1) delay(10); } } void loop() {} ``` -------------------------------- ### Configure MPU6050 for Low-Noise, Real-Time Operation Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/configuration.md Sets the MPU6050 for low-noise operation with a full 1 kHz sample rate and strong filtering. This configuration is suitable for real-time applications requiring high accuracy. ```cpp mpu.setAccelerometerRange(MPU6050_RANGE_8_G); mpu.setGyroRange(MPU6050_RANGE_1000_DEG); mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); // Strong filtering mpu.setSampleRateDivisor(0); // Full 1 kHz rate // Continuous measurement with noise filtering ``` -------------------------------- ### Data Logging with Timestamps Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Logs accelerometer, gyroscope, and temperature data with timestamps to the serial port in CSV format. Configures the sensor for data logging at a 1 kHz rate and limits logging to 60 seconds. ```cpp #include #include #include Adafruit_MPU6050 mpu; uint32_t sample_count = 0; uint32_t start_time = 0; void setup() { Serial.begin(115200); while (!Serial) delay(10); if (!mpu.begin()) { while (1) delay(10); } // Configure for data logging mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); mpu.setSampleRateDivisor(0); // Full 1 kHz rate start_time = millis(); // Print header Serial.println("time_ms,accel_x,accel_y,accel_z,gyro_x,gyro_y,gyro_z,temp"); } void loop() { sensors_event_t a, g, temp; mpu.getEvent(&a, &g, &temp); uint32_t elapsed = millis() - start_time; // CSV format for easy import to spreadsheet Serial.print(elapsed); Serial.print(","); Serial.print(a.acceleration.x, 4); Serial.print(","); Serial.print(a.acceleration.y, 4); Serial.print(","); Serial.print(a.acceleration.z, 4); Serial.print(","); Serial.print(g.gyro.x, 4); Serial.print(","); Serial.print(g.gyro.y, 4); Serial.print(","); Serial.print(g.gyro.z, 4); Serial.print(","); Serial.println(temp.temperature, 2); sample_count++; // Show statistics every second if (sample_count % 1000 == 0) { float elapsed_s = elapsed / 1000.0; float rate = sample_count / elapsed_s; Serial.print("# Sample rate: "); Serial.print(rate); Serial.println(" Hz"); } // Limit to 60 seconds of logging if (elapsed > 60000) { Serial.println("# Logging complete"); while (1) delay(10); } } ``` -------------------------------- ### Detecting Null Accelerometer Sensor Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Verifies that the accelerometer sensor is initialized by checking the return value of getAccelerometerSensor(). Ensure begin() has been called successfully. ```cpp Adafruit_Sensor *accel = mpu.getAccelerometerSensor(); if (accel == NULL) { Serial.println("Accelerometer not initialized!"); return; // Cannot use sensor } ``` -------------------------------- ### Initialize MPU6050 Sensor Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Initializes the MPU6050 sensor and I2C communication. This function must be called successfully before reading any sensor data. It checks if the chip is found and I2C communication is established. ```cpp Adafruit_MPU6050 mpu; void setup() { if (!mpu.begin()) { Serial.println("Failed to find MPU6050 chip"); while (1) delay(10); } Serial.println("MPU6050 initialized!"); } ``` -------------------------------- ### Safe Usage of getEvent() with Stale Data Check Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Demonstrates how to use getEvent() and check for fresh sensor data by comparing timestamps. Always call getEvent() with valid pointers. ```cpp sensors_event_t accel, gyro, temp; // Verify pointers if (mpu.getEvent(&accel, &gyro, &temp)) { // Always true // Validate data is not stale static uint32_t last_time = 0; if (accel.timestamp > last_time) { last_time = accel.timestamp; Serial.print("Fresh data: "); Serial.println(accel.acceleration.x); } else { Serial.println("Warning: stale sensor data"); } } ``` -------------------------------- ### Handling enableCycle() Failure Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Check the return value of enableCycle() to ensure the cycle mode setting was successfully applied. A false return indicates an I2C write failure. ```cpp if (!mpu.enableCycle(true)) { Serial.println("Failed to enable cycle mode!"); } ``` -------------------------------- ### Validate MPU6050 Readings with Retry Logic Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/errors.md Implement data validation by checking if the total acceleration is within a plausible range (e.g., at least gravity) and use a retry mechanism to handle occasional I2C communication glitches or power supply noise causing garbage readings. ```cpp // Add data validation sensors_event_t a, g, temp; for (int retry = 0; retry < 3; retry++) { mpu.getEvent(&a, &g, &temp); // Sanity check: gravity is always ~9.8 m/s² in at least one axis float total = sqrt(a.acceleration.x * a.acceleration.x + a.acceleration.y * a.acceleration.y + a.acceleration.z * a.acceleration.z); // Should be 9.8 ± 2 at minimum (at least gravity) if (total > 7 && total < 30) { // Valid reading break; } if (retry < 2) { delay(10); // Brief delay before retry } else { Serial.println("ERROR: Bad reading after retries"); } } Serial.print("Accel: "); Serial.print(a.acceleration.x); Serial.print(", "); Serial.println(a.acceleration.z); ``` -------------------------------- ### Temperature Monitoring Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/USAGE-PATTERNS.md Monitor the internal die temperature of the MPU6050. The temperature sensor is enabled by default but can be explicitly kept active. Includes logic to warn if the temperature exceeds a threshold and calculate a temperature offset. ```cpp #include #include #include Adafruit_MPU6050 mpu; void setup() { Serial.begin(115200); while (!Serial) delay(10); if (!mpu.begin()) { while (1) delay(10); } // Keep temperature sensor enabled (default) mpu.setTemperatureStandby(false); } void loop() { sensors_event_t accel, gyro, temp; mpu.getEvent(&accel, &gyro, &temp); // Monitor die temperature Serial.print("Die temperature: "); Serial.print(temp.temperature); Serial.println(" °C"); // Warn if running hot if (temp.temperature > 50) { Serial.println("WARNING: Sensor running hot!"); } // Can use temperature for calibration static float temp_ref = 25.0; float temp_offset = temp.temperature - temp_ref; Serial.print("Temperature offset: "); Serial.print(temp_offset); Serial.println(" °C"); delay(1000); } ``` -------------------------------- ### setFsyncSampleOutput() Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/Adafruit_MPU6050.md Configures which sensor data's LSB is stored in the FSYNC pin output register for external synchronization. Accepts various data sources including disabled, temperature, gyroscope axes, and accelerometer axes. ```APIDOC ## setFsyncSampleOutput() ### Description Configures which sensor data's LSB is stored in the FSYNC pin output register for external synchronization. ### Method void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **fsync_output** (mpu6050_fsync_out_t) - Required - Data source: MPU6050_FSYNC_OUT_DISABLED, MPU6050_FSYNC_OUT_TEMP, MPU6050_FSYNC_OUT_GYROX, MPU6050_FSYNC_OUT_GYROY, MPU6050_FSYNC_OUT_GYROZ, MPU6050_FSYNC_OUT_ACCELX, MPU6050_FSYNC_OUT_ACCELY, or MPU6050_FSYNC_OUT_ACCEL_Z ### Request Example ```cpp mpu.setFsyncSampleOutput(MPU6050_FSYNC_OUT_TEMP); Serial.println("FSYNC output set to temperature LSB"); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Adafruit_MPU6050_Accelerometer Source: https://github.com/adafruit/adafruit_mpu6050/blob/master/_autodocs/api-reference/unified-sensor-classes.md The accelerometer sensor component providing acceleration measurements in m/s² via the Adafruit_Sensor interface. Instances are created automatically by Adafruit_MPU6050::begin() and can be obtained via getAccelerometerSensor(). ```APIDOC ## Adafruit_MPU6050_Accelerometer ### Description Provides acceleration measurements in m/s² via the Adafruit_Sensor interface. ### Constructor ```cpp Adafruit_MPU6050_Accelerometer(Adafruit_MPU6050 *parent); ``` #### Parameters - **parent** (Adafruit_MPU6050*) - Required - Reference to the parent MPU6050 instance ### getEvent() Reads the latest accelerometer data and populates the sensor event structure. #### Parameters - **event** (sensors_event_t*) - Required - Pointer to sensor event structure to fill #### Returns - `true` on successful read #### Populated fields - `event->acceleration.x` — X-axis acceleration (m/s²) - `event->acceleration.y` — Y-axis acceleration (m/s²) - `event->acceleration.z` — Z-axis acceleration (m/s²) - `event->timestamp` — Milliseconds since Arduino startup - `event->sensor_id` — Sensor ID from initialization - `event->type` — SENSOR_TYPE_ACCELEROMETER ### getSensor() Retrieves static metadata about the accelerometer sensor. #### Parameters - **sensor** (sensor_t*) - Required - Pointer to sensor metadata structure to fill #### Populated fields - `sensor->name` — "MPU6050_A" - `sensor->version` — 1 - `sensor->sensor_id` — Unique sensor ID - `sensor->type` — SENSOR_TYPE_ACCELEROMETER - `sensor->min_delay` — 0 (no minimum delay constraint) - `sensor->min_value` — -156.9064 m/s² (±16g) - `sensor->max_value` — 156.9064 m/s² (±16g) - `sensor->resolution` — 0.061 mg/LSB (at ±2g range) ```