Stefan Goodchild

TouchOSC and Processing Accelerometer Example Code

Playing with my iPhone and Processing v1 on the train last night I started messing with TouchOSC and thought that this super simple (and fairly rough) example code using the oscP5 library may help someone on their way to interactive wobbly nirvana.

Code after the jump.

import processing.opengl.*;
import oscP5.*;

OscP5 oscP5;

float xrot = 0;
float zrot = 0;

float xrot_targ = 0;
float zrot_targ = 0;
float orientation = 0;

float dampSpeed = 5;

void setup() {
  size(400,400, OPENGL);
  oscP5 = new OscP5(this,8000);
  smooth();
}

void draw() {
  camera(  0, 0, 300,
         0, 0, 0,
         0.0, 1.0, 0.0
     );
  background(0); 

  // Basic value smoothing

  if (xrot_targ > xrot) {
    xrot = xrot + ((xrot_targ - xrot) / dampSpeed);
  } else {
    xrot = xrot - ((xrot - xrot_targ) / dampSpeed);
  }

  if (zrot_targ > zrot) {
    zrot = zrot + ((zrot_targ - zrot) / dampSpeed);
  } else {
    zrot = zrot - ((zrot - zrot_targ) / dampSpeed);
  }

 // Detection for if the iPhone is upsidedown or not

  if (orientation < 0) {
    fill(255,0,0);
    rotateX(radians(xrot));
    rotateZ(radians(zrot));
  } else {
    fill(255,255,0);
    rotateX(radians(xrot*-1));
    rotateZ(radians(zrot*-1));
  }
  box(130,10,60);

}

void oscEvent(OscMessage theOscMessage) {
  if(theOscMessage.checkAddrPattern("/accxyz")==true) {
      xrot_targ = (theOscMessage.get(0).floatValue()*90);
      zrot_targ = (theOscMessage.get(1).floatValue()*90)*-1;
      orientation = theOscMessage.get(2).floatValue();
  }
}
  • THANK YOU! I am the Processing/Osc newb you were probably thinking of in posting this, and it has saved me from hours of hairpulling agony.

    Margaret

    August 11th, 2009 at 11:29 am |

  • thanks for this, I was just playing around and was looking for some code to delve in. this was to the point!

    Iman

    December 14th, 2009 at 1:47 pm |

Leave a Reply

Comment Feed | Trackback