Advertisement
Guest User

Untitled

a guest
Jul 26th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 15.03 KB | None | 0 0
  1. // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
  2. // for both classes must be in the include path of your project
  3. #include "I2Cdev.h"
  4.  
  5. #include "MPU6050_6Axis_MotionApps20.h"
  6. #include "MPU6050.h" // not necessary if using MotionApps include file
  7.  
  8. // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
  9. // is used in I2Cdev.h
  10. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  11.     #include "Wire.h"
  12. #endif
  13.  
  14. // class default I2C address is 0x68
  15. // specific I2C addresses may be passed as a parameter here
  16. // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
  17. // AD0 high = 0x69
  18. MPU6050 mpu;
  19. //MPU6050 mpu(0x69); // <-- use for AD0 high
  20.  
  21.  
  22.  
  23. /* =========================================================================
  24.    NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
  25.    depends on the MPU-6050's INT pin being connected to the Arduino's
  26.    external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
  27.    digital I/O pin 2.
  28.  * ========================================================================= */
  29.  
  30. /* =========================================================================
  31.    NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
  32.    when using Serial.write(buf, len). The Teapot output uses this method.
  33.    The solution requires a modification to the Arduino USBAPI.h file, which
  34.    is fortunately simple, but annoying. This will be fixed in the next IDE
  35.    release. For more info, see these links:
  36.    http://arduino.cc/forum/index.php/topic,109987.0.html
  37.    http://code.google.com/p/arduino/issues/detail?id=958
  38.  * ========================================================================= */
  39.  
  40.  
  41.  
  42. // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
  43. // quaternion components in a [w, x, y, z] format (not best for parsing
  44. // on a remote host such as Processing or something though)
  45. #define OUTPUT_READABLE_QUATERNION
  46.  
  47. // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
  48. // (in degrees) calculated from the quaternions coming from the FIFO.
  49. // Note that Euler angles suffer from gimbal lock (for more info, see
  50. // http://en.wikipedia.org/wiki/Gimbal_lock)
  51. //#define OUTPUT_READABLE_EULER
  52.  
  53. // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
  54. // pitch/roll angles (in degrees) calculated from the quaternions coming
  55. // from the FIFO. Note this also requires gravity vector calculations.
  56. // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
  57. // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
  58. //#define OUTPUT_READABLE_YAWPITCHROLL
  59.  
  60. // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
  61. // components with gravity removed. This acceleration reference frame is
  62. // not compensated for orientation, so +X is always +X according to the
  63. // sensor, just without the effects of gravity. If you want acceleration
  64. // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
  65. //#define OUTPUT_READABLE_REALACCEL
  66.  
  67. // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
  68. // components with gravity removed and adjusted for the world frame of
  69. // reference (yaw is relative to initial orientation, since no magnetometer
  70. // is present in this case). Could be quite handy in some cases.
  71. //#define OUTPUT_READABLE_WORLDACCEL
  72.  
  73. // uncomment "OUTPUT_TEAPOT" if you want output that matches the
  74. // format used for the InvenSense teapot demo
  75. //#define OUTPUT_TEAPOT
  76.  
  77.  
  78. #define registroEscribir 0x6b
  79. #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
  80. #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
  81. bool blinkState = false;
  82.  
  83. // MPU control/status vars
  84. bool dmpReady = false;  // set true if DMP init was successful
  85. uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
  86. uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
  87. uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
  88. uint16_t fifoCount;     // count of all bytes currently in FIFO
  89. uint8_t fifoBuffer[64]; // FIFO storage buffer
  90.  
  91. // orientation/motion vars
  92. Quaternion q;           // [w, x, y, z]         quaternion container
  93. VectorInt16 aa;         // [x, y, z]            accel sensor measurements
  94. VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
  95. VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
  96. VectorFloat gravity;    // [x, y, z]            gravity vector
  97. float euler[3];         // [psi, theta, phi]    Euler angle container
  98. float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
  99.  
  100. // packet structure for InvenSense teapot demo
  101. uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
  102.  
  103. bool dormido;
  104.  
  105. // ================================================================
  106. // ===               INTERRUPT DETECTION ROUTINE                ===
  107. // ================================================================
  108.  
  109. volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
  110. void dmpDataReady() {
  111.     mpuInterrupt = true;
  112. }
  113.  
  114.  
  115.  
  116. // ================================================================
  117. // ===                      INITIAL SETUP                       ===
  118. // ================================================================
  119.  
  120. void setup() {
  121.     // join I2C bus (I2Cdev library doesn't do this automatically)
  122.     #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  123.         Wire.begin();
  124.         Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
  125.     #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  126.         Fastwire::setup(400, true);
  127.     #endif
  128.  
  129.     // initialize serial communication
  130.     // (115200 chosen because it is required for Teapot Demo output, but it's
  131.     // really up to you depending on your project)
  132.     Serial.begin(38400);
  133.     while (!Serial); // wait for Leonardo enumeration, others continue immediately
  134.  
  135.     // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
  136.     // Pro Mini running at 3.3V, cannot handle this baud rate reliably due to
  137.     // the baud timing being too misaligned with processor ticks. You must use
  138.     // 38400 or slower in these cases, or use some kind of external separate
  139.     // crystal solution for the UART timer.
  140.  
  141.     // initialize device
  142.     Serial.println(F("Initializing I2C devices..."));
  143.     mpu.setSleepEnabled(false);
  144.    
  145.  
  146.     mpu.initialize();
  147.     mpu.setSleepEnabled(false);
  148.     pinMode(INTERRUPT_PIN, INPUT);
  149.  
  150.     // verify connection
  151.     Serial.println(F("Testing device connections..."));
  152.     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
  153.  
  154.     // wait for ready
  155.     Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  156.     Serial.println(F("\nCodigo comentado de los 3 ciclos while "));
  157.    
  158.    
  159.     while (Serial.available() && Serial.read()); // empty buffer
  160.     while (!Serial.available());                 // wait for data
  161.     while (Serial.available() && Serial.read()); // empty buffer again
  162.    
  163.     // load and configure the DMP
  164.     Serial.println(F("Initializing DMP..."));
  165.     devStatus = mpu.dmpInitialize();
  166.     mpu.setSleepEnabled(false);
  167.  
  168.     dormido = mpu.getSleepEnabled();
  169.  
  170.     if (dormido)
  171.       Serial.println(F("Dormido!"));
  172.     else
  173.       Serial.println(F("No dormido!"));
  174.          
  175.     // supply your own gyro offsets here, scaled for min sensitivity
  176.     mpu.setXGyroOffset(500);
  177.     mpu.setYGyroOffset(500);
  178.     mpu.setZGyroOffset(500);
  179.     mpu.setZAccelOffset(500); // 1688 factory default for my test chip
  180.  
  181.     // make sure it worked (returns 0 if so)
  182.     if (devStatus == 0) {
  183.         // Calibration Time: generate offsets and calibrate our MPU6050
  184.         mpu.CalibrateAccel(6);
  185.         mpu.CalibrateGyro(6);
  186.         mpu.PrintActiveOffsets();
  187.         // turn on the DMP, now that it's ready
  188.         Serial.println(F("Enabling DMP..."));
  189.         mpu.setDMPEnabled(true);
  190.  
  191.         // enable Arduino interrupt detection
  192.         Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
  193.         Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
  194.         Serial.println(F(")..."));
  195.         attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
  196.         mpuIntStatus = mpu.getIntStatus();
  197.  
  198.         // set our DMP Ready flag so the main loop() function knows it's okay to use it
  199.         Serial.println(F("DMP ready! Waiting for first interrupt..."));
  200.         dmpReady = true;
  201.  
  202.         // get expected DMP packet size for later comparison
  203.         packetSize = mpu.dmpGetFIFOPacketSize();
  204.     } else {
  205.         // ERROR!
  206.         // 1 = initial memory load failed
  207.         // 2 = DMP configuration updates failed
  208.         // (if it's going to break, usually the code will be 1)
  209.         Serial.print(F("DMP Initialization failed (code "));
  210.         Serial.print(devStatus);
  211.         Serial.println(F(")"));
  212.     }
  213.  
  214.     // configure LED for output
  215.     pinMode(LED_PIN, OUTPUT);
  216. }
  217.  
  218.  
  219.  
  220. // ================================================================
  221. // ===                    MAIN PROGRAM LOOP                     ===
  222. // ================================================================
  223.  
  224. void loop() {
  225.  // mpu.setSleepEnabled(false);
  226.     // if programming failed, don't try to do anything
  227.     if (!dmpReady) return;
  228.  
  229.     // wait for MPU interrupt or extra packet(s) available
  230.     while (!mpuInterrupt && fifoCount < packetSize) {
  231.         if (mpuInterrupt && fifoCount < packetSize) {
  232.           // try to get out of the infinite loop
  233.           fifoCount = mpu.getFIFOCount();
  234.         }  
  235.         // other program behavior stuff here
  236.         // .
  237.         // .
  238.         // .
  239.         // if you are really paranoid you can frequently test in between other
  240.         // stuff to see if mpuInterrupt is true, and if so, "break;" from the
  241.         // while() loop to immediately process the MPU data
  242.         // .
  243.         // .
  244.         // .
  245.     }
  246.  
  247.     // reset interrupt flag and get INT_STATUS byte
  248.     mpuInterrupt = false;
  249.     mpuIntStatus = mpu.getIntStatus();
  250.  
  251.     // get current FIFO count
  252.     fifoCount = mpu.getFIFOCount();
  253.   if(fifoCount < packetSize){
  254.           //Lets go back and wait for another interrupt. We shouldn't be here, we got an interrupt from another event
  255.       // This is blocking so don't do it   while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
  256.   }
  257.     // check for overflow (this should never happen unless our code is too inefficient)
  258.     else if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
  259.         // reset so we can continue cleanly
  260.         Serial.println(F("La fifo tiene"));                                                                           ////////////////////
  261.         Serial.println(fifoCount);                                                                                 ////////////////////
  262.  
  263.         mpu.resetFIFO();
  264.       //  fifoCount = mpu.getFIFOCount();  // will be zero after reset no need to ask
  265.         Serial.println(F("FIFO overflow!"));
  266.        
  267.  
  268.     // otherwise, check for DMP data ready interrupt (this should happen frequently)
  269.     } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
  270.  
  271.         // read a packet from FIFO
  272.   while(fifoCount >= packetSize){ // Lets catch up to NOW, someone is using the dreaded delay()!
  273.     mpu.getFIFOBytes(fifoBuffer, packetSize);
  274.     // track FIFO count here in case there is > 1 packet available
  275.     // (this lets us immediately read more without waiting for an interrupt)
  276.     fifoCount -= packetSize;
  277.   }
  278.         #ifdef OUTPUT_READABLE_QUATERNION
  279.             // display quaternion values in easy matrix form: w x y z
  280.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  281.             Serial.print("quat\t");
  282.             Serial.print(q.w);
  283.             Serial.print("\t");
  284.             Serial.print(q.x);
  285.             Serial.print("\t");
  286.             Serial.print(q.y);
  287.             Serial.print("\t");
  288.             Serial.println(q.z);
  289.         #endif
  290.  
  291.         #ifdef OUTPUT_READABLE_EULER
  292.             // display Euler angles in degrees
  293.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  294.             mpu.dmpGetEuler(euler, &q);
  295.             Serial.print("euler\t");
  296.             Serial.print(euler[0] * 180/M_PI);
  297.             Serial.print("\t");
  298.             Serial.print(euler[1] * 180/M_PI);
  299.             Serial.print("\t");
  300.             Serial.println(euler[2] * 180/M_PI);
  301.         #endif
  302.  
  303.         #ifdef OUTPUT_READABLE_YAWPITCHROLL
  304.             // display Euler angles in degrees
  305.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  306.             mpu.dmpGetGravity(&gravity, &q);
  307.             mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  308.             Serial.print("ypr\t");
  309.             Serial.print(ypr[0] * 180/M_PI);
  310.             Serial.print("\t");
  311.             Serial.print(ypr[1] * 180/M_PI);
  312.             Serial.print("\t");
  313.             Serial.println(ypr[2] * 180/M_PI);
  314.         #endif
  315.  
  316.         #ifdef OUTPUT_READABLE_REALACCEL
  317.             // display real acceleration, adjusted to remove gravity
  318.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  319.             mpu.dmpGetAccel(&aa, fifoBuffer);
  320.             mpu.dmpGetGravity(&gravity, &q);
  321.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  322.             Serial.print("areal\t");
  323.             Serial.print(aaReal.x);
  324.             Serial.print("\t");
  325.             Serial.print(aaReal.y);
  326.             Serial.print("\t");
  327.             Serial.println(aaReal.z);
  328.         #endif
  329.  
  330.         #ifdef OUTPUT_READABLE_WORLDACCEL
  331.             // display initial world-frame acceleration, adjusted to remove gravity
  332.             // and rotated based on known orientation from quaternion
  333.             mpu.dmpGetQuaternion(&q, fifoBuffer);
  334.             mpu.dmpGetAccel(&aa, fifoBuffer);
  335.             mpu.dmpGetGravity(&gravity, &q);
  336.             mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
  337.             mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
  338.             Serial.print("aworld\t");
  339.             Serial.print(aaWorld.x);
  340.             Serial.print("\t");
  341.             Serial.print(aaWorld.y);
  342.             Serial.print("\t");
  343.             Serial.println(aaWorld.z);
  344.         #endif
  345.    
  346.         #ifdef OUTPUT_TEAPOT
  347.             // display quaternion values in InvenSense Teapot demo format:
  348.             teapotPacket[2] = fifoBuffer[0];
  349.             teapotPacket[3] = fifoBuffer[1];
  350.             teapotPacket[4] = fifoBuffer[4];
  351.             teapotPacket[5] = fifoBuffer[5];
  352.             teapotPacket[6] = fifoBuffer[8];
  353.             teapotPacket[7] = fifoBuffer[9];
  354.             teapotPacket[8] = fifoBuffer[12];
  355.             teapotPacket[9] = fifoBuffer[13];
  356.             Serial.write(teapotPacket, 14);
  357.             teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
  358.         #endif
  359.  
  360.         // blink LED to indicate activity
  361.         blinkState = !blinkState;
  362.         digitalWrite(LED_PIN, blinkState);
  363.     }
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement