이제 오늘하려고 생각한것의 마지막 파트

 

이전글 코드는 ypr 값 값 값

식으로 나왓는데

ypr 지우고 콤마 분할되도록 수정

#include "I2Cdev.h"
#include <SoftwareSerial.h> 

#include "MPU6050_6Axis_MotionApps20.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

#define OUTPUT_READABLE_YAWPITCHROLL


#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' };


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



//RXD3, TXD4
SoftwareSerial BTSerial(4, 3);

void setup() {
    BTSerial.begin(9600);

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    while (!BTSerial); // wait for Leonardo enumeration, others continue immediately

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

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

    // load and configure the DMP
    BTSerial.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) {
        // turn on the DMP, now that it's ready
        BTSerial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        BTSerial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        //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
        BTSerial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        BTSerial.print(F("DMP Initialization failed (code "));
        BTSerial.print(devStatus);
        BTSerial.println(F(")"));
    }
}


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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
    }

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

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

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

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

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

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

 

 

 

 

 

동작은 하긴하는데

송신 속도가 너무 느려서

다음 링크 참고해서 보드레이트 변경 

https://rockjjy.tistory.com/2503

 

Arduino Uno 로 HC-06 블루투스 슬레이브 모듈을 사용해 무선으로 코드 업로드 해보기

Arduino Uno 로 HC-06 블루투스 슬레이브 모듈을 사용해서 무선으로 코드를 업로드 해보는 프로젝트 입니다 Arduino 에 코드를 업로드 하는 가장 기본적인 방법은 USB 데이터 케이블을 사용해서 코드를

rockjjy.tistory.com

 

 

 

115200으로 바꾼뒤 배터리 연결하면

ypr을 제대로 받질 못한다.

pc로 전원주면 정상동작하긴하는데

 

다시 9600으로 낮춘뒤

해도 안되는데

딜레이를 30ms 주면 베터리 연결한 상태에서도 정상적으로 putty에서 볼수 있다.

20ms 딜레이도 안됨.

 

전원 문제는 생각도 못햇는데 골치아프네

값이 정상적으로 받아지다가 중간에 튈때도 많다.

 

송신 문자열에 .이랑 소수점 있으니까 이걸 제거해주면 어떨까

 

보내는게 줄어서인가 아까보단 나은거같기도하고

 

 

putty에선 정상적으로 뜨는데 값이 왜이렇게 튈까 찾아보다가

 

 

 

 

 

 

 

 

ypr빼고  리드 스트링 결과 그대루 출력시 결과

putty완 다르게 꽤 깨지는편

 

 

 

 

 

딜레이 30대신 200정도 줘볼까

느린건 아쉽지만 깨지는건 현저히 줄었다.

 

 

 

 

그리고 고정한 상태에서

y가 65, 5 가  번갈아 들어오는 상황이었는데

푸티로 열어보니 67정도로 계속 들어옴

근데 언리얼 시리얼 플러그인에서 리드 스트링할때 65 의 앞인 6을 잘라서 읽어버림.

 

 

 

 

잘되나 싶었는데 언리얼 시리얼 플러그인에서 막혀버리네

나머진 내일확인해봐야겟다.

 

진행 과정에 있었던 문제 

gpt 문답

Q : 아두이노에 보조베터리로 전원을주고 블루투스모듈과 MPU6050을 아두이노에 연결한 상태에서 블루투스 시리얼 통신을 했어.
아두이노에 delay를 주지않으면 MPU6050으로부터 값을 못가져오는데
delay(100)정도 주면 값을 블루투스로 받아올수 있었어
delay 유무에 따라 왜이러는거야?
그런데 베터리를 안쓰고 PC 전원을 주면 delay를 안써도 정상적으로 보내져
베터리 전원 문제도 있는거야?

 

A : 보조 배터리로 전원을 줄 때와 PC 전원을 사용할 때의 차이는 전원의 안정성과 품질에 기인할 수 있습니다. 보조 배터리는 출력 전압이나 전류의 안정성이 PC USB 포트보다 상대적으로 낮을 수 있고, 이는 전자 부품의 정상 작동에 영향을 줄 수 있습니다.

MPU6050과 블루투스 모듈은 정확한 타이밍과 일정한 전원 공급이 필요한 부품들이므로, 전원 공급이 불안정하면 센서 데이터의 샘플링과 처리가 제대로 이루어지지 않을 수 있습니다. `delay(100)`을 추가함으로써, 센서가 데이터를 처리하고 준비하는데 필요한 시간을 확보하게 되며, 이는 불안정한 전원 상황에서도 데이터를 안정적으로 처리할 수 있는 여유를 제공합니다.

반면 PC USB 포트는 일반적으로 보다 안정적인 전원을 제공합니다. 따라서 전원 불안정이 센서의 데이터 처리에 미치는 영향이 적어, `delay` 없이도 데이터를 정상적으로 처리할 수 있습니다.

전원 문제를 해결하기 위해 다음과 같은 방법을 시도해보실 수 있습니다:

- 보조 배터리의 출력 전압과 전류가 아두이노와 연결된 모듈의 요구 사항을 충족하는지 확인하세요.
- 전원 라인에 전압 조정기나 캐패시터와 같은 필터링 회로를 추가하여 전원 노이즈를 줄이세요.
- 가능하다면, 더 안정적인 전원 공급 장치를 사용하세요.

이러한 조치를 통해 전원 공급 문제를 해결하고, 모든 조건에서 MPU6050과 블루투스 모듈이 안정적으로 작동하도록 할 수 있습니다.

지난번 글에서 mpu6050 1개에서 ypr 뽑아내는걸 했는데

나중에 mpu6050을 10개로 늘리면 어캐하지는 둘째치고..

 

블루투스 모듈 쓰도록 고치려고한다.

 

일단 mpu6050 dmp 코드

#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

#define OUTPUT_READABLE_YAWPITCHROLL


#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' };


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


void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #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

    // 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"));

    // 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) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        //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 {
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

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


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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
    }

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

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

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

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

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

        #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

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

 

지난번에 사용한 블루투스 코드

#include <SoftwareSerial.h> 
//RXD2, TXD3
SoftwareSerial BTSerial(3, 2);

//SoftwareSerial BTSerial(7, 8);             // HC-06모듈 7=TXD , 8=RXD 핀 선언 

void setup()
{
  BTSerial.begin(9600);
}

char ch = 'a';

void loop()
{
  if (BTSerial.available())
  {
    BTSerial.write(ch); // HC-06 모듈로 "A"를 송신
    if (ch == 'z')
      ch = 'a';
    else
      ch++;
  }
  delay(500); // 1초 딜레이
}

 

 

일단

나는 bt할때 rxd2, txd3을 쓰고 있엇는데

mpu6050에서 d2를 인터럽트핀으로 쓰고있다보니

 

bt rxd3, txd4로 변경

이 코드를 위 mpu 6050과 짬뽕해야한다..

#include <SoftwareSerial.h> 
//RXD3, TXD4
SoftwareSerial BTSerial(4, 3);


void setup()
{
  BTSerial.begin(9600);
}

char ch = 'a';

void loop()
{
  if (BTSerial.available())
  {
    BTSerial.write(ch); // HC-06 모듈로 "A"를 송신
    if (ch == 'z')
      ch = 'a';
    else
      ch++;
  }
  delay(500);
}

 

 

 

 

일단 대충 섞음

원랜 시리얼 출력으로 하던부분을 BTSerial 출력하도록 수정

 

#include "I2Cdev.h"
#include <SoftwareSerial.h> 

#include "MPU6050_6Axis_MotionApps20.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

#define OUTPUT_READABLE_YAWPITCHROLL


#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' };


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



//RXD3, TXD4
SoftwareSerial BTSerial(4, 3);

void setup() {
    BTSerial.begin(9600);

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    while (!BTSerial); // wait for Leonardo enumeration, others continue immediately

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

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

    // load and configure the DMP
    BTSerial.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) {
        // turn on the DMP, now that it's ready
        BTSerial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        BTSerial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        //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
        BTSerial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        BTSerial.print(F("DMP Initialization failed (code "));
        BTSerial.print(devStatus);
        BTSerial.println(F(")"));
    }

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


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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
    }

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

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

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

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

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

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

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

 

 

 

 

 

그런데 이 상태로 보조배터리 연결후 putty 켜보니 값이 제대로 안나온다.

딜레이를 안줘서 그런가?

피포 버퍼 오버플로자꾸되서 해당 출력도 제거

#include "I2Cdev.h"
#include <SoftwareSerial.h> 

#include "MPU6050_6Axis_MotionApps20.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

#define OUTPUT_READABLE_YAWPITCHROLL


#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' };


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



//RXD3, TXD4
SoftwareSerial BTSerial(4, 3);

void setup() {
    BTSerial.begin(9600);

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    while (!BTSerial); // wait for Leonardo enumeration, others continue immediately

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

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

    // load and configure the DMP
    BTSerial.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) {
        // turn on the DMP, now that it's ready
        BTSerial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        BTSerial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        //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
        BTSerial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        BTSerial.print(F("DMP Initialization failed (code "));
        BTSerial.print(devStatus);
        BTSerial.println(F(")"));
    }
}


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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
    }

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

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

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

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

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

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

 

 

 

 

지난주 페이스 무너지고 나서 제대로 못하고 있었는데

드뎌 mpu6050 다뤄보려고함

 

기존에 이미 아두이노 mpu6050 사용하는 글들 많은데

무엇을 참고할가..

 

한참 찾은건 아니지만

이 링크에서 데이터 시트 참고해서 설명을 해주고 있고,

https://chigun.tistory.com/20

 

[MPU6050] 1. 데이터 시트를 통해 센서 값 확인하기

구글에 MPU6050 데이터 시트를 검색하면 다음과 같은 파일을 찾을 수 있다. 최상단의 파일은 말 그대로 데이터 시트로 센서에 관한 스펙과 통신 방식, 전력 등에 관한 것을 제조사에서 정리한 것이

chigun.tistory.com

 

이 글에서는 mpu6050 lib로 ypr 를 뽑아내는 예제를 보여준다.

https://m.blog.naver.com/boilmint7/220932352810

 

아두이노 3축자이로센서(MPU-6050)사용 예제설명

아두이노 3축자이로센서(MPU-6050) 사용 예제 설명.     아두이노 자이로센서 (MPU-6050) ...

blog.naver.com

 

 

mpu6050에서 바로 rpy 뽑아내는것도 좋지만

그래도 쓰는데 데이터시트 내용 대충 한번 보긴해야겠지

 

글을 찾아보니 mpu6050을 아두이노 핀 a4, a5에 연결해야한다고하는데

i2c 통신하면 디지털쪽해야하지 않나 싶다가 

이게 우노에서 i2c 통신에 사용되는 핀이라고한다.

https://blog.naver.com/evnngsky/220282372750

 

 

 

 

우노보드 핀맵을 열어보면 a4, a5가 sda, scl이 맞긴하다.

시키는데로 연결하고

 

 

 

 

https://chigun.tistory.com/20

 

[MPU6050] 1. 데이터 시트를 통해 센서 값 확인하기

구글에 MPU6050 데이터 시트를 검색하면 다음과 같은 파일을 찾을 수 있다. 최상단의 파일은 말 그대로 데이터 시트로 센서에 관한 스펙과 통신 방식, 전력 등에 관한 것을 제조사에서 정리한 것이

chigun.tistory.com

 

 

다시 이 링크로 돌아와 글을보는데 정리하면 이런듯

1. 아두이노 i2c 통신을 하려면 wire.h 사용

2. mpu6050 ic2 주소값은 0x68

3. mpu6050 초기화 : 0x68에다가 107, 0 송신 : 107레지스터에 0 전달

 * 초기화 해주면 다시는 안해도됨.

4. 뒷 내용은 각가속도 중력가속도 감도 설정 + 레지스터에서 값가져오기

 

내용은 완벽히 이해하긴 힘들지만

그래도 데이터시트랑 i2c 읽어오는 내용을 꽤 친절하게 설명해주니 이만큼 봐도 충분해보임.

 

 

 

하지만 나는 각가속도, 중력가속도가 아니라 rpy가 필요해서

이제 다른글 보고진행

 

 

하기전에

i2c 주소값이 0x68이면

나는 mpu 6050여러개 쓸건데 어떻게하면 되나 궁금해짐

 

gpt에게 물어봄

q : 아두이노 우노보드에서 mpu6050 2개를 사용하려면 어떻게 작성하면되 mpu6050의 i2c 주소값은 0x68이라고하는데, 두개다 주소가 같은거아니야? 

a : 아뇨, MPU6050 모듈은 I2C 통신을 통해 통신하는데, 주소를 변경하여 같은 버스 상에 여러 개의 모듈을 사용할 수 있습니다. 보통 MPU6050의 기본 주소는 0x68이지만, AD0 핀의 상태에 따라(AD0 핀이 GND에 연결되면 0x68, VCC에 연결되면 0x69) 주소를 변경할 수 있습니다. 두 개의 MPU6050 모듈을 사용할 때, 하나는 0x68 주소로 설정하고 다른 하나는 0x69 주소로 설정하여 충돌을 피할 수 있습니다.

 

q : 그러면 2개가 아니라 mpu6050을 5개 사용하는 경우 어떻게 하면되

a : 만약 MPU6050을 5개 사용하려면, 각각의 모듈에 고유한 I2C 주소를 할당해야 합니다. MPU6050 모듈은 AD0 핀을 통해 주소를 변경할 수 있습니다. AD0 핀을 다른 GPIO 핀에 연결하고 해당 핀을 사용하여 AD0 핀을 제어하여 주소를 변경할 수 있습니다. 예를 들어, 5개의 MPU6050 모듈을 사용하는 경우, 각 모듈에 다른 주소를 할당하기 위해 AD0 핀을 5개의 GPIO 핀에 연결하고, 해당 GPIO 핀을 사용하여 AD0 핀을 제어하여 주소를 변경할 수 있습니다. 이렇게 하면 각 MPU6050 모듈은 고유한 주소를 가지게 됩니다.

 

 

대충 얘 설명이 맞는지는 몰라도 mpu6050에 있는 ad0핀으로 mpu6050 여러개쓸때 고유 주소갖도록 변경할수 있나봄.

 

비트연산으로 값뽑아오는건 여기서 꽤 친절하게 설명해준편

https://steemit.com/kr-arduino/@codingman/mpu-6050

 

MPU-6050 가속도/자이로 센서 제어 (아두이노) — Steemit

MPU-6050 가속도/자이로 센서 제어 (아두이노) 오늘은 MPU-6050 가속도/자이로 센서를 이용하여 실험하는 시간을 갖도록 하겠습니다. 자이로 센서를 사용하려면 오일러의 공식을 알아야 하고 오일러

steemit.com

 

 

 

 

 

 

 

 

 

다시 돌아와 rpy뽑아내는 링크 참고

https://m.blog.naver.com/boilmint7/220932352810

 

 

아두이노 3축자이로센서(MPU-6050)사용 예제설명

아두이노 3축자이로센서(MPU-6050) 사용 예제 설명.     아두이노 자이로센서 (MPU-6050) ...

blog.naver.com

 

 

 

근데 위 글에서는 INT 핀을 D2와 연결해야된다고 한다.

gpt 한태 물어봄

q : 아두이노 우노보드 mpu6050 사용하는 글 찾아봤는데 INT핀을 D2와 연결시키던데 이건왜하는거야? SCL, SDA만 연결해도 되지않아?

a : INT 핀을 D2에 연결하는 이유는 MPU6050의 인터럽트 기능을 사용하기 위함입니다. 이를 통해 특정 조건이 충족되었을 때 인터럽트를 발생시키고 처리할 수 있습니다. SCL과 SDA는 데이터 통신을 위한 핀이며, INT 핀은 MPU6050의 상태를 감지하고 처리하는 데 사용됩니다. 따라서 INT 핀을 D2와 연결하여 MPU6050의 인터럽트를 사용할 수 있습니다.

 

제대로 찾아본건 아니지만 국내 블로그 글에서는 int핀을 사용하는 이유를 제대로 설명하진 않고있다.

mpu6050 라이브러리에서 쓰나보지 싶어 그냥 나는 D4에 연결

(블루투스로 D2,D3 쓰고있기 때문)

 

 

 

이 글에서 시키는데로 라이브러리 다운받으려고하는데

첨부파일 다운이안된다.

 

대신 여기서 다운받아 사용

https://bella1130.tistory.com/35

 

[17] 자이로 센서(MPU 6050)

자이로센서의 움직임을 시각적으로 보여주는 processing이라는 툴을 사용해 보도록 하겠습니다. ​ 아두이노, 자이로센서의 연결은 다음과 같습니다. 여기에서 실행할 프로그램은 arduino의 인터럽

bella1130.tistory.com

 

 

 

원 블로그글 링크대로가면

C:\Program Files (x86)\Arduino\libraries

여기가면 된다는데

나는 아두이노 라이브러리가 

앱데이터 로컬쪽에 가있더라.

C:\Users\jdo\AppData\Local\Arduino15\libraries

 

 

 

 

근데 여기다 추가하고 아두이노 ide를 열어도 예제가 추가되질 않는다.

아무 예제나 열어서 폴더 열기해보니까

임시폴더에 들어가있더라

 

 

 

그냥 아쉬운데로 mpu6050 내 dmp 예제 열어봣는데

 

// 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:
//      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:

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



// 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
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#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
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#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 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();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #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 Ardunio
    // 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();

    // 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) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, 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;

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

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

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

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

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

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

        #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);
    }
}

 

 

일단 아두이노ide example에서 보이지는않지만

빌드는 정상적으로 된다.

그런데 위 코드에서 인터럽트핀을  내가 D2가 아닌 D4를 써서 좀바꿔주고 싶은데

어디있는지 잘안보인다.

 

 

 

일단 필요한 lib 가져오고

i2c 통신 설정하는 내용이 앞에나온다.

 

// 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

 

 

근데 다음 내용이 문제다.

인터럽트 핀을 우노보드에서 d2로 연결해야한다고 하는데

나는 d4를 쓴다.

/* =========================================================================
   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.
 * ========================================================================= */

 

 

일단 gpt 한태 질문

q : 아두이노 우노보드 mpu6050 사용하는데 INT핀을 우노보드의 D2에다가 연결하라고 해 다른 핀을 사용하면 안될까?

a : 다른 핀을 사용할 수도 있지만, MPU6050의 INT 핀은 보통 D2 핀에 연결하는 것을 권장합니다. 이는 MPU6050 라이브러리와 관련된 코드가 기본적으로 D2 핀을 사용하기 때문입니다. 만약 다른 핀을 사용하려면 해당 핀의 인터럽트 기능을 사용할 수 있는지 확인하고, 코드를 수정하여 새로운 핀을 사용하도록 설정해야 합니다.

 

 

q : 그러면 mpu6050 여러개 사용하는 경우 int핀들을 전부 d2와 연결해야되??

a : MPU6050 여러 개를 사용하는 경우, 각 MPU6050의 INT 핀을 모두 하나의 핀(D2)에 연결할 필요는 없습니다. 각 MPU6050의 INT 핀을 서로 다른 디지털 핀에 연결하여 각각의 MPU6050의 인터럽트 신호를 처리할 수 있습니다. 따라서 각 MPU6050 모듈의 INT 핀을 서로 다른 디지털 핀에 연결하여 사용하면 됩니다.

 

q : 그러면 나는 mpu6050 인터럽트핀을 우노보드 d4에 연결해서 사용하면 mpu6050 헤더파일은 변경하면되는거야? 어떻게 고치면되?

a : 네, MPU6050의 INT 핀을 우노보드의 D4에 연결한 경우 MPU6050 라이브러리의 헤더 파일을 수정하여 해당 핀을 사용하도록 변경해야 합니다. 
라이브러리의 소스 코드를 열어 해당 핀을 수정하거나, 라이브러리의 설정 파일에서 해당 핀을 재정의할 수 있습니다. 보통 라이브러리에는 핀 매핑에 대한 설정이 있으므로 해당 설정을 변경하여 INT 핀을 D4로 사용할 수 있습니다. 
핀 매핑 설정을 찾아 해당 핀을 D4로 수정하고, 라이브러리를 다시 컴파일하여 사용하면 MPU6050의 INT 핀을 D4에 연결하여 정상적으로 사용할 수 있습니다.

 

 

 

gpt 설명만 보면 mpu 6050 여러개 쓰면 int핀도 따로해줘야한다고 하는데 

int를 안써도 되나 싶어서 찾아보다

발견한 글 여기서는 결론은 인터럽트 핀은 옵션이란다.

 

 

https://arduino.stackexchange.com/questions/44937/how-important-is-the-int-pin-of-the-mpu6050-gy-521

 

How important is the INT pin of the MPU6050 (GY-521)?

I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking

arduino.stackexchange.com

 

다시 gpt 질문

q : mpu 6050에서 인터럽트핀이 언제사용되 우노보드랑 연결해서쓰려고해

a : MPU6050의 인터럽트 핀은 다양한 용도로 사용될 수 있습니다. 일반적으로 MPU6050에서 인터럽트 핀은 다음과 같은 상황에서 사용됩니다:

1. Motion Detection(동작 감지): MPU6050은 움직임을 감지하는 기능을 제공합니다. 인터럽트 핀을 사용하여 특정 동작이 감지되었을 때, 우노보드에 인터럽트 신호를 보내고 처리할 수 있습니다.

2. Freefall Detection(자유 낙하 감지): MPU6050은 자유 낙하를 감지할 수 있는 기능도 제공합니다. 인터럽트 핀을 사용하여 자유 낙하 감지 시 우노보드에 알림을 보낼 수 있습니다.

3. Orientation Tracking(자세 추적): MPU6050은 자세 추적을 위한 기능도 갖추고 있습니다. 인터럽트 핀을 사용하여 특정 자세 조건이 충족되었을 때, 우노보드에 인터럽트를 발생시키고 처리할 수 있습니다.

따라서, MPU6050의 인터럽트 핀을 우노보드와 연결하여 사용하면 이러한 기능들을 활용할 수 있습니다. 사용하고자 하는 기능에 따라 MPU6050 라이브러리와 우노보드 코드를 적절하게 설정 및 프로그래밍해야 합니다.

 

 

 

이 내용만 보면 인터럽트 쓰긴해야될것같은데

다른글 찾아봄

 

 

 

 

 

 

이 글에서 설명하는 예제가 2가지가 있는데

첫 예제에서는 INT핀안쓰고

둘째 예제에서는 INT핀 사용

 

 

 

https://www.jkelec.co.kr/img/sensors/manual/mpu6050_gy521/mpu6050_gy521_manual.html

 

MPU6050 GY-521 센서 메뉴얼

  1. MPU6050 센서 소개 MPU6050은 가속도와 자이로센서가 1개의 센서에 모두 포함하고 있는 6DOF(Degrees of Freedom) 센서이다. MPU6050은 I2C (Inter Integrated Circuit) 통신 프로토콜을 통해서 데이터를 추출 할

www.jkelec.co.kr

 

 

그런데 둘째 예재를 보면 인터럽트 핀을 지정하는 내용이 나온다.

 

 

 

내가 다운받은 예제 코드랑 여기서 설명하는 예제비교해보자

거의 비슷하긴한데 우측코드는

 attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);

 

 좌측코드는 

        attachInterrupt(0, dmpDataReady, RISING);
 


약간 차이난다.

 

 

 

 

일단 mpu6050 여러개 받아오는건 나중에 생각하고

내가 갖고 있는 예제코드만 인터럽트핀 D4로 바꿔서 동작하도록 고침

 

변경된건 인터럽트핀 정의해서

어태치 인터럽트한것정도?

 

#define INTERRUPT_PIN 4 // use pin 2 on Arduino Uno & most boards
void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #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 Ardunio
    // 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) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        //attachInterrupt(0, dmpDataReady, RISING);
        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);
}

 

 

업로드 했지만 동작이 안된다

DMP ready! Waiting for first interrupt...
 
 
 

원래대로 고치고 핀도 d2로 옮기니 정상동작 확인

어카지 인터럽트핀 여러개해야하는데

 

 

근데 코드안고치고 인터럽트핀 아얘 뽑아도 정상적으로 동작한다.

괜한 걱정한듯

하지만 초기화 부분에서 자꾸 멈춰서 주석처리시켜줘야할듯

 

 

 

근대 실행시키고나서 보면 yaw가 계속 누적되서 커지다가 어느순간 멈춘다.

ok 기존 코드는 너무 길어서 

주석이나 몇가지 부분들을 빼서 조금 줄임

일단. 인터럽트 핀 안쓰고 ypr 받아오도록 정리

 

#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

#define OUTPUT_READABLE_YAWPITCHROLL



#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' };


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


void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #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

    // 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) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        //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);
}


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

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
    }

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

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

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

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

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

        #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

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

 

 

 

촬영 결과

대충 되긴한다

프레임은 줄인다고 22뿐인데 이미지가 커서 용량이꽤되네

2~3달간 언리얼 공부하면서 프로젝트 발표했던것들이 있어

여기에 링크 남긴다.

 

1차프로젝트 기획 - 손검출을이용한 자동차시뮬레이터

https://docs.google.com/presentation/d/1c_5qoX-Va1VqvE6wc0jZqaYnp4DzvrmP/edit#slide=id.p1

1차프로젝트 프로토타입 - 손검출을이용한 자동차시뮬레이터

https://docs.google.com/presentation/d/1LW0pUNbyc7b5z3Wp8OHd9OvmSf9EkkGR/edit#slide=id.p1

1차프로젝트 알파 - 손검출을이용한 자동차시뮬레이터

https://docs.google.com/presentation/d/1WS2-zUlpS_MkMcmRUssAwGekLn9cIfnP/edit#slide=id.p1

1차프로젝트 베타 - 손검출을이용한 자동차시뮬레이터

https://docs.google.com/presentation/d/1PsUrccbHe4Myl8WK3wAMrnlad7Db2SBl/edit#slide=id.p1

 

 

2차프로젝트 기획 - 버추얼 피아노

https://docs.google.com/presentation/d/1GVN8IPpeQm4J18yRnm5Fh2AIEu4S9xjA/edit#slide=id.p1

2차프로젝트 프로토타입 - 버추얼 피아노

https://docs.google.com/presentation/d/1bkyBLjFY6aWnxru6j455r26aSTKrrahf/edit#slide=id.p1

2차프로젝트 프로토타입 - 버추얼 칼림바

https://docs.google.com/presentation/d/1ajEUDPyJJkSeywkgIDZRUJMIftPbPQJ0/edit#slide=id.p1

 

원래 버추얼 피아노를 하려했다가 손 잡기 문제가 있어 데스크탑으로 변경

 

2차프로젝트 알파 - 버추얼 데스크탑

https://docs.google.com/presentation/d/1eqiJEY-xM-Y5gBGS7s-QilQf6SxJkxAs/edit#slide=id.p1

2차프로젝트 베타 - 버추얼 데스크탑

https://docs.google.com/presentation/d/1_Vrt8yKb-K48xkh1Iu9uwGp3V7cAMx4Q/edit#slide=id.p1

 

 

 

3차프로젝트 기획 - 관성 자세

https://docs.google.com/presentation/d/1YyUrZmpN605Wa3vn5tbPP9gpS3zDR_MF/edit#slide=id.p1

 

 

 

 

 

 

이번엔 지난번에 찾은 시리얼 통신 플러그인 쓰려고하는데,

 

 

 

대충 기본맵 만들고

 

 

 

 

게임모드 베이스 만들고

 

 

블루투스게임모드베이스 bp 생성

 

 

 

기본 게임모드, 맵설정

 

 

 

 

이제 시리얼 플러그인 써야되는데

 

지난번에 찾은 플러그인에보면 언리얼 버전별로 여러개 있음.

https://github.com/videofeedback/Unreal_Engine_SerialCOM_Plugin/tree/main

 

 

 

내가쓰는 언리얼은 5.3.2므로 맞는거 다운

 

 

 

 

 

 

프로젝트 폴더에

Plugins 폴더 만들고

다운로드 받은 플러그인 압축해제해서 옮기기

 

 

 

이 상태에서 껏다키면

플러그인에 내가 추가한 플러그인이 등록된걸 볼수 있음.

 

 

 

 

이 플러그인에서 제공하는거 뭐가있나 보려고 확인

 

 

 

 

우클릭 하면 open serial port가 있는거 확인

 

 

 

 

 

 

open serial port는 serial com object 리턴하는데

이 객체에서 나머지 필요한 기능들 제공.

 

 

 

 

이렇게 하면

아까 1초간격으로 A출력하긴했는데

다음에 다시 실행할땐 시리얼 포트가 열리지 않아서 실행이 안된다.

 

이전 실행때 시리얼 포트 열어놓고 안닫았기 때문인듯

 

 

 

몰랐는데 event end play를 하면 꺼질때 호출할수 있을듯

 

이렇게 게임끝날떄 클로즈 시켜주면

여러번 껏다켜도 정상적으로 블루투스로부터 A를 받아 출력함

 

 

 

관성 모션 이제 시작

일정은 이런식으로 정리

 

 

 

 

일단 HW는 이런식으로 준비

우노 - 블루투스-MPU6050

 

 

아두이노 오랜만에 하니 먼저 블링크 예제부터 테스트

블링크 업로드가 안되던데, 전에 내부 클럭 제네레이터 쓰도록 부트로더 수정했던 우노보드같음

교체하니 정상적으로 블링크 동작 확인

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(1000);                      // wait for a second
  digitalWrite(LED_BUILTIN, LOW);   // turn the LED off by making the voltage LOW
  delay(1000);                      // wait for a second
}

 

 

 

 

블루투스 통신 테스트는 다음 링크 참고하여 진행

https://blog.naver.com/boilmint7/221900933326

 

아두이노 HC-06 블루투스 2.0 모듈 사용 예제

이번에 함께 다룰 아두이노 부품은 HC-06 블루투스 2.0 모듈 입니다. 아두이노는 유선통신인 시리얼(Ser...

blog.naver.com

 

 

 

#include <SoftwareSerial.h> 
//RXD2, TXD3
SoftwareSerial BTSerial(3, 2);

//SoftwareSerial BTSerial(7, 8);             // HC-06모듈 7=TXD , 8=RXD 핀 선언 

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
}

void loop()
{
  if(BTSerial.available())
    Serial.write(BTSerial.read());
  if(Serial.available())
    BTSerial.write(Serial.read());
}

 

 

 

내 HC-06 블루투스 모듈은

이름 그대로 안나오고 Arduino로 나와서 잠깐해매긴했지만

 

안드로이드 폰을 통해서 정상적으로 동작확인

 

 

 

 

 

 

 

이번에 블루투스모듈-PC간 시리얼 통신 확인

윈도우 피시에서 블루투스 모듈 연결시키고

 

 

 

 

 

지난번 글 참고해서

추가 블루투스 옵션으로 들어와

COM포트 확인해보니

COM7, COM8 사용함을 확인함.

 

 

 

 

 

 

 

윈도우pc-블루투스 모듈간 통신 하는걸 확인하다 찾은글

 

https://blog.naver.com/winkck/221090944749

 

[12] 아두이노 블루투스 통신하기

아두이노 보드에 블루투스 모듈(HC-06)을 연결하여 컴퓨터와 통신을 해보도록 하겠습니다. 시리얼 터미널...

blog.naver.com

 

 

 

이 글 참고해서

putty로 com8포트 열면

깜빡이던 BT모듈이 안깜빡이고 계속 불켜진상태로 유지

 

 

 

 

 

키보드 입력하면 com8 화면에는 아무것도 안나오지만

 

 

그대로 켜둔 시리얼모니터 상에는 내가 입력한 키가 나온다.

 

 

 

 

 

 

이번엔 반대로

PUTTY -> HC-06이 아니라

HC-06 -> PUTTY로 해보기

 

 

블루투스 모듈로 A를 1초간격 보내는 코드

#include <SoftwareSerial.h> 
//RXD2, TXD3
SoftwareSerial BTSerial(3, 2);

//SoftwareSerial BTSerial(7, 8);             // HC-06모듈 7=TXD , 8=RXD 핀 선언 

void setup()
{
  BTSerial.begin(9600);
}

void loop()
{
  if (BTSerial.available())
  {
    BTSerial.write('A'); // HC-06 모듈로 "A"를 송신
  }
  delay(1000); // 1초 딜레이
}

 

 

푸티를 열면

BT에서 송신하는 값이 정상적으로 돌아온다.

 

 

 

 

 

 

 

VR 폰 손 카메라뿐

VR 캐릭터 - 몸을 다룰려고

 

Actor, Pawn, Character

- AActor : TF갖고 있어, 월드(레벨)에 배치가 가능

- APawn : 사용자 입력 받음

- ACharacter : 동작(걷기, 뛰기, 점프, 비행 등), 애니메이션

 

 

VRPawn, VRCharacter 차이

- USceneComponent 대신 UCapsuleComponent

- USkeletalMesh Component 추가

 

 

 

 

 

VRPlayer 만들기

Acharacter 상속

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "VRPlayer.generated.h"

UCLASS()
class KDT_VR_API AVRPlayer : public ACharacter
{
	GENERATED_BODY()

public:
	// Sets default values for this character's properties
	AVRPlayer();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


	UPROPERTY(VisibleAnywhere, Category="MySettings|Components")
	class UCameraComponent* cameraComp;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UStaticMeshComponent* headMesh;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UMotionControllerComponent* leftMotion;
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UMotionControllerComponent* rightMotion;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class USkeletalMeshComponent* leftHand;
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class USkeletalMeshComponent* rightHand;




};

 

 

// Fill out your copyright notice in the Description page of Project Settings.


#include "VRPlayer.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SkeletalMeshComponent.h"
#include "Camera/CameraComponent.h"
#include "MotionControllerComponent.h"


// Sets default values
AVRPlayer::AVRPlayer()
{
 	// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	cameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
	cameraComp->SetupAttachment(RootComponent);

	headMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HeadMesh"));
	headMesh->SetupAttachment(cameraComp);

	leftMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Left Motion Controller"));
	leftMotion->SetupAttachment(RootComponent);
	leftMotion->MotionSource = FName("Left");

	leftHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Left Hand Mesh"));
	leftHand->SetupAttachment(leftMotion);
	leftHand->SetRelativeRotation(FRotator(0, 0, 90));

	rightMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Right Motion Controller"));
	rightMotion->SetupAttachment(RootComponent);
	rightMotion->MotionSource = FName("Right");

	rightHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Right Hand Mesh"));
	rightHand->SetupAttachment(rightMotion);
	rightHand->SetRelativeRotation(FRotator(0, 0, 90));


}

// Called when the game starts or when spawned
void AVRPlayer::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AVRPlayer::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

// Called to bind functionality to input
void AVRPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

}

 

 

 

head mesh 설정

 

 

 

헤드셋 쓴상태에선 로그보기 힘듬

 

왼쪽손 로그는 왼쪽위

 

로그를 매시로 띄울수 있음

UTextRenderComponent

 

 

 

 

 

 

 

 

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "VRPlayer.generated.h"

UCLASS()
class KDT_VR_API AVRPlayer : public ACharacter
{
	GENERATED_BODY()

public:
	// Sets default values for this character's properties
	AVRPlayer();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;


	UPROPERTY(VisibleAnywhere, Category="MySettings|Components")
	class UCameraComponent* cameraComp;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UStaticMeshComponent* headMesh;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UMotionControllerComponent* leftMotion;
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UMotionControllerComponent* rightMotion;

	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class USkeletalMeshComponent* leftHand;
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class USkeletalMeshComponent* rightHand;

	
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UTextRenderComponent* leftLog;
	UPROPERTY(VisibleAnywhere, Category = "MySettings|Components")
	class UTextRenderComponent* rightLog;


};

 

// Fill out your copyright notice in the Description page of Project Settings.


#include "VRPlayer.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SkeletalMeshComponent.h"
#include "Camera/CameraComponent.h"
#include "MotionControllerComponent.h"
#include "Components/TextRenderComponent.h"

// Sets default values
AVRPlayer::AVRPlayer()
{
 	// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	cameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
	cameraComp->SetupAttachment(RootComponent);

	headMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HeadMesh"));
	headMesh->SetupAttachment(cameraComp);

	leftMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Left Motion Controller"));
	leftMotion->SetupAttachment(RootComponent);
	leftMotion->MotionSource = FName("Left");

	leftHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Left Hand Mesh"));
	leftHand->SetupAttachment(leftMotion);
	leftHand->SetRelativeRotation(FRotator(0, 0, 90));

	rightMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Right Motion Controller"));
	rightMotion->SetupAttachment(RootComponent);
	rightMotion->MotionSource = FName("Right");

	rightHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Right Hand Mesh"));
	rightHand->SetupAttachment(rightMotion);
	rightHand->SetRelativeRotation(FRotator(0, 0, 90));

	leftLog = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Left Log"));
	leftLog->SetupAttachment(leftMotion);
	rightLog = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Right Log"));
	rightLog->SetupAttachment(rightMotion);

 

 

 

 

 

 

텍스트수정가능

근데 텍스트가 카메라와 같은 방향

 

손목위치 기준 

 

 

 

 

 

yaw 180도 뒤집을때

 

 

 

 

 

 

 

모션을 옆으로보냄

 

 

 

 

 

 

 

 

 

 

 

 

 

손위치 조정

 

 

 

 

 

 

 

이벤트 추가

 

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "VRPlayer.generated.h"


	UPROPERTY(EditAnywhere, Category = "MySettings|Inputs")
	class UInputMappingContext* vrMapping;
	UPROPERTY(EditAnywhere, Category="MySettings|Inputs")
	class UInputAction* rightTriggerTouch;

private:
	//트리거 함수, 델리게이터 형식
	void RightTriggerTouch(const FInputActionValue& val);

};

 

 

// Called to bind functionality to input
void AVRPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	UEnhancedInputComponent* enhancedInputCopmonent = Cast<UEnhancedInputComponent>(PlayerInputComponent);

	if (enhancedInputCopmonent != nullptr)
	{
		//enhancedInputCopmonent->BindAction();
	}
}


void AVRPlayer::RightTriggerTouch(const FInputActionValue& val)
{


}

 

 

 

언리얼 델리게이터, 시그니처, 바인딩


1. 델리게이터 (Delegate):
   - 델리게이터는 이벤트를 선언하고 호출하기 위한 개체입니다.
   - 다른 함수들을 여러 개 등록하고, 이벤트가 발생할 때 등록된 함수들을 호출할 수 있습니다.
   - 예를 들어, 특정 상황에 대한 이벤트가 발생할 때, 여러 함수들이 실행되어야 할 때 유용하게 사용됩니다.

2. 시그니처 (Signature):
   - 시그니처는 델리게이터에 등록되는 함수의 형식을 정의하는 것입니다.
   - 함수의 매개변수와 반환 값의 형식을 지정하여 델리게이터와 함수가 상호작용할 수 있도록 합니다.
   - 예를 들어, 함수가 인자로 정수를 받고, 부울 값을 반환하는 경우 시그니처는 "(int32, bool)"와 같이 정의됩니다.

3. 바인딩 (Binding):
   - 바인딩은 델리게이터와 함수를 연결하는 과정입니다.
   - 델리게이터에 함수를 바인딩하여 이벤트가 발생할 때 해당 함수가 호출되도록 설정합니다.
   - 바인딩은 런타임 중에 동적으로 수행될 수도 있고, 블루프린트나 C++ 코드에서 정적으로 구현될 수도 있습니다.

 

 

UInputMappingContext, UInputAction

- UInputMappingContext와 UInputAction은 언리얼 엔진에서 입력 매핑과 관련된 중요한 클래스입니다. 

1. UInputMappingContext:
   - UInputMappingContext는 입력 매핑을 그룹화하고 관리하기 위한 클래스입니다.
   - 게임 내에서 특정 상황 또는 컨텍스트에서 사용되는 입력 매핑을 정의하고 관리할 수 있습니다.
   - 예를 들어, "게임 플레이"와 "메뉴"라는 두 가지 컨텍스트에서 서로 다른 입력 매핑을 정의하고 관리할 수 있습니다.
   - UInputMappingContext를 사용하여 특정 컨텍스트에 대한 입력 처리 규칙을 설정하고, 해당 컨텍스트에서 사용되는 UInputAction들을 관리할 수 있습니다.

2. UInputAction:
   - UInputAction은 사용자의 입력에 대한 액션을 정의하는 클래스입니다.
   - 키보드, 마우스, 게임패드 등 다양한 입력 장치로부터의 입력을 처리할 수 있습니다.
   - UInputMappingContext 내에서 사용되며, 특정 입력에 대한 액션을 정의하고 해당 액션을 처리하는 함수를 바인딩할 수 있습니다.
   - 예를 들어, "점프"라는 UInputAction을 정의하여 특정 키 또는 버튼 입력에 대한 점프 동작을 처리할 수 있습니다.

 

InputMappincSubsystem에 대해

// InputMapping Context 파일을 입력 서브시스템에 등록하는 
// 베이스 시스템, 기기별로 다른부분은 서브시스템으로
// 인풋맵핑 컨텍스트를 연결하는 이유는 여러종류로 만들어서 쓸수있도록 하기위함.
// 이전엔 입력체계를 프로젝트 세팅즈에서 해서 런타임중에 바꿀수 없어씅나
// 지금은 인풋맵핑컨텍스트 파일을 따로만들어서 런타임중에 변경 가능하도록 수정됨.
// 캐릭터때 조작법, 차 탔을때 조작법이 바뀐다. => 맵핑 컨텍스트를 변경시켜 구현

 

 

 

 

 

언리얼 인풋시스템에 대해 찾아보다가 잘 정리한 글 찾아서 캡처

 

https://upbo.tistory.com/141

 

 

 

 

 

 

 

 

 

 

 

Input폴더에 다음과 같이 추가

우클릭-input에

inputAction과 inputMappingContext 존재

 

 

 

 

IA_RightIndexTrigger_Touch 벨류는 bool

 

IA_RightIndexTrigger_Press 벨류는 bool

 

IA_RightIndexTrigger_Value의 벨류는 float (눌림정도

 

 

 

IMC_MyVRInputMap은

IA_RightIndexTrigger_Touch/Press/Value 추가

각각 oculus touch trigger 설정

 

 

 

 

VR인풋 파일을 PMI_VRTemplate로 프로젝트 셋팅즈에서 설정

 

 

PMI_VRTemplate는 여기애

 

 

 

 

 

여기서 IMC_MyVRInputMap 추가

 

 

 

 

 

VR플레이어 헤더파일에 인풋맵핑콘택스트, 액션, 바인딩함수 추가

 

	UPROPERTY(EditAnywhere, Category = "MySettings|Inputs")
	class UInputMappingContext* vrMapping;
	UPROPERTY(EditAnywhere, Category="MySettings|Inputs")
	class UInputAction* rightTriggerTouch;
	UPROPERTY(EditAnywhere, Category = "MySettings|Inputs")
	class UInputAction* rightTriggerPress;
	UPROPERTY(EditAnywhere, Category = "MySettings|Inputs")
	class UInputAction* rightTriggerValue;

private:
	//트리거 함수, 델리게이터 형식
	void RightTriggerTouch(const FInputActionValue& val);
	void RightTriggerPress(const FInputActionValue& val);
	void RightTriggerValue(const FInputActionValue& val);

 

 

 

 

비긴플레이에

플레이어 컨트롤러로부터 컨트롤러 가져와서 vrMapping 등록

뒤에 셋업플레이어인풋컴포넌트에서 바인딩 액션 정리

 

 

// Fill out your copyright notice in the Description page of Project Settings.


#include "VRPlayer.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SkeletalMeshComponent.h"
#include "Camera/CameraComponent.h"
#include "MotionControllerComponent.h"
#include "Components/TextRenderComponent.h"

#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"

// Sets default values
AVRPlayer::AVRPlayer()
{
 	// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	cameraComp = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComp"));
	cameraComp->SetupAttachment(RootComponent);

	headMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HeadMesh"));
	headMesh->SetupAttachment(cameraComp);

	leftMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Left Motion Controller"));
	leftMotion->SetupAttachment(RootComponent);
	leftMotion->MotionSource = FName("Left");

	leftHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Left Hand Mesh"));
	leftHand->SetupAttachment(leftMotion);
	leftHand->SetRelativeRotation(FRotator(0, 0, 90));

	rightMotion = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("Right Motion Controller"));
	rightMotion->SetupAttachment(RootComponent);
	rightMotion->MotionSource = FName("Right");

	rightHand = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Right Hand Mesh"));
	rightHand->SetupAttachment(rightMotion);
	rightHand->SetRelativeRotation(FRotator(0, 0, 90));

	leftLog = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Left Log"));
	leftLog->SetupAttachment(leftMotion);
	leftLog->SetRelativeLocation(FVector(20, 0, 0));
	//									피치 요, 롤
	leftLog->SetRelativeRotation(FRotator(90, 180, 0));
	leftLog->SetHorizontalAlignment(EHTA_Center);
	leftLog->SetVerticalAlignment(EVRTA_TextCenter);
	leftLog->SetWorldSize(20);
	leftLog->SetTextRenderColor(FColor::Yellow);

	rightLog = CreateDefaultSubobject<UTextRenderComponent>(TEXT("Right Log"));
	rightLog->SetupAttachment(rightMotion);
	rightLog->SetRelativeRotation(FRotator(90, 180, 0));
	rightLog->SetHorizontalAlignment(EHTA_Center);
	rightLog->SetVerticalAlignment(EVRTA_TextCenter);
	rightLog->SetWorldSize(20);
	rightLog->SetTextRenderColor(FColor::Yellow);
}

// Called when the game starts or when spawned
void AVRPlayer::BeginPlay()
{
	Super::BeginPlay();

	// InputMapping Context 파일을 입력 서브시스템에 등록하는 
	// 베이스 시스템, 기기별로 다른부분은 서브시스템으로
	// 인풋맵핑 컨텍스트를 연결하는 이유는 여러종류로 만들어서 쓸수있도록 하기위함.
	// 이전엔 입력체계를 프로젝트 세팅즈에서 해서 런타임중에 바꿀수 없어씅나
	// 지금은 인풋맵핑컨텍스트 파일을 따로만들어서 런타임중에 변경 가능하도록 수정됨.
	// 캐릭터때 조작법, 차 탔을때 조작법이 바뀐다. => 맵핑 컨텍스트를 변경시켜 구현

	// 입력 서브시스템을 갖고 있는것 - 플레이어 컨트롤러 
	// 플레이어 컨트롤러로부터 입력 서브시스템을 가져옴. getSubsystem() 함수 있음 누구로부터가져올


	//InputMapping Context 파일을 입력 서브시스템에 등록하는 절차 진행
	APlayerController* pc = GetController<APlayerController>();

	if (pc != nullptr)
	{

		UEnhancedInputLocalPlayerSubsystem* subsys = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>
			(pc->GetLocalPlayer());
		subsys->AddMappingContext(vrMapping, 0);

	}

}

// Called every frame
void AVRPlayer::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

// Called to bind functionality to input
void AVRPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	UEnhancedInputComponent* enhancedInputCopmonent = Cast<UEnhancedInputComponent>(PlayerInputComponent);

	if (enhancedInputCopmonent != nullptr)
	{
		// 입력 컴포넌트에 RightTriggerTouch() 함수 연결. (손댔을때, 손땟을때도)
		enhancedInputCopmonent->BindAction(rightTriggerTouch, ETriggerEvent::Started, this, &AVRPlayer::RightTriggerTouch);
		enhancedInputCopmonent->BindAction(rightTriggerTouch, ETriggerEvent::Completed, this, &AVRPlayer::RightTriggerTouch);


		enhancedInputCopmonent->BindAction(rightTriggerPress, ETriggerEvent::Started, this, &AVRPlayer::RightTriggerPress);
		enhancedInputCopmonent->BindAction(rightTriggerPress, ETriggerEvent::Completed, this, &AVRPlayer::RightTriggerPress);
		
		enhancedInputCopmonent->BindAction(rightTriggerValue, ETriggerEvent::Triggered, this, &AVRPlayer::RightTriggerValue);


	}


}


void AVRPlayer::RightTriggerTouch(const FInputActionValue& val)
{
	FString result = val.Get<bool>() == true ? FString("True") : FString("False");
	rightLog->SetText(FText::FromString(FString::Printf(TEXT("Right index touch : %s"), *result)));

}

void AVRPlayer::RightTriggerPress(const FInputActionValue& val)
{
	FString result = val.Get<bool>() == true ? FString("True") : FString("False");
	rightLog->SetText(FText::FromString(FString::Printf(TEXT("Right index pressed : %s"), *result)));
}

void AVRPlayer::RightTriggerValue(const FInputActionValue& val)
{
	float pressed = val.Get<float>();
	rightLog->SetText(FText::FromString(FString::Printf(TEXT("Right index Value : %.3f"), pressed)));
}

 

 

 

마지막으로 VR 플레이어에 액션들 등록

 

결과물

 

 

 

 

일단 지난번에 블라즈 핸드 + 윈API +가상 모니터 드라이버로 손으로 제어하는 가상 데스크탑을 만듬

이번에 진행할 목표는

관성센서를 이용한 모션 추론을 해보려고함.

 

이를 블루투스 통신으로 시도할 예정이라 먼저

블루투스 관련 자료들을 찾아봄

 

 

 

 

블루투스 통신 관련 자료찾다가 

언리얼엔진에서 블루투스 통신하는건 못찾았지만

대신 시리얼통신 플러그인 찾음

 

https://github.com/videofeedback/Unreal_Engine_SerialCOM_Plugin

 

GitHub - videofeedback/Unreal_Engine_SerialCOM_Plugin: Serial Com Port Library for Unreal Engine 4 and Unreal Engine 5

Serial Com Port Library for Unreal Engine 4 and Unreal Engine 5 - videofeedback/Unreal_Engine_SerialCOM_Plugin

github.com

 

 

 

 

 

 

블루투스, 시리얼 통신에 대해서 전혀 모르지만

블루투스 송신한걸 시리얼 통신으로 받을수 있는것 같아보이긴해서

 

esp32로 오일러각 송신시켜서 이걸로 받는 식으로 해볼수 있을듯함.

 

 

 

이 영상에서 스마트폰, 윈도우 블루투스 시리얼 통신 조금 찾아봄

 

https://www.youtube.com/watch?v=xruXQ3T7E9o

 

 

장치 관리자 블루투스쪽에는 컴포트가 안나오는데

 

포트에 보면 블루투스에 직렬링크로 COM3, COM4 두개가 있지만

왜 두개인지 모르겟음

 

 

근대 위 유튜브 영상보고 따라가다가

추가 블루투스 옵션으로 들어가면

 

블루투스 설정 컴포트 확인 가능

 

 

근데 스마트폰-PC 블루투스 연결에서 계속 문제생김

 

 

 

 

 

 

PC 스마트폰간 블루투스 연결이 잘안되서 이부분 pass

 

 

esp32 블루투스 - pc 등 예제

 

https://makerspace.steamedu123.com/entry/ESP32-%EB%B8%94%EB%A3%A8%ED%88%AC%EC%8A%A4-%ED%85%8C%EC%8A%A4%ED%8A%B8-%ED%95%98%EA%B8%B0

 

[ESP32] 블루투스 테스트 하기

본 절은 ESP32를 사용하기 위해 알아야 할 내용과 실습 방법에 대해 설명한다. SS1 특징, 동작원리, 사양, 연결 핀 배열, 출력 값, 주의사항을 알아본다. ESP32를 연결하고, 간단한 코딩으로 블루투스

makerspace.steamedu123.com

 

 

 

아무튼 불루투스 연결하면 시리얼 포트로 송수신 가능해보임

 

 

 

 

 

 

 

 

 

 

 

vr setup

1. oculus link sdk

2. android studio - sdk, jdk, ndk

3. stream vr

4. meta app 스마트폰

 

 

jdk 설치

13

https://www.oracle.com/java/technologies/javase/jdk13-archive-downloads.html

 

Java Archive Downloads - Java SE 13

WARNING: These older versions of the JRE and JDK are provided to help developers debug issues in older systems. They are not updated with the latest security patches and are not recommended for use in production. For production use Oracle recommends downlo

www.oracle.com

jdk 설치경로

C:\Program Files\Java\jdk-13.0.2

 

 

 

 

 

안드로이드 스튜디오 설치

 

 

 

 

 

sdk 위치 따로 놓기

C:\Users\addinedu\AppData\Local\Android\Sdk

 

 

 

 

플랫폼 안드로이드 12 설정

 

 

sdk툴에서 sdk빌드툴 31버전으로 설정

 

ndk는 25.1

 

커맨드라인툴은 최신

 

 

 

 

 

c++

character로 VRPlayer 추가

 

 

VRPlayer

 

 "EnhancedInput", "HeadMountedDisplay", "XRBase", "UMG" 

 

추가 후 빌드

안되면 언리얼 끄고, vs 재시작후 다시시도

 

 

 

모듈 추가후 generate visual studio project files

 

언리얼에서 링크해서 쓰기위해 steam vr 사용

 

 

 

스팀VR 할때 유선으로 링크해야함

 

 

 

 

안드로이드 플랫폼 설정

 

 

 

sdk 설정

ndk가 25이므로 

ndk api level을 26에서 25로 수정

 

 

empty 프로젝트로 만들땐

프로젝트-서포트 플랫폼, 타겟하드웨어 설정 필요

 

 

 

 

 

기본맵생성

 

빛강도 2

 

 

안개파란색

 

vrgamemodebase cpp 추가

 

 

 

블루프린트 생성

게임모드에서 디폴트폰 설정

 

 

디폴트게임모드 생성한걸로 변경

맵도 생성한  맵 설정

 

내가 구현하면서 실수한게

블루프린트에서 사용하던 ScreenX, Y는

C++에서 써야되서

 

C++에서 먼저 만들어서 가져와써야됫다.

근데 생각못하고 BP에 만들어서 사용

 

그래서 기존 ScreenX, ScreenY앞에 BP_를 붙여 이름을 구분하고

 

 

CameraPawn 헤더에 따로변수추가

윈API 쓸것이므로 

헤더 추가

커서 이동, 클릭을 위한 함수도 추가.

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Windows/AllowWindowsPlatformTypes.h"
#include <Windows.h>
#include "Windows/HideWindowsPlatformTypes.h"


#include <GameFramework/SpringArmComponent.h>
#include <Camera/CameraComponent.h>

#include "Components/PoseableMeshComponent.h"

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "CameraPawn.generated.h"

UCLASS()
class HANDDESKTOP_API ACameraPawn : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawn's properties
	ACameraPawn();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
	
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = PoseableMesh)
	UPoseableMeshComponent* HandRight;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = PoseableMesh)
	UPoseableMeshComponent* HandLeft;


	UPROPERTY(VisibleAnywhere, Category = Camera)
	class USpringArmComponent* springArmComp;

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera)
	class UCameraComponent* camComp;

	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = ScreenCoord)
	int ScreenX = 0;
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = ScreenCoord)
	int ScreenY = 0;

	UFUNCTION(BlueprintCallable, Category=MouseControl)
	void MouseMove();
	UFUNCTION(BlueprintCallable, Category = MouseControl)
	void MouseClick(int status);

};

 

마우스 무브 구현

void ACameraPawn::MouseMove()
{
	SetCursorPos(ScreenX, ScreenY);
}

 

 

 

 

BP스크린xY계산과 커서 이동 중간에

ScreenXY 설정, 마우스 무브도 추가

 

 

 

마우스 커서 이동 확인

 

마지막으로 마우스 클릭 구현 차례인데

 

 

일단 3이하받으면 마우스 이벤트 수행

아니면 안하고

void ACameraPawn::MouseClick(int status)
{
	INPUT input = { 0 };
	input.type = INPUT_MOUSE;

	if (status == 0)
		input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
	else if(status == 1)
		input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
	else if(status == 2)
		input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
	else if(status == 3)
		input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
	
	if (status <= 3)
		SendInput(1, &input, sizeof(INPUT));
}

 

 

 

 

 

마우스 클릭 이벤트 처리 시점을 생각해봤는데

커서 이동 체크 루틴에서

 

1. 커서 이동 체크시 아닐 겨우 확인 직후 바로

2. 커서 이동 체크시 이동하는 경우 ScreenXY 설정, 마우스 이동이후 바로

다뤄야 할듯

 

 

 

좌클릭의 경우 오른손 검지 중지 붙였을때

우클릭의경우 오른손 약지 소지를 접었을때로 처리

 

상태 다루기위한 ClickStatus, ClickStatusPrev int타입으로 추가

위 C++코드대로

0 : 좌마우스 다운

1 : 좌마우스 업

2 : 우마우스 다운

3 : 우마우스 업

4 : None

으로 5가지로 다룸

 

 

우선 좌클릭은 커서 이동여부 체크때 썻던 내용 활용

해서 하려고하는데

손 겹침과 마우스 입력 경우가 섞여있어서 햇갈린다.

 

나눠서 다시정리하자

 

 

손가락붙임상태

0 검지중지붙음

1 약지소지접힘

2 아무것도 안됨(디폴트)

 

마우스입력상태

0 : 좌마우스 다운

1 : 좌마우스 업

2 : 우마우스 다운

3 : 우마우스 업

4 : None(디폴트)

 

 

손가락붙임상태의 경우 이전, 현재를 따로 놓고 구분하자

 

이전 현재 값이 동일한 경우 4로 mouseClick함수 호출해서

SendInput을 안보내려고하는데

좌마우스 다운상태에서 SendInput시 드래그가 되는건진 모르겟다.

손가락붙임상태_이전 손가락붙임상태_현재 마우스입력상태
2(안붙음) 0(검지중지붙음) 0(좌마우스다운)
0(검지중지붙음) 2(안붙음) 1(좌마우스업)
2(안붙음) 1(약지소지접힘) 2(우마우스 다운)
1(약지소지접힘) 2(안붙음) 3(우마우스 업)
이전 현재 동일한경우 이전 현재 동일한경우 4(None)

 

이를 위해 마우스 스테이터스 변수 추가

 

 

 

 

 

오른손을보고 손가락붙임 상태 보는 BP

0, 1, 2 구분할수 있도록 만들었다.

 

 

 

 

 

 

 

 

그리고 이 표대로 작성 후

마우스 클릭 호출 하는 블루프린트

 

마우스 클릭 동작은 편의를 위해서 커서 움직이지 않는 경우에만 진입

손가락붙임상태_이전 손가락붙임상태_현재 마우스입력상태
2(안붙음) 0(검지중지붙음) 0(좌마우스다운)
0(검지중지붙음) 2(안붙음) 1(좌마우스업)
2(안붙음) 1(약지소지접힘) 2(우마우스 다운)
1(약지소지접힘) 2(안붙음) 3(우마우스 업)
이전 현재 동일한경우 이전 현재 동일한경우 4(None)

 

 

 

 

 

 

 

결과 영상

 

+ Recent posts