Phidgets accelerometer with processing
If you ever need to use the phidget accelerometer, Ru and me figured out how to use it in processing.
Here is the sketch.
import com.phidgets.*;
import com.phidgets.event.*;
AccelerometerPhidget am = null;
PFont font;
// function to open and read the accelerometer
void setupAccelerometer()
{
try
{
am = new AccelerometerPhidget();
am.addAccelerationChangeListener(new AccelerationChangeListener() {
public void accelerationChanged(AccelerationChangeEvent ae) {
}
}
);
// connect to Accelerometer
am.openAny();
println("Waiting for Accelerometer");
am.waitForAttachment();
println("OK ready to go");
}
catch(Exception e) {
println("ERROR");
System.out.println(e);
}
}
void setup()
{
size(400,140);
background(50);
font = loadFont("ArialMT-24.vlw"); //remember to create the font
// setup Accelerometer
setupAccelerometer();
}
void draw()
{
background(50);
try
{
float ax = (float)am.getAcceleration(0); //accelerometer values are doubles
float ay = (float)am.getAcceleration(1); //convert first to float
float az = (float)am.getAcceleration(2);
float mAx = map(ax, -1, 1, 0, 255); //map them to something reasonable
float mAy = map(ay, -1, 1, 0, 255);
float mAz = map(az, -1, 1, 0, 255);
int imAx = int(mAx); //then convert the values to int
int imAy = int(mAy);
int imAz = int(mAz);
if(imAx < 0){ //the mapping does not work all the time
imAx = 0; //this gets rid of the negative values
}
if(imAy < 0){
imAy = 0;
}
if(imAz 255){ //and this gets rid of the values over the limit
imAx = 255;
}
if(imAy > 255){
imAy = 255;
}
if(imAz > 255){
imAz = 255;
}
fill(imAx);
rect(30, 40, 55, 55);
textFont(font);
text(imAx, 30, 120);
fill(imAy);
rect(100, 40, 55, 55);
textFont(font);
text(imAy, 100, 120);
fill(imAz);
rect(170, 40, 55, 55);
textFont(font);
text(imAz, 170, 120);
fill(0);
rect(240, 40, 55, 55);
rect(310, 40, 55, 55);
//print("x axis = ");
//println(am.getAcceleration(0)); // Index 0 is the x-axis
//print("y axis = ");
//println(am.getAcceleration(1)); // 1 is the y-axis
//print("z axis = ");
//println(am.getAcceleration(2)); // 2 is the z-axis
//you can use am.getAccelerationMax or Min get the max and min values
//println(am.getAxisCount()); //getAxisCount returns the number of axis the
//the accelerometer has
}
catch(Exception e) {
println("ERROR");
System.out.println(e);
}
}