Ardiuno 2: Accelerometer

import ddf.minim.*;
import ddf.minim.ugens.*;

import processing.serial.*; 
Serial myPort;  
 
Minim       minim;
AudioOutput out;
Oscil       wave;

float inX;
float inY;
float inZ;

float inBend;

float inR;
float inG;
float inB;
float inT;
float inH;

float bX;
float bY;
float bZ;

int check = 0;

float sensors[];

int ch = 0;

String myString;
 
void setup(){
  size(800,500);
 
  minim = new Minim(this);
 
  // use the getLineOut method of the Minim object to get an AudioOutput object
  out = minim.getLineOut();
 
  // create a sine wave Oscil, set to 440 Hz, at 0.5 amplitude
  wave = new Oscil( 440, 0.5f, Waves.SINE );
  // patch the Oscil to the output
  wave.patch( out );
  
  String portName = Serial.list()[2];
  myPort = new Serial(this, portName, 9600);
  myPort.bufferUntil('\n');
}
 
void draw()
{
  background(0);
  stroke(255);
  strokeWeight(1);
 
  // draw the waveform of the output
  for(int i = 0; i < out.bufferSize() - 1; i++)
  {
    line( i, 250  - out.left.get(i)*50,  i+1, 250  - out.left.get(i+1)*50 );
    line( i, 350 - out.right.get(i)*50, i+1, 350 - out.right.get(i+1)*50 );
  }
 
  // draw the waveform we are using in the oscillator
  stroke( 128, 0, 0 );
  strokeWeight(4);
  for( int i = 0; i < width-1; ++i ) { point( i, height/2 - (height*0.49) * wave.getWaveform().value( (float)i / width ) ); } noStroke(); fill(80); rect(100,40,400,20); rect(100,80,400,20); rect(100,120,400,20); textSize(12); fill(255); textAlign(RIGHT); text("X AXIS",90,55); text("Y AXIS",90,95); text("Z AXIS",90,135); /// 3 axis of the accelorometer fill(0,255,255); rect(290 + (bX-inX)/2,40,inX-bX,20); rect(290 + (bY-inY)/2,80,inY-bY,20); rect(290 + (bZ-inZ)/2,120,inZ-bZ,20); if(inX > 0 && check == 0){
    bX = inX;
    bY = inY;
    bZ = inZ;
    check = 1;
  }
  if (myString != null) {
    myString = trim(myString);
    float sensors[] = float(split(myString, ','));

    inX=sensors[0];
    inY=sensors[1];
    inZ=sensors[2];

    inBend=sensors[6];

    inR=sensors[3];
    inG=sensors[4];
    inB=sensors[5];

    inT=sensors[7];
    inH=sensors[8];

  }
  float amp = map( bX-inX, -200, 200, 1, 0 );
  wave.setAmplitude( amp );
  
  float freq = map( bZ-inZ, -200, 200, 110, 880 );
  wave.setFrequency( freq );
  
}

 
void keyPressed()
{ 
  switch( key )
  {
    case '1': 
      wave.setWaveform( Waves.SINE );
      break;
 
    case '2':
      wave.setWaveform( Waves.TRIANGLE );
      break;
 
    case '3':
      wave.setWaveform( Waves.SAW );
      break;
 
    case '4':
      wave.setWaveform( Waves.SQUARE );
      break;
 
    case '5':
      wave.setWaveform( Waves.QUARTERPULSE );
      break;
 
    default: break; 
  }
}

void serialEvent(Serial myPort) {
  // read the serial buffer:
  myString = myPort.readStringUntil('\n');
}