/////////////////////////////////////////////////////////////////////////
// adam setapen (asetapen)                  how to make (almost) anything
// 12.12.2010                                               MIT media lab
// bowViz.pde
//      Bow Accelerometer Visualizer
/////////////////////////////////////////////////////////////////////////
 
import processing.serial.*;
 
Serial myPort;        // The serial port
int xPos = 1,i=0;         // horizontal position of the graph
float inByte=0, calibration=0.0;
int xVal, yVal, zVal;
final float average_size = 100.0;
 
 void setup () {
   // set the window size:
   size(800, 600);        
   
   calibration=0.0;
   
   ////Serial setup
   myPort = new Serial(this, "/dev/tty.usbserial-A600dSL2", 9600);
  
   ////Canvas setup
   background(0);
 }
 
 
 void draw () {
   	int first, secnd, third, fourth;
	int xValLo, xValHi, yValLo, yValHi, zValLo, zValHi;
	
	// Look for frame
	first = secnd = third = fourth = 0;
	while (first != 1 || secnd != 2 || third != 3 || fourth !=4) {
		if (myPort.available() > 0) {
	 		first = secnd;
	 		secnd = third;
	 		third = fourth;
	 		fourth = myPort.read();
		}
	}
	
	// Read X low
	while (myPort.available() <= 0) {}
	xValLo = myPort.read();
	// Read X high
	while (myPort.available() <= 0) {}
	xValHi = myPort.read();
	
	// Read Y low
	while (myPort.available() <= 0) {}
	yValLo = myPort.read();
	// Read Y high
	while (myPort.available() <= 0) {}
	yValHi = myPort.read();
	
	// Read Z low
	while (myPort.available() <= 0) {}
	zValLo = myPort.read();
	// Read Z high
	while (myPort.available() <= 0) {}
	zValHi = myPort.read();
	
	// Build full numerical values
	xVal = 256*xValHi + xValLo;
	yVal = 256*yValHi + yValLo;
	zVal = 256*zValHi + zValLo;
   	inByte = (xVal + yVal + zVal)/3;
     
     //use calibration for the first couple cycles
     if(i<average_size){
       calibration = calibration+inByte;
       i++;
     }
     else if(i==average_size){
       calibration=calibration/average_size;
      i++; 
     }
     
     inByte = map(inByte, 0, 1023, 0, height);
     // draw the line:
     stroke(127,34,255);
     line(xPos, height, xPos, height - inByte);
     
//     fill(0);
//     rect(0,0,50,50);
//     fill(255);
//     stroke(255);
   
     // at the edge of the screen, go back to the beginning:
     if (xPos >= width) {
     xPos = 0;
     background(0); 
     } 
     else {
     // increment the horizontal position:
     xPos++;
   
  if(abs(inByte-calibration) < 1){
    stroke(255,0,0);
    ellipse(width/2,height/2,20,20);
  }
  //else background(0);
 }
 }
