Skip to content

Instantly share code, notes, and snippets.

@hecomi
Last active August 29, 2015 14:04
Show Gist options
  • Save hecomi/8b3f5a6f59f03ea7ec14 to your computer and use it in GitHub Desktop.
Save hecomi/8b3f5a6f59f03ea7ec14 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Uniduino;
public class Accelerometer : MonoBehaviour
{
private Arduino arduino_;
public Transform target;
public Vector3 basePinValues = Vector3.zero;
public Vector3 currentPinValues = Vector3.zero;
public int rotationCacheNum_ = 10;
private List<Vector3> rotationCache_ = new List<Vector3>();
public Vector3 rotation {
get {
var sum = Vector3.zero;
rotationCache_.ForEach(val => { sum += val; });
return sum / rotationCache_.Count;
}
}
void Start()
{
arduino_ = Arduino.global;
arduino_.Setup(ConfigurePins);
}
void Update()
{
Debug.Log()
AddRotationCache(new Vector3(
arduino_.analogRead(0),
arduino_.analogRead(1),
arduino_.analogRead(2)
));
if (target) {
target.rotation = Quaternion.Euler(rotation);
}
}
void AddRotationCache(Vector3 pinValues)
{
currentPinValues = pinValues;
var diff = pinValues - basePinValues;
rotationCache_.Add(new Vector3(
Mathf.Atan2(diff.x, diff.z) / Mathf.PI * 180,
0,
Mathf.Atan2(diff.y, diff.z) / Mathf.PI * 180
));
if (rotationCache_.Count > rotationCacheNum_) {
rotationCache_.RemoveAt(0);
}
}
void ConfigurePins()
{
SetAnalog(0);
SetAnalog(1);
SetAnalog(2);
}
void SetAnalog(int pin)
{
arduino_.pinMode(pin, PinMode.ANALOG);
arduino_.reportAnalog(pin, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment