🔍

gyroscope data to unity via Arduino serial

Arduino setup


#include <Arduino.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>

Adafruit_MPU6050 mpu;

void printMetrics()
{
    sensors_event_t a, g, temp;

    for (byte i = 0; i < 150; i++) {
        mpu.getEvent(&a, &g, &temp);

        
        Serial.print(a.gyro.x);
       // Serial.print( g.acceleration.x);
        Serial.print(";");
        Serial.print(a.gyro.y);
        Serial.print(";");
        Serial.print(g.gyro.z);
        Serial.println();
        delay(10);
    }
}

void setup(void)
{
    Serial.begin(9600);
    if (!mpu.begin()) {
        Serial.println("Failed to find MPU6050 chip");
        while (true) {}
    }
}

void loop()
{
 
   
   
    // normal readings
    mpu.enableSleep(false);
    mpu.enableCycle(false);
    printMetrics();
 

    // cycle mode (ensure that sleep mode is not active)

   /* 
    mpu.setCycleRate(MPU6050_CYCLE_20_HZ);
    mpu.enableSleep(false);
    mpu.enableCycle(true);
    printMetrics();
    */

/*
    // sleep mode (measurements halted; fetching data still enabled)
    mpu.enableCycle(false);
    mpu.enableSleep(true);
    printMetrics();

*/
  delay(40);
}



basic Unity C# interface


using System.Collections;
using System;
using System.IO.Ports;
using UnityEngine;
 
public class gyro_controller : MonoBehaviour
{
    // smooth factor! > raw gyro data is very shaky!
    public float smoothing = .1f;
   
    SerialPort stream;
 
    static float t=0.0f;
    public GameObject target; // is the gameobject to
 
    public float multiplicator = 5f;
 
    float curr_offset_x = 0;
    float curr_offset_y = 0;
    float curr_offset_z = 0;
 
    // Increase the speed/influence rotation
    public float factor = 7;
 
 
 
    // SELECT YOUR COM PORT AND BAUDRATE
    public string port = "COM37";
    int baudrate = 9600;
    int readTimeout = 25;
 
    void Start()
    {
        // open port. Be shure in unity edit > project settings > player is NET2.0 and not NET2.0Subset
        stream = new SerialPort("\\\\.\\" + port, baudrate);
 
        try
        {
            stream.ReadTimeout = readTimeout;
        }
        catch (System.IO.IOException ioe)
        {
            Debug.Log("IOException: " + ioe.Message);
        }
 
        stream.Open();
    }
 
    void Update()
    {
 
        string dataString = "null received";
 
        if (stream.IsOpen)
        {
            try
            {
                dataString = stream.ReadLine();
               // Debug.Log("RCV_ : " + dataString);
            }
            catch (System.IO.IOException ioe)
            {
                Debug.Log("IOException: " + ioe.Message);
            }
 
        }
        else
            dataString = "NOT OPEN";
        Debug.Log("RCV_ : " + dataString);
 
        if (!dataString.Equals("NOT OPEN"))
        {
            // recived string is  like  "accx;accy;accz;gyrox;gyroy;gyroz"
            char splitChar = ';';
            string[] dataRaw = dataString.Split(splitChar);

            
 
           
            // normalized accelerometer values
            float gyroX = float.Parse(dataRaw[0]) * multiplicator;
            float gyroY = float.Parse(dataRaw[1]) * multiplicator;
            float gyroZ = float.Parse(dataRaw[2]) * multiplicator;

 
        
             // Convert gyroscope values to radians per second
    float radiansPerSecondX = gyroX * Mathf.Deg2Rad;
    float radiansPerSecondZ = gyroY * Mathf.Deg2Rad;
    float radiansPerSecondY = gyroZ * Mathf.Deg2Rad;

    

    // Compute the rotation delta relative to the world axes
    Quaternion rotationDelta = Quaternion.Euler(
        radiansPerSecondX ,
        radiansPerSecondY ,
        radiansPerSecondZ );

    // Apply the smoothed rotation delta to the object's rotation
    target.transform.rotation = Quaternion.Slerp( target.transform.rotation, rotationDelta, smoothing );

 
 
        }
    }
 
}