Many threads made I made code for the Arduino to take in accelerometer data. Here is the processing code to calculate the orientation.
/*
Sections of this code is taken from Tom Igoe's
Making Things Talk book. Specifically from
pages 288 to 292.
*/
import processing.serial.*;
import processing.opengl.*;
Serial myPort;
boolean madeContact = false;
boolean runOnce = false;
float check = 0;
int vals[] = new int[3];
int valsInit[] = new int[3];
float mapVals[] = new float[3];
float staticVals[] = new float[3];
float dynamicVals[] = new float[3];
float staticXYZ[] = new float[3];
float dynamicXYZ[] = new float[3];
float XYZ[] = new float[3];
int staticCum = 1;
int dynamicCum = 1;
String myString;
PFont font;
void setup(){
size(800,800,OPENGL);
background(0);
font = loadFont("Osaka-24.vlw");
textFont(font, 24);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 19200);
myPort.bufferUntil('\r');
}
void serialEvent(Serial myPort){
madeContact = true;
myString = myPort.readStringUntil('\n');
parseString(myString);
}
void parseString(String Str){
if (Str != null){
Str = trim(Str);
int sensors[] = int(split(Str, ','));
if (sensors.length >= 3){
for (int i = 0; i < 3; i++){
vals[i] = sensors[i];
mapVals[i] = map(vals[i], 0 ,1024, -1, 1);
}
if (runOnce == false){
valsInit = sensors;
runOnce = true;
}
}
myPort.write('\r');
}
}
void arrow(){
stroke(204, 102, 0);
pushMatrix();
translate(width/2,height/2);
beginShape(LINES);
vertex(0,0,0);
vertex(XYZ[0],XYZ[1],XYZ[2]);
endShape();
popMatrix();
}
void draw(){
background(0);
if (madeContact == false){ //if there is no serial event send a character
myPort.write('\r');
}
float sqrtVal = sqrt(sq(mapVals[0])+sq(mapVals[1])+sq(mapVals[2]));
if(sqrtVal >= 0.58 && sqrtVal <= 0.64){
//the accelerometer is static
for(int i=0; i < 3; i++){
staticVals[i] = mapVals[i] + staticVals[i];
staticXYZ[i] = staticVals[i]/staticCum;//lost this array somewhere
}
dynamicCum = 1;
for(int i=0; i < 3; i++){
dynamicVals[i] = 0;
}
staticCum++; //accumulator was in the wrong place
}
else{
//this is dynamic!!!
for(int i=0; i < 3; i++){
dynamicVals[i] = (mapVals[i] + dynamicVals[i]);
dynamicXYZ[i] = dynamicVals[i]/dynamicCum;
}
staticCum = 1;
for(int i=0; i < 3; i++){
staticVals[i] = 0;
}
dynamicCum++;
}
for (int i=0; i < 3; i++){
XYZ[i] = width*(staticVals[i]-dynamicVals[i]);
}
int yHold = 50;
for (int i = 0; i < 3; i++){
text(staticXYZ[i], 250, yHold+50);
text(dynamicXYZ[i], 150, yHold+50);
yHold = yHold + 50;
text(sqrtVal, 300, 300);
}
arrow();
}