极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 8613|回复: 4

菜鸟看 MPU-6050

[复制链接]
发表于 2014-9-25 20:15:01 | 显示全部楼层 |阅读模式
本帖最后由 hi55234 于 2014-9-25 20:19 编辑




库在这里:

MPU6050_6Axis_MotionApps20.h
https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

I2Cdev.h
https://github.com/jrowberg/i2cd ... 49fa/Arduino/I2Cdev

高大上的程序,直接出航向、仰角、翻滚

PS:特别注意,在不改变其i2c地址的情况下,很容易就和DS1307的地址就冲突了,不用看,就是 0x68这个地址



  1. // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
  2. // 6/21/2012 by Jeff Rowberg <[email][email protected][/email]>
  3. // Updates should (hopefully) always be available at [url]https://github.com/jrowberg/i2cdevlib[/url]
  4. //
  5. // Changelog:
  6. //      2013-05-08 - added seamless Fastwire support
  7. //                 - added note about gyro calibration
  8. //      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
  9. //      2012-06-20 - improved FIFO overflow handling and simplified read process
  10. //      2012-06-19 - completely rearranged DMP initialization code and simplification
  11. //      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
  12. //      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
  13. //      2012-06-05 - add gravity-compensated initial reference frame acceleration output
  14. //                 - add 3D math helper file to DMP6 example sketch
  15. //                 - add Euler output and Yaw/Pitch/Roll output formats
  16. //      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
  17. //      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
  18. //      2012-05-30 - basic DMP initialization working

  19. /* ============================================
  20. I2Cdev device library code is placed under the MIT license
  21. Copyright (c) 2012 Jeff Rowberg

  22. Permission is hereby granted, free of charge, to any person obtaining a copy
  23. of this software and associated documentation files (the "Software"), to deal
  24. in the Software without restriction, including without limitation the rights
  25. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  26. copies of the Software, and to permit persons to whom the Software is
  27. furnished to do so, subject to the following conditions:

  28. The above copyright notice and this permission notice shall be included in
  29. all copies or substantial portions of the Software.

  30. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  32. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  33. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  34. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  35. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  36. THE SOFTWARE.
  37. ===============================================
  38. */

  39. // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
  40. // for both classes must be in the include path of your project
  41. #include "I2Cdev.h"

  42. #include "MPU6050_6Axis_MotionApps20.h"
  43. //#include "MPU6050.h" // not necessary if using MotionApps include file

  44. // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
  45. // is used in I2Cdev.h
  46. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  47.     #include "Wire.h"
  48. #endif

  49. // class default I2C address is 0x68
  50. // specific I2C addresses may be passed as a parameter here
  51. // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
  52. // AD0 high = 0x69
  53. MPU6050 mpu;
  54. //MPU6050 mpu(0x69); // <-- use for AD0 high

  55. /* =========================================================================
  56.    NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
  57.    depends on the MPU-6050's INT pin being connected to the Arduino's
  58.    external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
  59.    digital I/O pin 2.
  60. * ========================================================================= */

  61. /* =========================================================================
  62.    NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
  63.    when using Serial.write(buf, len). The Teapot output uses this method.
  64.    The solution requires a modification to the Arduino USBAPI.h file, which
  65.    is fortunately simple, but annoying. This will be fixed in the next IDE
  66.    release. For more info, see these links:

  67.    [url]http://arduino.cc/forum/index.php/topic[/url],109987.0.html
  68.    [url]http://code.google.com/p/arduino/issues/detail?id=958[/url]
  69. * ========================================================================= */



  70. // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
  71. // quaternion components in a [w, x, y, z] format (not best for parsing
  72. // on a remote host such as Processing or something though)
  73. //#define OUTPUT_READABLE_QUATERNION

  74. // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
  75. // (in degrees) calculated from the quaternions coming from the FIFO.
  76. // Note that Euler angles suffer from gimbal lock (for more info, see
  77. // [url]http://en.wikipedia.org/wiki/Gimbal_lock[/url])
  78. //#define OUTPUT_READABLE_EULER

  79. // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
  80. // pitch/roll angles (in degrees) calculated from the quaternions coming
  81. // from the FIFO. Note this also requires gravity vector calculations.
  82. // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
  83. // more info, see: [url]http://en.wikipedia.org/wiki/Gimbal_lock[/url])
  84. #define OUTPUT_READABLE_YAWPITCHROLL

  85. // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
  86. // components with gravity removed. This acceleration reference frame is
  87. // not compensated for orientation, so +X is always +X according to the
  88. // sensor, just without the effects of gravity. If you want acceleration
  89. // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
  90. //#define OUTPUT_READABLE_REALACCEL

  91. // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
  92. // components with gravity removed and adjusted for the world frame of
  93. // reference (yaw is relative to initial orientation, since no magnetometer
  94. // is present in this case). Could be quite handy in some cases.
  95. //#define OUTPUT_READABLE_WORLDACCEL

  96. // uncomment "OUTPUT_TEAPOT" if you want output that matches the
  97. // format used for the InvenSense teapot demo
  98. //#define OUTPUT_TEAPOT



  99. #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
  100. bool blinkState = false;

  101. // MPU control/status vars
  102. bool dmpReady = false;  // set true if DMP init was successful
  103. uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
  104. uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
  105. uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
  106. uint16_t fifoCount;     // count of all bytes currently in FIFO
  107. uint8_t fifoBuffer[64]; // FIFO storage buffer

  108. // orientation/motion vars
  109. Quaternion q;           // [w, x, y, z]         quaternion container
  110. VectorInt16 aa;         // [x, y, z]            accel sensor measurements
  111. VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
  112. VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
  113. VectorFloat gravity;    // [x, y, z]            gravity vector
  114. float euler[3];         // [psi, theta, phi]    Euler angle container
  115. float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

  116. // packet structure for InvenSense teapot demo
  117. uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };



  118. // ================================================================
  119. // ===               INTERRUPT DETECTION ROUTINE                ===
  120. // ================================================================

  121. volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
  122. void dmpDataReady() {
  123.     mpuInterrupt = true;
  124. }



  125. // ================================================================
  126. // ===                      INITIAL SETUP                       ===
  127. // ================================================================

  128. void setup() {
  129.     // join I2C bus (I2Cdev library doesn't do this automatically)
  130.     #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  131.         Wire.begin();
  132.         TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
  133.     #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  134.         Fastwire::setup(400, true);
  135.     #endif

  136.     // initialize serial communication
  137.     // (115200 chosen because it is required for Teapot Demo output, but it's
  138.     // really up to you depending on your project)
  139.     Serial.begin(115200);
  140.     while (!Serial); // wait for Leonardo enumeration, others continue immediately

  141.     // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
  142.     // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
  143.     // the baud timing being too misaligned with processor ticks. You must use
  144.     // 38400 or slower in these cases, or use some kind of external separate
  145.     // crystal solution for the UART timer.

  146.     // initialize device
  147.     Serial.println(F("Initializing I2C devices..."));
  148.     mpu.initialize();

  149.     // verify connection
  150.     Serial.println(F("Testing device connections..."));
  151.     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  152.     // wait for ready
  153.     Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  154.     while (Serial.available() && Serial.read()); // empty buffer
  155.     while (!Serial.available());                 // wait for data
  156.     while (Serial.available() && Serial.read()); // empty buffer again

  157.     // load and configure the DMP
  158.     Serial.println(F("Initializing DMP..."));
  159.     devStatus = mpu.dmpInitialize();

  160.     // supply your own gyro offsets here, scaled for min sensitivity
  161.     mpu.setXGyroOffset(220);
  162.     mpu.setYGyroOffset(76);
  163.     mpu.setZGyroOffset(-85);
  164.     mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  165.     // make sure it worked (returns 0 if so)
  166.     if (devStatus == 0) {
  167.         // turn on the DMP, now that it's ready
  168.         Serial.println(F("Enabling DMP..."));
  169.         mpu.setDMPEnabled(true);

  170.         // enable Arduino interrupt detection
  171.         Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
  172.         attachInterrupt(0, dmpDataReady, RISING);
  173.         mpuIntStatus = mpu.getIntStatus();

  174.         // set our DMP Ready flag so the main loop() function knows it's okay to use it
  175.         Serial.println(F("DMP ready! Waiting for first interrupt..."));
  176.         dmpReady = true;

  177.         // get expected DMP packet size for later comparison
  178.         packetSize = mpu.dmpGetFIFOPacketSize();
  179.     } else {
  180.         // ERROR!
  181.         // 1 = initial memory load failed
  182.         // 2 = DMP configuration updates failed
  183.         // (if it's going to break, usually the code will be 1)
  184.         Serial.print(F("DMP Initialization failed (code "));
  185.         Serial.print(devStatus);
  186.         Serial.println(F(")"));
  187.     }

  188.     // configure LED for output
  189.     pinMode(LED_PIN, OUTPUT);
  190. }



  191. // ================================================================
  192. // ===                    MAIN PROGRAM LOOP                     ===
  193. // ================================================================

  194. void loop() {
  195.     // if programming failed, don't try to do anything
  196.     if (!dmpReady) return;

  197.     // wait for MPU interrupt or extra packet(s) available
  198.     while (!mpuInterrupt && fifoCount < packetSize) {
  199.         // other program behavior stuff here
  200.         // .
  201.         // .
  202.         // .
  203.         // if you are really paranoid you can frequently test in between other
  204.         // stuff to see if mpuInterrupt is true, and if so, "break;" from the
  205.         // while() loop to immediately process the MPU data
  206.         // .
  207.         // .
  208.         // .
  209.     }

  210.     // reset interrupt flag and get INT_STATUS byte
  211.     mpuInterrupt = false;
  212.     mpuIntStatus = mpu.getIntStatus();

  213.     // get current FIFO count
  214.     fifoCount = mpu.getFIFOCount();

  215.     // check for overflow (this should never happen unless our code is too inefficient)
  216.     if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
  217.         // reset so we can continue cleanly
  218.         mpu.resetFIFO();
  219.         Serial.println(F("FIFO overflow!"));

  220.     // otherwise, check for DMP data ready interrupt (this should happen frequently)
  221.     } else if (mpuIntStatus & 0x02) {
  222.         // wait for correct available data length, should be a VERY short wait
  223.         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

  224.         // read a packet from FIFO
  225.         mpu.getFIFOBytes(fifoBuffer, packetSize);
  226.         
  227.         // track FIFO count here in case there is > 1 packet available
  228.         // (this lets us immediately read more without waiting for an interrupt)
  229.         fifoCount -= packetSize;

  230.         #ifdef OUTPUT_READABLE_QUATERNION
  231.             // display quaternion values in easy matrix form: w x y z
  232.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  233.             Serial.print("quat\t");
  234.             Serial.print(q.w);
  235.             Serial.print("\t");
  236.             Serial.print(q.x);
  237.             Serial.print("\t");
  238.             Serial.print(q.y);
  239.             Serial.print("\t");
  240.             Serial.println(q.z);
  241.         #endif

  242.         #ifdef OUTPUT_READABLE_EULER
  243.             // display Euler angles in degrees
  244.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  245.             mpu.dmpGetEuler(euler, &q);
  246.             Serial.print("euler\t");
  247.             Serial.print(euler[0] * 180/M_PI);
  248.             Serial.print("\t");
  249.             Serial.print(euler[1] * 180/M_PI);
  250.             Serial.print("\t");
  251.             Serial.println(euler[2] * 180/M_PI);
  252.         #endif

  253.         #ifdef OUTPUT_READABLE_YAWPITCHROLL
  254.             // display Euler angles in degrees
  255.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  256.             mpu.dmpGetGravity(&gravity, &q);
  257.             mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  258.             Serial.print("ypr\t");
  259.             Serial.print(ypr[0] * 180/M_PI);
  260.             Serial.print("\t");
  261.             Serial.print(ypr[1] * 180/M_PI);
  262.             Serial.print("\t");
  263.             Serial.println(ypr[2] * 180/M_PI);
  264.         #endif

  265.         #ifdef OUTPUT_READABLE_REALACCEL
  266.             // display real acceleration, adjusted to remove gravity
  267.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  268.             mpu.dmpGetAccel(&aa, fifoBuffer);
  269.             mpu.dmpGetGravity(&gravity, &q);
  270.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  271.             Serial.print("areal\t");
  272.             Serial.print(aaReal.x);
  273.             Serial.print("\t");
  274.             Serial.print(aaReal.y);
  275.             Serial.print("\t");
  276.             Serial.println(aaReal.z);
  277.         #endif

  278.         #ifdef OUTPUT_READABLE_WORLDACCEL
  279.             // display initial world-frame acceleration, adjusted to remove gravity
  280.             // and rotated based on known orientation from quaternion
  281.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  282.             mpu.dmpGetAccel(&aa, fifoBuffer);
  283.             mpu.dmpGetGravity(&gravity, &q);
  284.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  285.             mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
  286.             Serial.print("aworld\t");
  287.             Serial.print(aaWorld.x);
  288.             Serial.print("\t");
  289.             Serial.print(aaWorld.y);
  290.             Serial.print("\t");
  291.             Serial.println(aaWorld.z);
  292.         #endif
  293.    
  294.         #ifdef OUTPUT_TEAPOT
  295.             // display quaternion values in InvenSense Teapot demo format:
  296.             teapotPacket[2] = fifoBuffer[0];
  297.             teapotPacket[3] = fifoBuffer[1];
  298.             teapotPacket[4] = fifoBuffer[4];
  299.             teapotPacket[5] = fifoBuffer[5];
  300.             teapotPacket[6] = fifoBuffer[8];
  301.             teapotPacket[7] = fifoBuffer[9];
  302.             teapotPacket[8] = fifoBuffer[12];
  303.             teapotPacket[9] = fifoBuffer[13];
  304.             Serial.write(teapotPacket, 14);
  305.             teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
  306.         #endif

  307.         // blink LED to indicate activity
  308.         blinkState = !blinkState;
  309.         digitalWrite(LED_PIN, blinkState);
  310.     }
  311. }
复制代码



另外附一个arduino官方对这玩意介绍的地址:
http://playground.arduino.cc/Main/MPU-6050

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x
回复

使用道具 举报

发表于 2014-9-26 10:33:48 | 显示全部楼层
赞,顺便把硬件连接也给出来就好了
回复 支持 反对

使用道具 举报

发表于 2014-9-26 11:45:08 | 显示全部楼层
谢谢分享!学习了!!!
回复 支持 反对

使用道具 举报

发表于 2014-10-26 02:03:16 | 显示全部楼层
我这里出来的数据漂移很严重啊,特别是yaw & pitch, roll好一点。特别是刚开始测试的时候,有时候随便转一下又会好一点。不知道怎么回事啊。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-10-26 21:20:36 | 显示全部楼层
sinyontom 发表于 2014-10-26 02:03
我这里出来的数据漂移很严重啊,特别是yaw & pitch, roll好一点。特别是刚开始测试的时候,有时候随便转一下 ...

yaw随它去,因为没有磁力校正,所以飘很正常,用后2个就够了
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-15 17:29 , Processed in 0.039850 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表