Skip to content

Instantly share code, notes, and snippets.

@johro
Created December 29, 2014 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johro/ca94ff8dd1f5ca576be5 to your computer and use it in GitHub Desktop.
Save johro/ca94ff8dd1f5ca576be5 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.IO.Ports;
using System.Threading;
using UnityEngine;
public class Light_controll : MonoBehaviour
{
private const string SERIAL_PORT = "COM6";
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();
private static bool swicth;
private static Light light;
void Start()
{
//DontDestroyOnLoad(this.gameObject);
_readThread = new Thread(Read);
_serialPort = new SerialPort(SERIAL_PORT, SERIAL_BAUD_RATE);
_serialPort.ReadTimeout = SERIAL_TIMEOUT;
try
{
_serialPort.Open();
}
catch (IOException)
{
this.gameObject.transform.eulerAngles = new Vector3(0, 90, 0);
this.gameObject.transform.parent = GameObject.Find("OVRCameraController").transform;
Destroy(this);
}
_continue = true;
swicth = true;
light = this.gameObject.GetComponent<Light>();
_readThread.Start();
}
void Update()
{
transform.rotation = _handQuaternion;
light.enabled = swicth;
}
void OnApplicationQuit()
{
_continue = false;
_readThread.Join();
_serialPort.Close();
}
private static void Read()
{
string[] values;
float x, y, z, w;
String str;
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]);
str = values[5];
w = float.Parse(values[1]);
_handQuaternion.Set(x, y, z, w);
if(str == "OK"){
swicth = true;
}
else
{
swicth = false;
}
}
}
catch (TimeoutException)
{
}
}
Thread.Sleep(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment