Skip to content

Instantly share code, notes, and snippets.

@hecomi
Last active August 29, 2015 14:04
Show Gist options
  • Save hecomi/57299a56fb19bd9088ca to your computer and use it in GitHub Desktop.
Save hecomi/57299a56fb19bd9088ca to your computer and use it in GitHub Desktop.
namespace {
const int AVERAGE_NUM = 10;
const int BASE_X = 530;
const int BASE_Y = 519;
const int BASE_Z = 545;
}
void setup()
{
Serial.begin(9600) ;
}
void loop()
{
int x = 0, y = 0, z = 0;
for (int i = 0; i < AVERAGE_NUM; ++i) {
x += analogRead(0);
y += analogRead(1);
z += analogRead(2);
}
x /= AVERAGE_NUM;
y /= AVERAGE_NUM;
z /= AVERAGE_NUM;
const int angleX = atan2(x - BASE_X, z - BASE_Z) / PI * 180;
const int angleY = atan2(y - BASE_Y, z - BASE_Z) / PI * 180;
Serial.print(angleX);
Serial.print("\t");
Serial.print(angleY);
Serial.println("");
delay(16);
}
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RotateBySerialMessage : MonoBehaviour
{
private List<Vector3> angles = new List<Vector3>();
public int averageNum = 10;
public Vector3 angle {
get {
if (angles.Count > 0) {
var averageAngle = Vector3.zero;
angles.ForEach(angle => { averageAngle += angle; });
averageAngle /= angles.Count;
return averageAngle;
} else {
return Vector3.zero;
}
}
}
void OnSerialMessage(Vector3 angle)
{
angles.Add(angle);
if (angles.Count > averageNum) {
angles.RemoveAt(0);
}
}
void Update()
{
transform.rotation = Quaternion.Euler(angle);
}
}
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class SerialHandler : MonoBehaviour
{
public string portName = "/dev/tty.usbmodem1421";
public int baudRate = 9600;
public GameObject target;
private SerialPort serialPort_;
void Start()
{
Open();
}
void OnDestroy()
{
Close();
}
void Open()
{
serialPort_ = new SerialPort(portName, baudRate, Parity.None, 8, StopBits.One);
serialPort_.Open();
StartCoroutine( Read() );
}
void Close()
{
if (serialPort_ != null && serialPort_.IsOpen) {
serialPort_.Close();
}
}
public IEnumerator Read()
{
while (serialPort_ != null && serialPort_.IsOpen) {
string message = "";
try {
message = serialPort_.ReadLine().
Split(new string[]{"\n"}, System.StringSplitOptions.None)[0];
serialPort_.ReadChar();
} catch (System.Exception e) {
Debug.LogError(e.Message);
}
if (message != "") {
var data = message.Split(new string[]{"\t"}, System.StringSplitOptions.None);
OnMessage(data);
}
yield return new WaitForEndOfFrame();
}
yield break;
}
void OnMessage(string[] data)
{
if (data.Length < 2) return;
try {
var angleX = float.Parse(data[0]);
var angleY = float.Parse(data[1]);
var angle = new Vector3(angleX, 0, angleY);
if (target) {
target.SendMessage("OnSerialMessage", angle, SendMessageOptions.DontRequireReceiver);
}
} catch (System.Exception e) {
Debug.LogWarning(e.Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment