디시인사이드 갤러리

마이너 갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

[질문] MPU6050 connection 실패

bokdogi(58.224) 2025.07.24 22:00:03
조회 185 추천 0 댓글 4
														
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2019-07-08 - Added Auto Calibration and offset generator
//         - and altered FIFO retrieval sequence to avoid using blocking code
//      2016-04-18 - Eliminated a potential infinite loop
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

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

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

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

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

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

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

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

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

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

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

 * ========================================================================= */



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

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
#define OUTPUT_READABLE_YAWPITCHROLL

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

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

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



#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

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

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

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



// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

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



// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

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

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

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

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

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

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

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

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // Calibration Time: generate offsets and calibrate our MPU6050
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection ( Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt( INTERRUPT_PIN ));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

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

        // get expected DMP packet size for later comparison
        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(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}



// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;
    // read a packet from FIFO
    if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet
        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif
   
        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

여기서 실행하면


24b0d121e09c28a8699fe8b115ef0464df8ee5cb

계속 이렇게 뜹니다 해결방법 있을까요?


추천 비추천

0

고정닉 0

0

원본 첨부파일 1

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 말머리 제목 글쓴이 작성일 조회 추천
- 설문 연말 모임 가는 곳마다 가장 인싸일 것 같은 스타는? 운영자 25/12/08 - -
- AD AI 가전 디지털 모음전 운영자 25/11/27 - -
6547 일반 ESP32 RP2040 계열들 원래 컴파일 속도 이렇게 느림? [4] ㅇㅇ(1.252) 08.24 104 0
6546 질문 아두이노 시작 [1] yyy갤로그로 이동합니다. 08.24 149 0
6544 질문 이런 보드에 핀헤더 박을라면 납땜말곤 없음? [3] 아두갤(121.128) 08.23 142 0
6541 질문 아두이노 오류 질문 [2] ㅇㅇ(121.187) 08.19 87 0
6538 일반 esp32 왜이렇게 뜨거워짐 [12] ㅇㅇ(211.234) 08.15 328 1
6537 질문 리니어슬라이드 [2] 초보(211.185) 08.15 79 0
6535 질문 알리에서 센서 사본 사람 있음? [3] ㅇㅇ(211.235) 08.13 175 0
6533 일반 아두이노레오나르도 c++이랑 호환 어떻게 해 형들? [5] 111111(121.138) 08.12 92 0
6532 일반 키트 사는거 말고 컴퓨터로 시연할 수 있는곳 있음? [2] ㅇㅇ(39.121) 08.12 88 0
6531 일반 우편함 센서 만들고 싶은데 알못이라 제미나이한테 물어봤는데 이거 맞음? [4] ㅇㅇ(14.58) 08.10 172 0
6530 일반 아두이노 ㅈ도 모르는데 [4] ㅇㅇ(118.36) 08.09 252 0
6529 질문 esp32 rf 송수신기 연결 [4] ㅇㅇ(110.35) 08.09 163 0
6528 일반 bldc x 22 [1] zhan갤로그로 이동합니다. 08.09 64 0
6527 질문 bldc 모터 회전x [8] zhan갤로그로 이동합니다. 08.08 116 0
6523 일반 릴레이 모듈이랑 ESP32 mini 좀 그려봤다 [2] ㅇㅇ(183.99) 08.06 105 3
6522 일반 espressif 로고 왜이렇게 어렵냐 [1] ㅇㅇ(183.99) 08.06 86 3
6521 질문 늒네 레오나르도 살리기 가능함? [5] ㅇㅇ갤로그로 이동합니다. 08.05 107 1
6520 질문 esp32-cam 질문점여 [1] ㅇㅇ(121.139) 08.05 105 0
6519 일반 아두이노 외주 견적 [5] ㅇㅇ(168.188) 08.05 119 0
6518 질문 혹시 ESP32 질문 드려도 되나요? [6] 늒네(121.137) 08.02 191 0
6517 일반 그거암? PCB 손톱깎이로도 잘림 [2] b.링크/KQuest갤로그로 이동합니다. 08.01 201 1
6516 질문 초음파센서 40khz짜리 말고 60k이나 100k, 120k짜리는 안팜? [3] ㅇㅇ(1.215) 08.01 70 0
6515 일반 프로젝트로 라즈베리파이 쓰려는데 [5] ㅇㅇ갤로그로 이동합니다. 08.01 151 0
6514 질문 아두이노 무한로딩 ㅇㅇ(211.212) 07.31 80 0
6513 질문 왕초보 gps모듈 질문좀요 [1] 왕초보(1.224) 07.31 74 0
6512 정보 데이터시트 읽는 방법 [2] ㅇㅇ(138.199) 07.30 78 2
6511 질문 센서 확장 쉴드 관련 질문 [2] 콜록(211.169) 07.30 49 1
6510 일반 왜 아두이노 책보면 다 led 키는것만 알려주지 [10] ㅇㅇ갤로그로 이동합니다. 07.30 192 0
6509 일반 여기서 STM32도 취급함? [5] ㅇㅇ갤로그로 이동합니다. 07.28 169 0
6508 일반 전력센서노드 업글 [1] FFrnpeg갤로그로 이동합니다. 07.27 73 2
6507 일반 전기 ㅈ도모르는새끼가 만들어본 자기유지회로 [9] b.링크/KQuest갤로그로 이동합니다. 07.27 420 3
6506 질문 뉴비) 이런거는 어덯게 연결함? [2] ㅇㅇ(221.146) 07.27 135 0
6505 질문 아두이노 1도 모르는데 이런 기계 만들려면 뭘 공부해야하나요 [6] ㅇㅇ(121.128) 07.26 161 0
6504 질문 내가 원하는 기계 만들고싶어사 그런데 아두이노로 입문하면 됨? [10] ㅇㅇ갤로그로 이동합니다. 07.26 216 0
6503 일반 새삼 attiny85가 대단하네 ㅇㅇ(39.123) 07.25 93 2
질문 MPU6050 connection 실패 [4] bokdogi(58.224) 07.24 185 0
6500 일반 아니다 휴일 날 계속 시도해보고 안돠면 단위랑 한글 포기해야겠다 [5] 폭염단계(211.235) 07.23 92 0
6498 일반 코딩 좃버러지인데 아두이노과목 들으면 많이 힘들까요 [2] ㅇㅇ(118.235) 07.23 167 0
6497 질문 아니 질문 [4] 폭염단계(175.120) 07.23 78 0
6496 일반 텍스트 너모 힘들고.... [4] 폭염단계(175.120) 07.23 73 0
6495 일반 아두이노 미사용 소자 싸게팔아요 [3] ㅇㅇ(211.234) 07.23 134 0
6494 질문 아두이노 업로드 할 때 오류 뜨는데 이거 뭐임? [2] ㅇㅇ(39.113) 07.22 81 0
6492 일반 AA 건전지 2개로 밖에 돌아다니며 쓸 플젝 있나 [1] ㅇㅇ(131.186) 07.20 81 0
6491 질문 JLC PCBA 써보신 분 있음? [4] ㅇㅇ(211.234) 07.20 85 0
6490 일반 지피티 처음엔 좋았는데 점점 사람 미치게하는거 같음 [14] 폭염단계(175.120) 07.20 161 0
6489 일반 심심한데 Lora 무선 통신이나 만들까 [4] ㅇㅇ(39.123) 07.19 102 0
6488 질문 4인치 디스플레이 글자크기 질문 [6] ㅇㅇ(175.120) 07.18 118 0
6487 질문 현관문에AA사이즈 배터리 문제 [7] asdf4(182.225) 07.18 96 0
6486 질문 급하게 점퍼케이블 필요한데 서울에 어디 파는 곳 없을까? [11] 후시딘갤로그로 이동합니다. 07.18 308 0
6485 일반 commodore mega 64 [1] asdf4(182.225) 07.17 67 1
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2