Processing & iOS

I love Processing. It's a great language that's derived from Java with a nice IDE and concept: don't worry about the complex stuff you need to do arts-y stuff with, it's already done for you. So in furthering my professional research (read: slacking-off), I've come up with a neat little code snippet for everyone to use the iPhone's accelerometer sensor for Processing sketches (see below). This snippet requires two pieces of software:

The Rundown

Basically, this snippet uses the listening capabilities of the UDP class to listen on a designated port for incoming UDP transmissions. The Accelerometer Simulator app streams a formatted packet over UDP to the host running the Processing Sketch.

Once received, the sketch splits the data packet into separate tokens, converts them into a 3D Vector (global variable p) where upon entering the drawing loop of the sketch, provides the location to which the 3D cube is drawn to relative to the center of the window. In order to make the movement of the cube more pronounced (acceleration ranges are approximately ±2.5g), an acceleration scaling factor was used to multiply the incoming acceleration samples.

The Code

// iPhoneAccelerometerProcessing.pde
import hypermedia.net.*;

// Global Variables
UDP udp;  
PVector p;  
final float prescaler = 20;

// Setup Method / Entry Point
void setup()  
{
    size(screen.width/2, screen.height/2, P3D);
    udp = new UDP(this, 6000);
    udp.listen(true);
    strokeWeight(4);
    p = new PVector(0,0,0);
}

// Draw Method / Per-Frame Drawing Routine
void draw()  
{
    background(255);
    translate((p.x*prescaler)+width/2,
              (p.y*prescaler)+height/2,
              (p.z*prescaler));
    rotateY(0.5);
    box(100);
}

// UDP Data Packet Listener
void receive( byte[] data, String ip, int port )  
{
    String message = new String(subset(data, 0, data.length-2));
    String[] toks = splitTokens(message, ",");
    p = new PVector(
            float(toks[2]), 
            float(toks[3]), 
            float(toks[4])
    );
}