MPU6050_DMP6.ino 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. // 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. http://arduino.cc/forum/index.php/topic,109987.0.html
  68. http://code.google.com/p/arduino/issues/detail?id=958
  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. // http://en.wikipedia.org/wiki/Gimbal_lock)
  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: http://en.wikipedia.org/wiki/Gimbal_lock)
  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. // track FIFO count here in case there is > 1 packet available
  227. // (this lets us immediately read more without waiting for an interrupt)
  228. fifoCount -= packetSize;
  229. #ifdef OUTPUT_READABLE_QUATERNION
  230. // display quaternion values in easy matrix form: w x y z
  231. mpu.dmpGetQuaternion(&q, fifoBuffer);
  232. Serial.print("quat\t");
  233. Serial.print(q.w);
  234. Serial.print("\t");
  235. Serial.print(q.x);
  236. Serial.print("\t");
  237. Serial.print(q.y);
  238. Serial.print("\t");
  239. Serial.println(q.z);
  240. #endif
  241. #ifdef OUTPUT_READABLE_EULER
  242. // display Euler angles in degrees
  243. mpu.dmpGetQuaternion(&q, fifoBuffer);
  244. mpu.dmpGetEuler(euler, &q);
  245. Serial.print("euler\t");
  246. Serial.print(euler[0] * 180/M_PI);
  247. Serial.print("\t");
  248. Serial.print(euler[1] * 180/M_PI);
  249. Serial.print("\t");
  250. Serial.println(euler[2] * 180/M_PI);
  251. #endif
  252. #ifdef OUTPUT_READABLE_YAWPITCHROLL
  253. // display Euler angles in degrees
  254. mpu.dmpGetQuaternion(&q, fifoBuffer);
  255. mpu.dmpGetGravity(&gravity, &q);
  256. mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  257. Serial.print("ypr\t");
  258. Serial.print(ypr[0] * 180/M_PI);
  259. Serial.print("\t");
  260. Serial.print(ypr[1] * 180/M_PI);
  261. Serial.print("\t");
  262. Serial.println(ypr[2] * 180/M_PI);
  263. #endif
  264. #ifdef OUTPUT_READABLE_REALACCEL
  265. // display real acceleration, adjusted to remove gravity
  266. mpu.dmpGetQuaternion(&q, fifoBuffer);
  267. mpu.dmpGetAccel(&aa, fifoBuffer);
  268. mpu.dmpGetGravity(&gravity, &q);
  269. mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  270. Serial.print("areal\t");
  271. Serial.print(aaReal.x);
  272. Serial.print("\t");
  273. Serial.print(aaReal.y);
  274. Serial.print("\t");
  275. Serial.println(aaReal.z);
  276. #endif
  277. #ifdef OUTPUT_READABLE_WORLDACCEL
  278. // display initial world-frame acceleration, adjusted to remove gravity
  279. // and rotated based on known orientation from quaternion
  280. mpu.dmpGetQuaternion(&q, fifoBuffer);
  281. mpu.dmpGetAccel(&aa, fifoBuffer);
  282. mpu.dmpGetGravity(&gravity, &q);
  283. mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  284. mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
  285. Serial.print("aworld\t");
  286. Serial.print(aaWorld.x);
  287. Serial.print("\t");
  288. Serial.print(aaWorld.y);
  289. Serial.print("\t");
  290. Serial.println(aaWorld.z);
  291. #endif
  292. #ifdef OUTPUT_TEAPOT
  293. // display quaternion values in InvenSense Teapot demo format:
  294. teapotPacket[2] = fifoBuffer[0];
  295. teapotPacket[3] = fifoBuffer[1];
  296. teapotPacket[4] = fifoBuffer[4];
  297. teapotPacket[5] = fifoBuffer[5];
  298. teapotPacket[6] = fifoBuffer[8];
  299. teapotPacket[7] = fifoBuffer[9];
  300. teapotPacket[8] = fifoBuffer[12];
  301. teapotPacket[9] = fifoBuffer[13];
  302. Serial.write(teapotPacket, 14);
  303. teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
  304. #endif
  305. // blink LED to indicate activity
  306. blinkState = !blinkState;
  307. digitalWrite(LED_PIN, blinkState);
  308. }
  309. }