GithubHelp home page GithubHelp logo

mpu6050's Introduction

MPU6050 by Electronic Cats - Library for Arduino

LibraryBuild

Arduino library for controlling MPU6050 module.

MPU6050 Combines a 3-axis gyroscope and a 3-axis accelerometer on the same silicon die together with an onboard DMP (Digital Motion Processor) which processes complex 6-axis MotionFusion algorithms.

Based on jrowberg/i2cdevlib

Features of this version

  • Supported Chipsets

    • AVR
    • SAM
    • SAMD21
    • ARM
    • ESP32
    • ESP8266
    • RENESAS

Quick Installing

To install, use the Arduino Library Manager and search for "MPU6050" and install the MPU6050 by Electronic Cats library.

How to contribute

Contributions are welcome!

Please read the document Contribution Manual which will show you how to contribute your changes to the project.

✨ Thanks to all our contributors! ✨

See Electronic Cats CLA for more information.

See the community code of conduct for a vision of the community we want to build and what we expect from it.

Maintainer

Electronic Cats invests time and resources providing this open source design, please support Electronic Cats and open-source hardware by purchasing products from Electronic Cats!

mpu6050's People

Contributors

arthulisher avatar benpeart avatar bheesma-10 avatar deimoshall avatar eric286 avatar holzachr avatar jazhe avatar kalana-ratnayake avatar marcelol52 avatar net234 avatar oscar-raygoza avatar quesswho avatar robtasm avatar sabas1080 avatar wero1414 avatar xpeqex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mpu6050's Issues

LinearAcceleration does not compensate for Gravity using DMP 6.12

Code snippet (identical for comparing 6.12 and old version):

xyzInt16_t mpuGyro::getAccelReal()
{
mpu6050.dmpGetQuaternion(&q, fifoBuffer); // A
mpu6050.dmpGetAccel(&aa, fifoBuffer); // B
mpu6050.dmpGetGravity(&gravity, &q); // C
mpu6050.dmpGetLinearAccel(&aaReal, &aa, &gravity); // D

xyzInt16_t ar;
ar.x = aaReal.x;
ar.y = aaReal.y;
ar.z = aaReal.z;
return ar;
}

I have found this compatible with the provided examples for both .h-versions.

Sample printout using DMP 6.12:
grX | grY | grZ | arealX | arealY | arealZ | arealScaledX | arealScaledY | arealScaledZ
-0.0011 | 0.010009 | 0.999853 | 30 | -11 | 8303 | 0.035925 | -0.013173 | 9.942924
-0.00098 | 0.008056 | 0.999861 | 3 | -107 | 8101 | 0.003593 | -0.128134 | 9.701027
-0.00085 | 0.006591 | 0.999867 | -7 | -113 | 8181 | -0.008383 | -0.135319 | 9.796828
-0.00073 | 0.005371 | 0.999871 | 0 | -107 | 8191 | 0 | -0.128134 | 9.808803

Sample printout using DMP20:
grX | grY | grZ | arealX | arealY | arealZ | arealScaledX | arealScaledY | arealScaledZ
-0.00024 | -0.00281 | 0.999877 | -4 | -4 | 0 | -0.00479 | -0.00479 | 0
-0.00024 | -0.00281 | 0.999877 | 4 | -4 | 4 | 0.00479 | -0.00479 | 0.00479
-0.00024 | -0.00281 | 0.999877 | -3 | 2 | -5 | -0.003593 | 0.002395 | -0.005988
-0.00024 | -0.00281 | 0.999877 | -6 | -5 | -6 | -0.007185 | -0.005988 | -0.007185

Additional question:
I happened to find a statement in 6.12 telling that the MPU6050_DMP_FIFO_RATE_DIVISOR (default 0x1) can no longer be set by the user. Is there a plan to fix this, or can you suggest a workaround such as a patch for the DMP image?

Regards,
BjornGu

ElectronicCats

I haven't able to find the proper documentation for this library. All of them were either examples or online tutorials, which explains the same code again and again. Could you please provide us with a documentation?

Can i change the interrupt pin?

Hi,
I've recently purchased a MPU6050 and i started to look for tutorials on how to use. Turns out that there's a lot more involved in this tniy sensor than I originally would have thought. After watching some tutorials, I've landed on this library, wich seems to be one of the best, since it uses DMP. From what i learned, Pin 2 is connected to the Interrupt pin on the sensor, while SDA and SCL are used for I2C. I've tested it on an Arduino Mega, and it worked really well.

My problem:

now I want to use an arduino pro micro, where the SDA pin is Pin 2!
Here's a pic of the pinout:
(https://europe1.discourse-cdn.com/arduino/original/3X/a/1/a189ab6e38490f5a7e4b03312c75241e60bc0857.png)
It's evident that i cannot use it for both I2C and Int, but i cannot find where pin 2 is declared for the interrupt function.
Am I missing something really obvious? Keep in mind that I still consider myself a almost-total beginner, and I do not have the experience nor the knowledge to deal with this issue.

What I'd like to know:

is it possible to change something somehere to get everything to work?

Thanks a lot for your help, I'm looking forward to your response

Changing sensors in code on lsm303dlh and l3gd20

Hello @sabas1080
I want to use gyroscope and accelerometer sensors like lsm303dlh and l3gd20.
How to find the “entry point” to insert your own acceleration and angular velocity values into the code?
I get the raw data something like this:

#include <Wire.h>
#include <L3G.h>
#include <LSM303.h>

LSM303 mag_accel;
L3G gyro;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  if (!gyro.init())
  {
    Serial.println("Failed to autodetect gyro type!");
    while (1);
  }
  if (!mag_accel.init())
  {
    Serial.println("Failed to initialize mag_accel!");
    while (1);
  }
  gyro.enableDefault();
  mag_accel.enableDefault(); 
}

void loop() {

  gyro.read();
  mag_accel.read();

Serial.print(gyro.g.x);
Serial.print(",");
Serial.print(gyro.g.y);
Serial.print(",");
Serial.print(gyro.g.z);
Serial.print(",");
Serial.print(mag_accel.a.x);
Serial.print(",");
Serial.print(mag_accel.a.y);
Serial.print(",");
Serial.println(mag_accel.a.z);

}

As far as I understand, your code examples contain source code for working with DMP and more?

When I saw a dump of some code in the code, it seemed to me that your code was not applied to other sensors other than MPU9250.
I would be grateful for any hint.

ElectronicCats usage of teapot demo rotation system

Hello,
I am making hand controller for VR using your library.I am using unity and I don't know how to use same system of rotating as on teapot demo.

// toxiclibs direct angle/axis rotation from quaternion (NO gimbal lock!)

// (axis order [1, 3, 2] and inversion [-1, +1, +1] is a consequence of

// different coordinate system orientation assumptions between Processing

// and InvenSense DMP)

float[] axis = quat.toAxisAngle();

Currently i'm just sending yaw pitch roll data over bluetooth but it acts weird. how can I use same system as in teapot demo?

If further information is needed I can send them

thanks

When I move my mpu6050, sometimes the data will stay unchanged.

When I move my mpu6050, sometimes the data will stay unchanged.

Is it because I moved somewhere? Or how? For example, when I swing 6050, its X, y, Z will not change sometimes, but it will be normal after restart. It shouldn't be that my DuPont line isn't plugged in, right?

Using DMP6 example code without Interrupt Pin

I am looking to use your awesome lib in a data logger project to write GPS data and Acceleration data to an SD card.
The microprocessor is an ESP32 Heltec development board.

Your example MPU6050_DMP6 works great!
However the interrupt causes issues using GPS data.

Is it possible to use the DMP6 code and eliminate the interrupt component?
This way I will read and store acceleration values in the main program loop and write the data to SD along with the GPS data

Thanks for your help

Want to use this library in code for our nano-satellite to detemine it's angular velocities on all 3-axis.

As the satellite needs to be dead-launched, that is it cant be turned on during the launch. It gets turned on only when deployed from the spacecraft when it is already in random motion. Now auto-calibrating in this condition would result in the random motion being referenced as steady-state and thus will result in errors in values further when the satellite slows down due to onboard passive magnets. Do you have any way out of this?

I think this is not an issue, but it can work in stm32f103ret6

Hello !
I am very excited because this library can be used by the stm32f103ret6 platform. The platformio I used was compiled successfully and ran successfully. Thanks for your contributions.

WX20210727-111417@2x

My English is not good, this is translated by Google。😀

ElectronicCats

getTemperature returns a 16-bit 2's compliment

so at 73 deg F, the lib returns -2858 or so.

Can you please add code in the lib to return the actual temp?

Thanks in advance.

Supporting devices with WHOAMI 0x98

There seem to be devices out there, that respond with "0x98" when asked for the WHOAMI register 0x75.
According to the datasheet, the correct answer would be "0x68". However, these "other" devices are out there, and tend to confuse the users of this library and including projects, when their material is not working.
I cannot verify if these devices work fine for the rest of the spec, but maybe someone out there can, and could extend MPU6050::testConnection() to validate the getDeviceID to be either 0x34 or 0x4C?
Does anyone have experience with such devices?

Support for GIGA R1 WiFi with 3 x I2C

Hi, been using your library successfully on a Mega (thankyou) but I'm now migrating to a GIGA and would like to use Wire1 rather than Wire. I notice other mpu6050 libs have the interface as an argument. Is that possible currently (maybe with a local hack) with your lib? If not, any plans to do this as I'd like to stick with this lib.

Thanks, Steve

Wrong reading when the MPU6050 is placed vertically

I tried to initialize the mpu6050 when it was placed vertically, but the mpu6050 got wrong data. The error is that when I rotate the mpu6050, the angle change cannot correspond to my deflection. Is there a way to set the initialization to use the mpu6050 vertically?

I have been stuck with this problem for a long time. Thanks for anybody who can give me some advise.

Library claims ARM support but uses dtostrf

The library claims ARM support but uses dtostrf, making it incompatible with Arduino Due.
Removing the call to dtostrf, the code compiles, but accelgyro.testConnection() in he raw example fails to connect.

esp32 2.0.4 Unlimited waiting for bugs

esp32 2.0.4 Unlimited waiting for bugs

    mpu.initialize();

When the program runs here, it will not run the following code. Arduino for esp32 1.0.6 is normal.

i get stuck in Success! DMP code written and verified

02:33:36.853 -> *wm:connectTimeout not set, ESP waitForConnectResult...
02:33:37.253 -> *wm:AutoConnect: SUCCESS
02:33:37.253 -> *wm:STA IP Address: 192.168.0.11
02:33:37.253 -> WiFi connected! IP address: 192.168.0.11
02:33:37.253 -> Initializing I2C devices...
02:33:37.253 -> Testing device connections...
02:33:37.253 -> MPU6050 connection successful
02:33:37.253 -> Initializing DMP...
02:33:37.253 ->
02:33:37.253 ->
02:33:37.253 -> Resetting MPU6050...
02:33:37.287 -> Checking hardware revision...
02:33:37.287 -> Revision @ user[16][6] = 165
02:33:37.287 -> Resetting memory bank selection to 0...
02:33:37.287 -> Reading OTP bank valid flag...
02:33:37.287 -> OTP bank is valid!
02:33:37.287 -> Setting slave 0 address to 0x7F...
02:33:37.287 -> Disabling I2C Master mode...
02:33:37.287 -> Setting slave 0 address to 0x68 (self)...
02:33:37.287 -> Resetting I2C Master control...
02:33:37.334 -> Setting clock source to Z Gyro...
02:33:37.334 -> Setting DMP and FIFO_OFLOW interrupts enabled...
02:33:37.334 -> Setting sample rate to 200Hz...
02:33:37.334 -> Setting external frame sync to TEMP_OUT_L[0]...
02:33:37.334 -> Setting DLPF bandwidth to 42Hz...
02:33:37.334 -> Setting gyro sensitivity to +/- 2000 deg/sec...
02:33:37.334 -> Writing DMP code to MPU memory banks (1929 bytes)
02:33:37.506 -> Success! DMP code written and verified.

How to solve it?
im using wemos d1 mini

Accelerometer Word scale factor

Hello,

I don't know if this is a mistake or not, but I thought I should bring it up and ask.

In the datasheet for the MPU6050, it specifies the following:

ACCELEROMETER SENSITIVITY
Full-Scale Range
AFS_SEL=0 -> ±2 g
AFS_SEL=1 -> ±4 g
AFS_SEL=2 -> ±8 g
AFS_SEL=3 -> ±16 g

ADC Word Length
AFS_SEL=0 ->16,384 LSB/g
AFS_SEL=1 -> 8,192 LSB/g
AFS_SEL=2 -> 4,096 LSB/g
AFS_SEL=3 -> 2,048 LSB/g

However, in the MPU6050.cpp file lines 1817 to 1823 it can be seen that the values for the LSB sensitivity are basically halved and the units are different (LSB/mg):

 * <pre>
 * AFS_SEL | Full Scale Range | LSB Sensitivity
 * --------+------------------+----------------
 * 0       | +/- 2g           | 8192 LSB/mg
 * 1       | +/- 4g           | 4096 LSB/mg
 * 2       | +/- 8g           | 2048 LSB/mg
 * 3       | +/- 16g          | 1024 LSB/mg
 * </pre>

One final detail, these values were marked as LSB/mg prior to revision 2.2 on the datasheet. This is what leads me to believe this description might be incorrect.

Thanks.

is OUTPUT_READABLE_YAWPITCHROLL display Euler angles in degrees conversion correct?

Serial.print(ypr[1] * 180/M_PI);

Is this conversion correct?

Why when I put my chip vertical (90 degree), the print output is: 28.xx, i.e. (~= 90 / 3.14 = 28.66)? BTW, I got ~+/- 0.xx at zero degrees.

For example for pitch: the chip in flat position (~0 degree):

ypr	8.53	-0.10	0.08
ypr	8.53	-0.11	0.10
ypr	8.53	-0.12	0.10
ypr	8.53	-0.13	0.10
ypr	8.53	-0.13	0.10
ypr	8.53	-0.13	0.09
ypr	8.53	-0.13	0.09
ypr	8.53	-0.14	0.09
ypr	8.53	-0.14	0.09
ypr	8.53	-0.14	0.09
ypr	8.53	-0.14	0.10
ypr	8.53	-0.14	0.10
ypr	8.53	-0.14	0.10

the chip in vertical position (~90 degree):

ypr	12.09	28.00	14.33
ypr	12.09	28.05	14.36
ypr	12.08	28.10	14.39
ypr	12.08	28.14	14.42
ypr	12.06	28.20	14.45
ypr	12.06	28.24	14.48
ypr	12.05	28.31	14.51
ypr	12.04	28.36	14.53
ypr	12.03	28.42	14.56
ypr	12.02	28.48	14.59
ypr	12.02	28.54	14.63
ypr	12.01	28.59	14.67
ypr	12.00	28.64	14.71
ypr	12.00	28.69	14.75
ypr	12.00	28.75	14.79
ypr	11.99	28.81	14.84
ypr	11.98	28.86	14.88
ypr	11.97	28.92	14.92

what I'm missing?

Thanks.

Please provide documentation.

The name of the functions, argument types, constants and it's value, a brief explanation of it's working - if included as a document would be nice so that the one seeing the documentation can just start away without any further search. Please provide small and easy to digest examples, so that this would stand out from other libraries.

Gyroscope

Hi ,
Gyroscope calibration routines doesn't work properly , when it it subjected to constant angular velocity the module is not able to recognize the same angular velocity when mounted in different orientations .
Can you please verify this at different range of gyroscope as well ??

Note: We restarted each time when it is mounted at different orientations, and we waited for it calibration ( though the accelerometer is getting calibrated properly , gyroscope didn't calibrate for the new orientation )

Thanks.

Compilation of demo MPU6050_DM6 for Arduino Nano 33 BLE fails [workaround included]

Compilation of the example script MPU6050_DM6, freshly installed version 0.2.1, targeting the Nano 33 BLE, fails with the error:

/Users/rob/Documents/Arduino/libraries/MPU6050/src/MPU6050.cpp: In member function 'void MPU6050::PrintActiveOffsets()':
/Users/rob/Documents/Arduino/libraries/MPU6050/src/MPU6050.cpp:3309:154: error: 'dtostrf' was not declared in this scope

In packages/arduino/hardware/mbed_nano/2.0.0/cores/arduino there is api/deprecated-avr-comp/avr/dtostrf.c.impl which suggests adding the line

#include "api/deprecated-avr-comp/avr/dtostrf.c.impl"

to the top of MPU6050.cpp would provide this definition. That makes compilation work for me; for a release you might have to wrap that #include in some #ifdef protection.

What is the unit of acceleration?

    mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
 
  mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

aaReal and aaWorld
What are these two units? What's the difference? I don't quite understand. I didn't understand the specific difference in the notes. I don't know what the two units are.

What is the unit of acceleration and how is the angular velocity obtained?

ElectronicCats

Hi, there.

I was trying to understand how to set the frequency for the accelerometer and gyroscope for MPU6050 using your libraries, but the attempt was unsuccessful.
Could you help me guys?

Bojarin,
Thanks in advance.

using MPU6050 no-interrupt gives erratic accel readings

I am using your awesome lib to interface with an MPU6050 on an ESP32 without interrupt pin.
The basic code reads data from the MPU6050 and then displays it on the OLED

However the readings are very erratic. Even wth the MPU taped to a table to give stability, the readings are very erratic and occasionally read close to 2g without any movement at all

// ACCEL_to_OLED
//
#include "heltec.h"
#include "SSD1306Ascii.h"
#include "SSD1306AsciiWire.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"

SSD1306AsciiWire oled;

MPU6050 mpu;

bool dmpReady = false; 
uint8_t devStatus; 
uint16_t packetSize; 
uint16_t fifoCount; 
uint8_t fifoBuffer[64];
float MaxGx = 0, MaxGy = 0, MaxGz = 0;

Quaternion q;           // [w, x, y, z]         quaternion container

void setup() {
      Heltec.begin(true /*DisplayEnable Enable*/, false /*LoRa Enable*/, true /*Serial Enable*/);

      oled.begin(&Adafruit128x64, 0x3C, 16);
      oled.setFont(System5x7);
      oled.clear();
    
      Wire.begin();  //pin 21 and 22 for ESP32
      Wire.setClock(400000); 

      Serial.begin(115200);
 
      Serial.println(F("Initializing I2C devices..."));
      mpu.initialize();

      Serial.println(F("Testing device connections..."));
      Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

      Serial.println(F("Initializing DMP..."));
      oled.setCursor(0,0);
      oled.println("Calibrate Acc/Gyro");
      devStatus = mpu.dmpInitialize();

      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    if (devStatus == 0) {
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        Serial.println(F("Enabling DMP..."));
        oled.print("Accel/Gyro Ready");
        delay(1000);
        oled.clear();
        mpu.setDMPEnabled(true);

        Serial.println(F("DMP ready!"));
        dmpReady = true;

        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }
}


void loop() {
    // if MPU6050nprogramming failed, don't do anything
    if (!dmpReady) return;

    while (fifoCount < packetSize) {
        if (fifoCount < packetSize) {
          // try to get out of the infinite loop 
          fifoCount = mpu.getFIFOCount();
        }  
    }

    fifoCount = mpu.getFIFOCount();
    if(fifoCount < packetSize){
          }
    else if (fifoCount >= 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
      //  fifoCount = mpu.getFIFOCount();  // will be zero after reset
        Serial.println(F("FIFO overflow!"));
   } 

  while(fifoCount >= packetSize){
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    fifoCount -= packetSize;
  }

            mpu.dmpGetQuaternion(&q, fifoBuffer);

             if (abs(q.x) > abs(MaxGx))
              {
                MaxGx = q.x;
              } else{
                MaxGx = MaxGx;
              }

            if (abs(q.y) > abs(MaxGy))
              {
                MaxGy = q.y;
              } else{
                MaxGy = MaxGy;
              }

            if (abs(q.z) > abs(MaxGz))
              {
                MaxGz = q.z;
               } else{
                MaxGz = MaxGz;
               }

              oled.setCursor(0,0);
              oled.clearToEOL();
              oled.println("ACCEL  X     Y     Z");
              oled.setCursor(0,1);
              oled.clearToEOL();
              oled.setCursor(20,1);
              oled.print(q.x,2);
              oled.setCursor(60,1);
              oled.print(q.y,2);
              oled.setCursor(95,1);
              oled.println(q.z,2);

              oled.setCursor(0,4);
              oled.println("MaxG   X     Y     Z");
              oled.setCursor(0,5);
              oled.clearToEOL();
              oled.setCursor(20,5);
              oled.print(MaxGx);
              oled.setCursor(60,5);
              oled.print(MaxGy);
              oled.setCursor(95,5);
              oled.println(MaxGz);
}

question for the version

Could you let me know, what's the difference between dmp6 with dmp v6.12???

actually in the sketch, WORLD_ACCEL values are different..

On dmp6(sketch) world_accel, values are 0,0,0(x,y,z), otherwise on dmp6.12 it shows 0,0,8192(x,y,z) ..

since I'm newbie.. i really need your help!

Thanks for your good library again!

Orientation

I have investigated MPU6050 library and teapot demo example in MPU6050/examples/MPU6050_DMP6.
I found dmpGetYawPitchRoll use orientation -180degree rotated from the MPU6050 hardware orientation.
Teapot demo uses toxiclibs, also roll pitch direction is diff from MPU6050 hardware orientation.

mpu6050_orientation
(1) MPU6050 hardware orientation by the datasheet
(2) Orientation of dmpGetYawPitchRoll by the lib
(3) Orientation in toxiclibs.

Please share any opinion.
Thank you

Bits operation mistake

First, thank you for maintaining this library!

So, I'm adapting this library to work in the raspberry pi zero. I'm reading the whole code to understand better how it works and I stopped in the methods that read specific bits of a byte or word read from I2C device, as below:

mpu6050/src/I2Cdev.cpp

Lines 139 to 153 in 4e0f3a2

int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
// 01101001 read byte
// 76543210 bit numbers
// xxx args: bitStart=4, length=3
// 010 masked
// -> 010 shifted
uint8_t count, b;
if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) {
uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
b &= mask;
b >>= (bitStart - length + 1);
*data = b;
}
return count;
}

I was in doubt if these methods work as expected and I made some tests. The code that I used is very simple as can be seen below

#include <iostream>
#include <cstdint>
#include <bitset>

#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c\n"
#define BYTE_TO_BINARY(byte)  \
  (byte & 0x80 ? '1' : '0'), \
  (byte & 0x40 ? '1' : '0'), \
  (byte & 0x20 ? '1' : '0'), \
  (byte & 0x10 ? '1' : '0'), \
  (byte & 0x08 ? '1' : '0'), \
  (byte & 0x04 ? '1' : '0'), \
  (byte & 0x02 ? '1' : '0'), \
  (byte & 0x01 ? '1' : '0')

int main() {
  uint8_t byte_read = 0b01101001;
  uint8_t bit_start = 4;
  uint8_t length = 3;

  printf("Raw val  = " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte_read));

  uint8_t mask = ((1 << length) - 1) << (bit_start - length + 1);
  printf("Raw mask = " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(mask));

  byte_read &= mask;
  printf("byte_read & mask = " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte_read));

  byte_read >>= (bit_start - length + 1);
  printf("byte_read shifted right by %d = " BYTE_TO_BINARY_PATTERN, bit_start - length + 1, BYTE_TO_BINARY(byte_read));
}

Using the same example that is in the body of the method, the result was this:

Raw val  = 01101001
Raw mask = 00011100
byte_read & mask = 00001000
byte_read shifted right by 2 = 00000010

That is different of the correct result: 011 (bits, 4, 5, and 6 of 01101001)

Besides that, a strange behavior happens when e.g., bit_start = 1 and length = 5 because the result of this operation (bit_start - length + 1) will be negative that doesn't exist in shift operations. The output of this scenario is this:

Raw val  = 01101001
Raw mask = 00000000
byte_read & mask = 00000000
byte_read shifted right by -3 = 00000000

I'm trying to make a better approach and if you want I can share with you.

And finally, do you think that this operation does not affect the MPU6050 class?

Deadlock upon calibration if no Serial available

There are some cases when you write into serial without checkups. Like, here

Serial.write('>');

If Serial is not available, Arduino will fall into deadlock waiting for serial port infinitely. Or so i think, as your code works purrfectly from PC usb, but fails to init if powered from +5V pin.

You should either if (Serial) them or move Serial output to debug functions.

MPu6050 register map revision dont have all registers

Your library is based on register map rev 2.0 documentation but i cant find this version of the documentation.

example : Register 0x1F ( 31 ) is not mentioned in the register map documents i found. ( setting motion detect threshold )

I know production is stopped but still a lot of GY521 (clones ?) are sold these days.

Edit : This is not an issue with the library but a kind request to receive the doc 2.0 the library is based on.

Below is the document i found that misses a lot of information:

MPU6050 register map rev 4.2

Also the DMP specification was officially released in 2014 , but i cant find the document either.

Library does not interface with MPU6050 on Heltec Wifi V2 ESP32 Board

I am trying to use this library to interface with an MPU-6050 accel/gyro on a Heltec ESP32 WiFi V2 Development board

The board pinout shows SDA as Pin 21 and SCL as Pin 22

Upon compile I get this message
WARNING: library MPU6050 claims to run on avr, samd architecture(s) and may be incompatible with your current board which runs on esp32 architecture(s).

Reading problem when placing the mpu6050 vertically

Transplant example MPU6050_ DMP6 encountered a problem. The angle measurement is incorrect after vertical initialization

When I try automatic calibration of acceleration and attitude angle, initial three-axis attitude angle after calibration is about 0.When I place the mpu6050 horizontally (the z+direction is downward), the three-axis angle changes correctly.
But when I place the mpu6050 vertically (the x+direction is downward), the measured values of the three-axis angle will change correspondingly, but the measured results tend to decay. For example, if I rotate the pitch from 0 ° to 60 °, the measured results will increase from 0 ° to 60 °, but cannot reach 60 °, it will decay all the time。

Is there some suggestions for improvement in this situation?

Thanks a lot

'class MPU6050' has no member named 'begin'

When I try and compile the code to my Arduino UNO I get the error 'class MPU6050' has no member named 'begin'

Here is my code:

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;
 
void setup()
{
  Serial.begin(115200);
 
  Serial.println("Inicjalizacja MPU6050");
 
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Nie mozna znalezc MPU6050 - sprawdz polaczenie!");
    delay(500);
  }
}
 
void loop()
{
  Vector rawAccel = mpu.readRawAccel();
  Vector normAccel = mpu.readNormalizeAccel();
 
  Serial.print(" Xraw = ");
  Serial.print(rawAccel.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawAccel.YAxis);
  Serial.print(" Zraw = ");
 
  Serial.println(rawAccel.ZAxis);
  Serial.print(" Xnorm = ");
  Serial.print(normAccel.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normAccel.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normAccel.ZAxis);
 
  delay(10);
}

Thanks in advance

library issues

hello
got some issue with code\library -
im getting 'class MPU6050' has no member named 'begin' in this sketch:

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

void setup()
{
Serial.begin(9600);

Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Error");
delay(1000);
}
pinMode(13, OUTPUT);

mpu.setThreshold(2);
}

void loop()
{
Vector rawGyro = mpu.readRawGyro();
Vector normGyro = mpu.readNormalizeGyro();
float normal_x = normGyro.XAxis;
float normal_y = normGyro.YAxis;
float normal_z = normGyro.ZAxis;
Serial.print(" Xnorm = ");
Serial.print(normal_x);
Serial.print(" Ynorm = ");
Serial.print(normal_y);
Serial.print(" Znorm = ");
Serial.println(normal_z);

if(abs(normal_x) + abs(normal_y) + abs(normal_z) > 0.2){
digitalWrite(13, HIGH);
}else{
digitalWrite(13, LOW);
}

delay(10);
}

if you have any hints - will be happy. thanks

MPU-6050 Locks Up during Initialization

I'm having trouble using this library with the ESP32 devkit v1. The device locks up during initialization. However, if I use an I2C scanner, the device is identified, as follows

18:47:16.447 ->  Scanning I2C Addresses
18:47:16.447 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.447 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.447 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.447 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.487 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.487 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.487 -> .. .. .. .. .. .. .. .. 68 .. .. .. .. .. .. .. 
18:47:16.487 -> .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. 
18:47:16.487 -> Scan Completed, 1 I2C Devices found.
18:47:16.487 -> 
18:47:16.487 -> Discovering eeprom sizes 0x50..0x57
18:47:16.609 -> 0x50: Not Present.
18:47:16.689 -> 0x51: Not Present.
18:47:16.809 -> 0x52: Not Present.
18:47:16.889 -> 0x53: Not Present.
18:47:17.009 -> 0x54: Not Present.
18:47:17.099 -> 0x55: Not Present.
18:47:17.179 -> 0x56: Not Present.
18:47:17.299 -> 0x57: Not Present.

If I try examples from other sources that do direct I2C register reads and writes, everything works fine. Exemple output:

19:01:44.601 -> AcX = 1.00 | AcY = -0.03 | AcZ = 0.00 | Tmp = 27.87 | GyX = -0.22 | GyY = 0.10 | GyZ = -0.32
19:01:44.901 -> AcX = 1.00 | AcY = -0.03 | AcZ = 0.01 | Tmp = 27.92 | GyX = -0.17 | GyY = 0.13 | GyZ = -0.09
19:01:45.182 -> AcX = 1.00 | AcY = -0.02 | AcZ = 0.01 | Tmp = 27.97 | GyX = -0.18 | GyY = 0.00 | GyZ = -0.26

My code is as follows. Please note that I'm not using the default I2C pins, but as I stated before, everything works fine with direct registers reads and writes.

#include "MPU6050.h"
#include "Wire.h"

MPU6050 acelerometro(0x68);

// Valores brutos
int16_t ax, ay, az;     // Aceleração
int16_t gx, gy, gz;     // Rotação

void setup()
{
  Serial.begin(115200);
  Serial.println("Teste do Acelerômetro MPU-6050");     // "MPU-6050 accelerometer test"

  Serial.println("Inicializando");  

  // Wire
  Wire.begin(32, 33);
  delay(1000);

  // MPU-6050
  acelerometro.initialize();    // <-- LOCKS EXECUTING THIS!

  // Teste da conexão (segundo exemplo)
  Serial.println("Testando conexão ao acelerômetro...");    // "Testing accelerometer connection..."
  bool resultado = acelerometro.testConnection();

  Serial.print("Resultado: ");                              // "Result"
  Serial.println(resultado?"Sucesso":"Falha");              // "Success/Failure"
}

void loop()
{
  acelerometro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  
  Serial.print("aceleração/rotação:\t");                    // "Acceleration/Rotation"
  Serial.print(ax); Serial.print("\t");
  Serial.print(ay); Serial.print("\t");
  Serial.print(az); Serial.print("\t");
  Serial.print(gx); Serial.print("\t");
  Serial.print(gy); Serial.print("\t");
  Serial.println(gz);
}

Example output:

19:10:59.957 -> ets Jun  8 2016 00:22:57
19:10:59.957 -> 
19:10:59.957 -> rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
19:10:59.957 -> configsip: 0, SPIWP:0xee
19:10:59.957 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
19:10:59.957 -> mode:DIO, clock div:1
19:10:59.957 -> load:0x3fff0030,len:1324
19:10:59.957 -> ho 0 tail 12 room 4
19:10:59.957 -> load:0x40078000,len:13508
19:10:59.957 -> load:0x40080400,len:3604
19:10:59.957 -> entry 0x400805f0
19:11:00.077 -> Teste do Acelerômetro MPU-6050
19:11:00.077 -> Inicializando

Power supply is 3.3V, AD0 is grounded, using 3.3k ohms pull-ups on SCL and SDA and (being repetitive) it works fine when using direct I2C register reads and writes.

Any clues?

'class MPU6050' has no member named 'begin'

When I try and compile the code to my Arduino UNO I get the error 'class MPU6050' has no member named 'begin'

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

void setup()
{
Serial.begin(115200);

// Initialize MPU6050
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}

// If you want, you can set gyroscope offsets
// mpu.setGyroOffsetX(155);
// mpu.setGyroOffsetY(15);
// mpu.setGyroOffsetZ(15);

// Calibrate gyroscope. The calibration must be at rest.
// If you don't want calibrate, comment this line.
mpu.calibrateGyro();

// Set threshold sensivty. Default 3.
// If you don't want use threshold, comment this line or set 0.
mpu.setThreshold(3);

// Check settings
checkSettings();
}

void checkSettings()
{
Serial.println();

Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

Serial.print(" * Clock Source: ");
switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator"); break;
}

Serial.print(" * Gyroscope: ");
switch(mpu.getScale())
{
case MPU6050_SCALE_2000DPS: Serial.println("2000 dps"); break;
case MPU6050_SCALE_1000DPS: Serial.println("1000 dps"); break;
case MPU6050_SCALE_500DPS: Serial.println("500 dps"); break;
case MPU6050_SCALE_250DPS: Serial.println("250 dps"); break;
}

Serial.print(" * Gyroscope offsets: ");
Serial.print(mpu.getGyroOffsetX());
Serial.print(" / ");
Serial.print(mpu.getGyroOffsetY());
Serial.print(" / ");
Serial.println(mpu.getGyroOffsetZ());

Serial.println();
}

void loop()
{
Vector rawGyro = mpu.readRawGyro();
Vector normGyro = mpu.readNormalizeGyro();

Serial.print(" Xraw = ");
Serial.print(rawGyro.XAxis);
Serial.print(" Yraw = ");
Serial.print(rawGyro.YAxis);
Serial.print(" Zraw = ");
Serial.println(rawGyro.ZAxis);

Serial.print(" Xnorm = ");
Serial.print(normGyro.XAxis);
Serial.print(" Ynorm = ");
Serial.print(normGyro.YAxis);
Serial.print(" Znorm = ");
Serial.println(normGyro.ZAxis);

delay(10);
}

Initialization in z-axis reversal leads to P reversal in PID for pitch and roll

I'd like to share my solution to an issue similar to this one #55 and point out a bug I seem it be.

Describe the bug
The problem is this: my pitch and roll will overshoot in the reverse direction (e.g. when I turn an axis from 11 to -22, the value may go to 55 and then slowly change back to -22 (the closer it gets to -22 the slower it changes)) I tried different CalibrateAccel() and CalibrateGyro() parameters and it doesn't fix.

To Reproduce
Yesterday I tried the example/MPU6050_DMP6 in v1.3.0 and still had this problem.

I found out today that when I initialize the mpu6050 module with the Z-axis pointing to the sky there is no problem. ✅

And my previous initialization of the module with the z-axis pointing downwards triggered the bug every time.❗

so I guess maybe when I initialized with the z-axis pointing downwards the P in the PID for pitch and roll didn't go negative resulting in the response changing to positive feedback at first.

To help us to understand your situation, we would like to ask you for the following additional information::

  • esp8266 nodemcu
  • Windows 11
  • platformIO installed a few days ago
  • The problem triggers steadily when the z-axis is initialized downwards, I'm buying other mpu6050 modules to exclude hardware issues, but just initialize the z-axis facing upwards and there's no problem!

MPU6050 getting stuck in FIFO Loop

This is based on previously closed issue #13

I have been testing the use of the MPU6050 without interrupt in my GPS-Accelerometer Data logger.
I had to add a line to reset the FIFO before reading the FIFO since it was giving corrupted data.

For some reason it gets stuck in this loop on occasion, I have not determined why. The code was from the DMP6 example

// wait for MPU extra packet(s) available
while (fifoCount < packetSize) {
if (fifoCount < packetSize) {
// try to get out of the infinite loop
Serial.println("In FIFO Loop"); //for troubleshooting
fifoCount = mpu.getFIFOCount();
}
}

The DEBUG build no longer compiles

If you attempt to compile with the DEBUG macro defined, the library does not compile with the error:

.pio\libdeps\debug\MPU6050\src\MPU6050_9Axis_MotionApps41.cpp: In member function 'uint8_t MPU6050_9Axis_MotionApps41::dmpInitialize()':
.pio\libdeps\debug\MPU6050\src\MPU6050_9Axis_MotionApps41.cpp:366:17: error: 'productID' was not declared in this scope
     DEBUG_PRINT(productID);

I have submitted a pull request that contains a two-part fix. The first part is to fix the compile error by commenting out the offending DEBUG_PRINT line. The second/better fix is to update the DEBUG_PRINT macros so that the structure of the macros ensures that the code is always validated at compile time but is not called when DEBUG is undefined. This will prevent stale debug code from accumulating when the debug version is not regularly compiled.

Library version should be bumped up.

Hi,
Thanks for your library!
I think the library version should be bumped up to 0.5.1, here is why:
I just added your library to my ESP32 PlatformIO project, but it did not work.
After several hours of debugging I found out there is an extra unneeded Wire.beginTransmission(...); before Wire.requestFrom(...).
I wanted to report it as bug, but I found out it was already fixed here. However since the lib version was not changed, you still get the non working version when you install the lib with PlatformIO.
Thanks a lot

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.