Skip to content

Instantly share code, notes, and snippets.

@takahi5
Created August 17, 2014 02:19
Show Gist options
  • Save takahi5/530888429a3137306ecf to your computer and use it in GitHub Desktop.
Save takahi5/530888429a3137306ecf to your computer and use it in GitHub Desktop.
[Unity + Arduino] Smoothing sensor input
using UnityEngine;
using System.Collections;
using Uniduino;
public class ArduinoController : MonoBehaviour {
public Arduino arduino;
public int pinValueX;
public int pinValueY;
public int pinValueZ;
ArrayList pinValueListX = new ArrayList();
ArrayList pinValueListY = new ArrayList();
ArrayList pinValueListZ = new ArrayList();
// smoothing回数 多いほど滑らか
int SMOOTHING_LENGTH = 10;
// Use this for initialization
void Start () {
arduino = Arduino.global;
arduino.Setup (ConfigurePins);
}
void ConfigurePins( )
{
// Use Analog output 3, 4, 5 pin
arduino.pinMode(3, PinMode.ANALOG); //x
arduino.pinMode(4, PinMode.ANALOG); //y
arduino.pinMode(5, PinMode.ANALOG); //z
arduino.reportAnalog(3, 1);
arduino.reportAnalog(4, 1);
arduino.reportAnalog(5, 1);
}
// Update is called once per frame
void Update () {
updatePinValueList (
arduino.analogRead (3),
arduino.analogRead (4),
arduino.analogRead (5)
);
pinValueX = getSmoothedValue (pinValueListX);
pinValueY = getSmoothedValue (pinValueListY);
pinValueZ = getSmoothedValue (pinValueListZ);
}
void updatePinValueList(int x, int y, int z){
if (pinValueListX.Count > SMOOTHING_LENGTH) {
pinValueListX.RemoveAt(0);
}
if (pinValueListY.Count > SMOOTHING_LENGTH) {
pinValueListY.RemoveAt(0);
}
if (pinValueListZ.Count > SMOOTHING_LENGTH) {
pinValueListZ.RemoveAt(0);
}
// ★smoothing後の値
pinValueListX.Add (x);
pinValueListY.Add (y);
pinValueListZ.Add (z);
}
int getSmoothedValue(ArrayList list){
if (list.Count < SMOOTHING_LENGTH) {
return 0;
}
int sum = 0;
for (int i=0; i<list.Count; i++){
sum += (int)list[i];
}
return (int)(sum / SMOOTHING_LENGTH);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment