I cant recall exactly where I found this code, but it works perfect in Processing w/ Wii nunchuck and an Arduino. Some of the other codes I found had various errors I couldnt troubleshoot my way past; this one was just plug n play:
Code:/**
* this sketch displays all of the nunchuck inputs and a converted pitch and roll
*/
//float xmag, ymag = 0;
//float newXmag, newYmag = 0;
int sensorCount = 9; // number of values to expect
import processing.serial.*;
Serial myPort; // The serial port
int BAUDRATE = 115200;
char DELIM = ','; // the delimeter for parsing incoming data
void setup()
{
size(720, 480, P3D);
//noStroke();
colorMode(RGB, 1);
myPort = new Serial(this, Serial.list()[0], BAUDRATE);
// clear the serial buffer:
myPort.clear();
}
float x, z;
void draw()
{
background(0.5, 0.5, 0.45);
//BOX
pushMatrix();
translate(width/2 + sensorValues[5] * 2, height/2 + sensorValues[6] * 2, 0);
z = sensorValues[0] / 180 * PI ;
x = sensorValues[1] / 180 * PI;
rotateZ(z);
rotateX(x);
fill(255, 255, 255);
box(40, 70, 100);
//SPHERE
popMatrix();
pushMatrix();
translate(width/2 + sensorValues[2], 400 + -1 * sensorValues[4], -100 + sensorValues[3]); //this is where I am grabbing the accelerometer info from
fill(255, 0, 0);
sphere(50);
popMatrix();
fill(0, 0, 255);
if (sensorValues[7]==0) { // blue box button press
rect(10, 10, 40, 40);
}
fill(0, 255, 0);
if (sensorValues[8]==0) { //green box button press
rect(60, 10, 40, 40);
}
}
float[] sensorValues = new float[sensorCount]; // array to hold the incoming values
void serialEvent(Serial myPort) {
// read incoming data until you get a newline:
String serialString = myPort.readStringUntil('\n');
// if the read data is a real string, parse it:
if (serialString != null) {
//println(serialString);
//println(serialString.charAt(serialString.length()-3));
// println(serialString.charAt(serialString.length()-2));
// split it into substrings on the DELIM character:
String[] numbers = split(serialString, DELIM);
// convert each subastring into an int
if (numbers.length == sensorCount) {
for (int i = 0; i < numbers.length; i++) {
// make sure you're only reading as many numbers as
// you can fit in the array:
if (i <= sensorCount) {
// trim off any whitespace from the substring:
numbers[i] = trim(numbers[i]);
sensorValues[i] = float(numbers[i]);
}
// Things we don't handle in particular can get output to the text window
//print(serialString);
}
}
}
}