ofSerial funk

…after 16 hours of struggle, and every attempt I could possibly image, I have decided to turn to the forum.

I have hooked some trackballs up to an Arduino which is in-turn connected to Ofx.

I am 99% sure the Arduino end is okay… but for some reason Ofx is (at times) reading the incoming in a wacky way. This is catastrophic.

See video, http://www.youtube.com/watch?v=Q0jJ-tvdBJ4&feature=youtu.be

  
  
    if(firstContact==false){  
		ofSleepMillis(5000); //we need this delay while Arduino gets reads		  
		bool byteWasWritten = serial.writeByte('a'); //request data  
		if(byteWasWritten){  
			firstContact=true;  
			cout << "first contact made" << endl;  
			ofSleepMillis(1000); 			  
		}  
    }  
	  
	if((firstContact==true)&&(serial.available())){  
  
		cout << "we have serial " << mCount << endl;  
		  
		while((serial.readBytes(bytesReturned,6))>0){  
	  
		//player 1 ~~~~~~~~~~~~~~~~~~~~~~~~~  
		//read, x1  
		if(bytesReturned[0] != 0){  
			x1 = bytesReturned[0];  
			if(x1>127){  
				x1 = x1-256;  
			}  
		}  
		//read, y1  
		if(bytesReturned[1] != 0){  
			y1 = bytesReturned[1];  
			if(y1>127){  
				y1 = y1-256;  
			}  
		}  
		//read, pot1  
		int temp_pot1 = bytesReturned[2];  
		if(abs(temp_pot1-pot1_prev)>2){ //make sure we moved the pot 2/127  
			pot1 = temp_pot1;  
			pot1_prev = pot1;  
		}  
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
  
		  
		//player 2 ~~~~~~~~~~~~~~~~~~~~~~~~~  
		//read, x2  
		if(bytesReturned[2] != 0) {  
			x2 = bytesReturned[2];  
			if(x2>127){  
				x2 = x2-256;  
			}  
		}  
		//read, y2  
		if(bytesReturned[3] != 0) {  
			y2 = bytesReturned[3];  
			if(y2>127){  
				y2 = y2-256;  
			}  
		}  
		//read, pot2  
		int temp_pot2 = bytesReturned[5];  
		if(abs(temp_pot2-pot2_prev)>2){  
			pot2 = temp_pot2;  
			pot2_prev = pot2;  
		}  
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
  
		}  
		  
		bool byteWasWritten = serial.writeByte('a'); //request more data  
		if(byteWasWritten){  
			cout << "more data requested" << endl;  
			//ofSleepMillis(1);  
		}  
  
		velR.x += x1;  
		velR.y -= y1;  
		velG.x += x2;  
		velG.y -= y2;  
		x1 = 0;  
		y1 = 0;  
		x2 = 0;  
		y2 = 0;  
			  
	}  
  

Okay, after much struggle, here is a working solution for reading 12 chars.
I can only assume there is something wrong with ‘while((serial.readBytes(bytesReturned,6))>0){’

  
  
        unsigned char bytesReturned[12];  
  
        int bytesNeeded = 12;  
  
        int arrayOffset = 0;  
  
        unsigned char tempArray[12];  
  
        while ( bytesNeeded )  
  
        {  
  
            int i;  
  
            int bytesRead = serial.readBytes(tempArray, 12 - arrayOffset);  
  
            for( i = 0; i< bytesRead; i++ )  
  
            {  
  
                bytesReturned[arrayOffset] = tempArray[i];  
  
                arrayOffset++;  
  
                bytesNeeded--;  
  
            }  
  
        }