Advertisement
Guest User

Untitled

a guest
Aug 1st, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 15.19 KB | None | 0 0
  1. // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
  2. // 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
  3. // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
  4. //
  5. // Changelog:
  6. //     2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
  7. //     2012-06-20 - improved FIFO overflow handling and simplified read process
  8. //     2012-06-19 - completely rearranged DMP initialization code and simplification
  9. //     2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
  10. //     2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
  11. //     2012-06-05 - add gravity-compensated initial reference frame acceleration output
  12. //                - add 3D math helper file to DMP6 example sketch
  13. //                - add Euler output and Yaw/Pitch/Roll output formats
  14. //     2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
  15. //     2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
  16. //     2012-05-30 - basic DMP initialization working
  17.  
  18. /* ============================================
  19. I2Cdev device library code is placed under the MIT license
  20. Copyright (c) 2012 Jeff Rowberg
  21.  
  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.  
  29. The above copyright notice and this permission notice shall be included in
  30. all copies or substantial portions of the Software.
  31.  
  32. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  33. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  34. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  35. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  36. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  38. THE SOFTWARE.
  39. ===============================================
  40. */
  41.  
  42. // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
  43. // is used in I2Cdev.h
  44. #include "Wire.h"
  45.  
  46. // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
  47. // for both classes must be in the include path of your project
  48. #include "I2Cdev.h"
  49.  
  50. #include "MPU6050_6Axis_MotionApps20.h"
  51. //#include "MPU6050.h" // not necessary if using MotionApps include file
  52.  
  53. // class default I2C address is 0x68
  54. // specific I2C addresses may be passed as a parameter here
  55. // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
  56. // AD0 high = 0x69
  57. MPU6050 mpu;
  58.  
  59. /* =========================================================================
  60.    NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
  61.    depends on the MPU-6050's INT pin being connected to the Arduino's
  62.    external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
  63.    digital I/O pin 2.
  64.  * ========================================================================= */
  65.  
  66. /* =========================================================================
  67.    NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
  68.    when using Serial.write(buf, len). The Teapot output uses this method.
  69.    The solution requires a modification to the Arduino USBAPI.h file, which
  70.    is fortunately simple, but annoying. This will be fixed in the next IDE
  71.    release. For more info, see these links:
  72.  
  73.    http://arduino.cc/forum/index.php/topic,109987.0.html
  74.    http://code.google.com/p/arduino/issues/detail?id=958
  75.  * ========================================================================= */
  76.  
  77.  
  78.  
  79. // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
  80. // quaternion components in a [w, x, y, z] format (not best for parsing
  81. // on a remote host such as Processing or something though)
  82. //#define OUTPUT_READABLE_QUATERNION
  83.  
  84. // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
  85. // (in degrees) calculated from the quaternions coming from the FIFO.
  86. // Note that Euler angles suffer from gimbal lock (for more info, see
  87. // http://en.wikipedia.org/wiki/Gimbal_lock)
  88. //#define OUTPUT_READABLE_EULER
  89.  
  90. // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
  91. // pitch/roll angles (in degrees) calculated from the quaternions coming
  92. // from the FIFO. Note this also requires gravity vector calculations.
  93. // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
  94. // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
  95. //#define OUTPUT_READABLE_YAWPITCHROLL
  96.  
  97. // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
  98. // components with gravity removed. This acceleration reference frame is
  99. // not compensated for orientation, so +X is always +X according to the
  100. // sensor, just without the effects of gravity. If you want acceleration
  101. // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
  102. //#define OUTPUT_READABLE_REALACCEL
  103.  
  104. // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
  105. // components with gravity removed and adjusted for the world frame of
  106. // reference (yaw is relative to initial orientation, since no magnetometer
  107. // is present in this case). Could be quite handy in some cases.
  108. //#define OUTPUT_READABLE_WORLDACCEL
  109.  
  110. // uncomment "OUTPUT_TEAPOT" if you want output that matches the
  111. // format used for the InvenSense teapot demo
  112. #define OUTPUT_TEAPOT
  113.  
  114.  
  115.  
  116. #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
  117. bool blinkState = false;
  118.  
  119. // MPU control/status vars
  120. bool dmpReady = false;  // set true if DMP init was successful
  121. uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
  122. uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
  123. uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
  124. uint16_t fifoCount;     // count of all bytes currently in FIFO
  125. uint8_t fifoBuffer[64]; // FIFO storage buffer
  126.  
  127. // orientation/motion vars
  128. Quaternion q;           // [w, x, y, z]         quaternion container
  129. VectorInt16 aa;         // [x, y, z]            accel sensor measurements
  130. VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
  131. VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
  132. VectorFloat gravity;    // [x, y, z]            gravity vector
  133. float euler[3];         // [psi, theta, phi]    Euler angle container
  134. float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
  135.  
  136. // packet structure for InvenSense teapot demo
  137. uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
  138.  
  139.  
  140.  
  141. // ================================================================
  142. // ===               INTERRUPT DETECTION ROUTINE                ===
  143. // ================================================================
  144.  
  145. volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
  146. void dmpDataReady() {
  147.     mpuInterrupt = true;
  148. }
  149.  
  150.  
  151.  
  152. // ================================================================
  153. // ===                      INITIAL SETUP                       ===
  154. // ================================================================
  155.  
  156. void setup() {
  157.     // join I2C bus (I2Cdev library doesn't do this automatically)
  158.     Wire.begin();
  159.  
  160.     // initialize serial communication
  161.     // (115200 chosen because it is required for Teapot Demo output, but it's
  162.     // really up to you depending on your project)
  163.     Serial.begin(9600);
  164.     while (!Serial); // wait for Leonardo enumeration, others continue immediately
  165.  
  166.     // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
  167.     // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
  168.     // the baud timing being too misaligned with processor ticks. You must use
  169.     // 38400 or slower in these cases, or use some kind of external separate
  170.     // crystal solution for the UART timer.
  171.  
  172.     // initialize device
  173.     Serial.println(F("Initializing I2C devices..."));
  174.     mpu.initialize();
  175.  
  176.     // verify connection
  177.     Serial.println(F("Testing device connections..."));
  178.     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
  179.  
  180.     // wait for ready
  181.     Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  182.     while (Serial.available() && Serial.read()); // empty buffer
  183.     while (!Serial.available());                 // wait for data
  184.     while (Serial.available() && Serial.read()); // empty buffer again
  185.  
  186.     // load and configure the DMP
  187.     Serial.println(F("Initializing DMP..."));
  188.     devStatus = mpu.dmpInitialize();
  189.    
  190.     // make sure it worked (returns 0 if so)
  191.     if (devStatus == 0) {
  192.         // turn on the DMP, now that it's ready
  193.         Serial.println(F("Enabling DMP..."));
  194.         mpu.setDMPEnabled(true);
  195.  
  196.         // enable Arduino interrupt detection
  197.         Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
  198.         attachInterrupt(0, dmpDataReady, RISING);
  199.         mpuIntStatus = mpu.getIntStatus();
  200.  
  201.         // set our DMP Ready flag so the main loop() function knows it's okay to use it
  202.         Serial.println(F("DMP ready! Waiting for first interrupt..."));
  203.         dmpReady = true;
  204.  
  205.         // get expected DMP packet size for later comparison
  206.         packetSize = mpu.dmpGetFIFOPacketSize();
  207.     } else {
  208.         // ERROR!
  209.         // 1 = initial memory load failed
  210.         // 2 = DMP configuration updates failed
  211.         // (if it's going to break, usually the code will be 1)
  212.         Serial.print(F("DMP Initialization failed (code "));
  213.         Serial.print(devStatus);
  214.         Serial.println(F(")"));
  215.     }
  216.  
  217.     // configure LED for output
  218.     pinMode(LED_PIN, OUTPUT);
  219. }
  220.  
  221.  
  222.  
  223. // ================================================================
  224. // ===                    MAIN PROGRAM LOOP                     ===
  225. // ================================================================
  226.  
  227. void loop() {
  228.     // if programming failed, don't try to do anything
  229.     if (!dmpReady) return;
  230.  
  231.     // wait for MPU interrupt or extra packet(s) available
  232.     while (!mpuInterrupt && fifoCount < packetSize) {
  233.         // other program behavior stuff here
  234.         // .
  235.         // .
  236.         // .
  237.         // if you are really paranoid you can frequently test in between other
  238.         // stuff to see if mpuInterrupt is true, and if so, "break;" from the
  239.         // while() loop to immediately process the MPU data
  240.         // .
  241.         // .
  242.         // .
  243.     }
  244.  
  245.     // reset interrupt flag and get INT_STATUS byte
  246.     mpuInterrupt = false;
  247.     mpuIntStatus = mpu.getIntStatus();
  248.  
  249.     // get current FIFO count
  250.     fifoCount = mpu.getFIFOCount();
  251.  
  252.     // check for overflow (this should never happen unless our code is too inefficient)
  253.     if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
  254.         // reset so we can continue cleanly
  255.         mpu.resetFIFO();
  256.         Serial.println(F("FIFO overflow!"));
  257.  
  258.     // otherwise, check for DMP data ready interrupt (this should happen frequently)
  259.     } else if (mpuIntStatus & 0x02) {
  260.         // wait for correct available data length, should be a VERY short wait
  261.         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
  262.  
  263.         // read a packet from FIFO
  264.         mpu.getFIFOBytes(fifoBuffer, packetSize);
  265.        
  266.         // track FIFO count here in case there is > 1 packet available
  267.         // (this lets us immediately read more without waiting for an interrupt)
  268.         fifoCount -= packetSize;
  269.  
  270.         #ifdef OUTPUT_READABLE_QUATERNION
  271.             // display quaternion values in easy matrix form: w x y z
  272.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  273.             Serial.print("quat\t");
  274.             Serial.print(q.w);
  275.             Serial.print("\t");
  276.             Serial.print(q.x);
  277.             Serial.print("\t");
  278.             Serial.print(q.y);
  279.             Serial.print("\t");
  280.             Serial.println(q.z);
  281.         #endif
  282.  
  283.         #ifdef OUTPUT_READABLE_EULER
  284.             // display Euler angles in degrees
  285.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  286.             mpu.dmpGetEuler(euler, &q);
  287.             Serial.print("euler\t");
  288.             Serial.print(euler[0] * 180/M_PI);
  289.             Serial.print("\t");
  290.             Serial.print(euler[1] * 180/M_PI);
  291.             Serial.print("\t");
  292.             Serial.println(euler[2] * 180/M_PI);
  293.         #endif
  294.  
  295.         #ifdef OUTPUT_READABLE_YAWPITCHROLL
  296.             // display Euler angles in degrees
  297.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  298.             mpu.dmpGetGravity(&gravity, &q);
  299.             mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  300.             Serial.print("ypr\t");
  301.             Serial.print(ypr[0] * 180/M_PI);
  302.             Serial.print("\t");
  303.             Serial.print(ypr[1] * 180/M_PI);
  304.             Serial.print("\t");
  305.             Serial.println(ypr[2] * 180/M_PI);
  306.         #endif
  307.  
  308.         #ifdef OUTPUT_READABLE_REALACCEL
  309.             // display real acceleration, adjusted to remove gravity
  310.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  311.             mpu.dmpGetAccel(&aa, fifoBuffer);
  312.             mpu.dmpGetGravity(&gravity, &q);
  313.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  314.             Serial.print("areal\t");
  315.             Serial.print(aaReal.x);
  316.             Serial.print("\t");
  317.             Serial.print(aaReal.y);
  318.             Serial.print("\t");
  319.             Serial.println(aaReal.z);
  320.         #endif
  321.  
  322.         #ifdef OUTPUT_READABLE_WORLDACCEL
  323.             // display initial world-frame acceleration, adjusted to remove gravity
  324.             // and rotated based on known orientation from quaternion
  325.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  326.             mpu.dmpGetAccel(&aa, fifoBuffer);
  327.             mpu.dmpGetGravity(&gravity, &q);
  328.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  329.             mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
  330.             Serial.print("aworld\t");
  331.             Serial.print(aaWorld.x);
  332.             Serial.print("\t");
  333.             Serial.print(aaWorld.y);
  334.             Serial.print("\t");
  335.             Serial.println(aaWorld.z);
  336.         #endif
  337.    
  338.         #ifdef OUTPUT_TEAPOT
  339.             // display quaternion values in InvenSense Teapot demo format:
  340.             teapotPacket[2] = fifoBuffer[0];
  341.             teapotPacket[3] = fifoBuffer[1];
  342.             teapotPacket[4] = fifoBuffer[4];
  343.             teapotPacket[5] = fifoBuffer[5];
  344.             teapotPacket[6] = fifoBuffer[8];
  345.             teapotPacket[7] = fifoBuffer[9];
  346.             teapotPacket[8] = fifoBuffer[12];
  347.             teapotPacket[9] = fifoBuffer[13];
  348.             Serial.write(teapotPacket, 14);
  349.             teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
  350.         #endif
  351.  
  352.         // blink LED to indicate activity
  353.         blinkState = !blinkState;
  354.         digitalWrite(LED_PIN, blinkState);
  355.     }
  356. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement