using System; using System.IO.Ports; using System.Threading; using UnityEngine; public class ControlObjectByMPU9150InUnity : MonoBehaviour { private const string SERIAL_PORT = "COM4"; private const int SERIAL_BAUD_RATE = 115200; private const int SERIAL_TIMEOUT = 100; private Thread _readThread; private static SerialPort _serialPort; private static bool _continue; private static Quaternion _handQuaternion = new Quaternion(); void Start() { _readThread = new Thread(Read); _serialPort = new SerialPort(SERIAL_PORT, SERIAL_BAUD_RATE); _serialPort.ReadTimeout = SERIAL_TIMEOUT; _serialPort.Open(); _continue = true; _readThread.Start(); } void Update() { transform.rotation = _handQuaternion; } void OnApplicationQuit() { _continue = false; _readThread.Join(); _serialPort.Close(); } private static void Read() { string[] values; float x, y, z, w; while (_continue) { if (_serialPort.IsOpen) { try { values = _serialPort.ReadLine().Split('\t'); if (values[0] == "quat") { x = float.Parse(values[2]); y = -float.Parse(values[4]); z = float.Parse(values[3]); w = float.Parse(values[1]); _handQuaternion.Set(x, y, z, w); } } catch (TimeoutException) { } } Thread.Sleep(1); } } }