iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0

在感測真實物體的姿態時,我們會使用到 MPU 6050來感測當前姿態,今天我會透過六軸慣性感測器來感測物件的動作。我們知道 MPU6050 包含三軸陀螺儀、三軸加速度計,可以當作任何姿態感測使用,但因為今天並非包含磁力計,無法修正該計算時的偏移量,因此可能無法非常的精準。但若環境中沒有過多的軟磁與硬磁的干擾就沒關係。我們今天就會使用 MPU6050 來當作我們今天飛機的飛行姿態使用,今天是個非常有趣的實作,讓我們就直接開始!!!

場景建置

  1. 首先我們設計一下場景與我們的飛機模型。

  2. 將我們的 Camea 放置在該 Plane 上面。調整一下它的位置。注意視角會在飛機的後方。

撰寫物件移動的方式與Camera追蹤

  1. 首先新增一個腳本在 Plane 上。 Planefly.cs。讓我們飛機可以不斷地往前飛。並且新增一個 Rigidbody 在我們的飛機上。以下的程式碼就是會根據飛機前面的方向向前移動。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlaneFly : MonoBehaviour
{
    public float flySpeed = 10f;
    //public float turnSpeed = 100f;
    

    void Update() 
    {
        transform.position += transform.forward * Time.deltaTime * 1f * flySpeed;
	      //transform.Rotate(0, 1f * Time.deltaTime * turnSpeed, 0f, Space.Self);
    }
   
}
  1. 回到Unity 確認該 Fly Speed 與 Turn Speed數值。

Arduino 使用 MPU6050

  1. 這邊我就不太述說該怎麼計算MPU6050 的yaw, pitch, raw 的方法。我這邊也是使用 Arduino 提供的程式碼,稍微修改一些輸出的方式而已。我修改的地方太多若要解釋真的會花太多時間,所以就直接上程式碼。希望讀者可以自行參考~
#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;
// 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 INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)


float yaw_offset, pitch_offset, row_offset;
float yawArr, pitchArr, rowArr;
int i = 0;


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("yaw: ");
            Serial.print(ypr[0] * 180/M_PI - yaw_offset  );
            Serial.print(",");
            yawArr += ypr[0];
            //Serial.print("\tPitch: ");
            Serial.print(ypr[1] * 180/M_PI - pitch_offset);
            Serial.print(",");
            pitchArr += ypr[1];
            //Serial.print("\tRaw: ");
            Serial.println(ypr[2] * 180/M_PI - row_offset);
            rowArr += ypr[2];

            i++;
            if(i == 10)
            {
              yaw_offset = yawArr / 10;
              pitch_offset = pitchArr / 10;
              row_offset = rowArr / 10;
              /*Serial.println("yaw offset: ");
              Serial.print(yaw_offset);
              Serial.println("pitch offset: ");
              Serial.print(pitch_offset);
              Serial.println("row offset: ");
              Serial.print(row_offset);
              Serial.println();*/
              
              i = 0;
              yawArr = 0;
              pitchArr = 0;
              rowArr = 0;

            }
        #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);
        delay(50);
    }
}
  1. 接下來我們就將其執行看一下結果如何。結果如下 x, y, z 軸旋轉的結果。但其實基本是 yaw, pitch, roll 。

  2. 我們要先知道該實體的轉動方向,我這邊上照片讓大家瞭解一下。

回到 Unity 取得該讀取的數值與使用

  1. 首先新增兩個 Port 開啟與關閉的按鈕,同時我們要顯示該 yaw, pitch, roll 所以這邊我們先設計好 UI。這邊我設計得有些複雜,看個人喜歡進行設計就好。

  2. 開始撰寫獲取當前 yaw, pitch, roll 的方法。並且跟昨天一樣控制 Port 的開啟、關閉。我這邊廢話不多說直接上程式碼XDDD。我會提供一些有幫助的註解。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO.Ports;
using System.Threading;
using System.Globalization;

public class PlaneFly : MonoBehaviour
{
    public float flySpeed = 10f;
    public float turnSpeed = 100f;
    public Text yaw;    // show the yaw value 
    public Text pitch;  // show the pitch value 
    public Text roll;   // show the roll value

    float[] yprflt = new float[3];   // store the yaw pitch roll float value 
    string[] yprstr = new string[3]; // store the yaw pitch roll string value


    // port control
    string portName = "COM7";
    int baudRate = 115200;    // need to change the baudRate!
    Parity parity = Parity.None;
    int dataBits = 8;
    StopBits stopBits = StopBits.One;
    SerialPort serialPort = null;
    [SerializeField]
    public int isClosedPort = 1;

    void Start() 
    {
        OpenPort();

    }
    

    void Update() 
    {
        ReadData();
        transform.position += transform.forward * Time.deltaTime * 1f * flySpeed;
        //transform.Rotate(0, 1f * Time.deltaTime * turnSpeed, 0f, Space.Self);

        ObjectRotation();  // set the obj rotation
    }

    public void OpenPort() 
    {
        serialPort = new SerialPort(portName, baudRate, parity, dataBits,stopBits);
        try{
            serialPort.Open();
            Debug.Log("Open port success!");
        }catch(Exception ex) 
        {
            Debug.Log(ex.Message);
        }
    }

    public void ClosePort() 
    {
        try{
            serialPort.Close();
        }catch(Exception ex) 
        {
            Debug.Log(ex.Message);
        }
    }

    public void ReadData() 
    {
        if(serialPort.IsOpen)
        {
            string getypr = serialPort.ReadExisting();   //get the arduino output
            Debug.Log(getypr);
            yprstr = getypr.Split(',');     // need to split the string and store to ypystr array
            if(yprstr.Length == 3)
            {
                yaw.text = yprstr[0];
                pitch.text = yprstr[1];
                roll.text = yprstr[2];
            }else{
                Debug.LogWarning("Length is not correct!");
            }

            for(int i=0; i < yprstr.Length; i++)
            {
                yprflt[i] = float.Parse(yprstr[i]); // change string to float 
            }

            // Thread.Sleep(50);
        }
    }

    public void ObjectRotation()
    {
        transform.rotation = Quaternion.Euler(-yprflt[1], yprflt[0], -yprflt[2]);
    }
   
}
  1. 回到 Unity 中將我們的 Button 、Text 設定好。


  2. 我們再次調整一下我們飛機的起始距離與飛行速度。 如下設計:

  3. 我們執行看看,看到飛機會往前飛行~~根據我 Yaw 旋轉的來調整飛行的方向。底下的為 yaw, pitch, roll 的數值。但還是會有些偏移,畢竟沒有加上濾波器 : >。挺有趣的XDD,最後的結果如下:




結論:

  1. 之前我們可以讀取到 Arduino 輸出的數值存取到 Unity 顯示,今天我們透過 MPU 6050 實作一個簡易的飛機飛行時姿態的使用。
  2. 透過 Split 將我們回傳的字串透過逗號區隔並儲存到該 String 陣列裡面。幫助我們之後使用該回傳的字串。
  3. 使用 MPU6050 來幫助我們實現物體的姿態偵測。

上一篇
Day21: Arduino with Unity
下一篇
Day23: UI in Unity (Background, Scene Switch, Menu, Button Control)
系列文
Unity 基本功能實作與日常紀錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言