Processing - Arduino Serial Communication problem

Hi!

I read a lot of posts about processing and arduino and serial port communication but still I can’t find a solution to my problem.

Sketch Code(Arduino)

....
Serial.begin(57600);        // start the hardware serial block and set the baud rate
  lastTime = millis();         // initialize lastTime variable
}

void loop() {
    gsr_count++;
    if (gsr_count>=41) {  //10*17 approx 700mS
      gsr_count=0;
      byte a=analogRead(0);
      Serial.print("A");
      Serial.println(a, BYTE);
    }
        //Code needs 16,47ms to run
        delay(15);
	
	Sensor = analogRead(PulseSensor);
	delayMicroseconds(100);
	Sensor += analogRead(PulseSensor);
	delayMicroseconds(100);
	Sensor += analogRead(PulseSensor);
	delayMicroseconds(100);
	Sensor += analogRead(PulseSensor);
	Sensor /= 4; 	//Low-pass Filtering
	


//    Sensor = analogRead(PulseSensor);      // take a reading

// KEEP TRACK OF THE DIRECTION OF THE WAVEFORM
    if (falling == false){                       // if the sensor values are rising 
      if (Sensor < lastSensor-1){                  // if current reading is less than last reading - noise      
         falling = true;                         // a peak has been reached
           
         digitalWrite(LED,LOW);                  // turn off pin 13 LED
      }else if(Sensor > lastSensor){             // otherwise, if current reading is bigger, values are still rising
         Peak = Sensor;                          // record the next potential peak
         lastSensor = Sensor;                    // keep track of rising signal  
      }
    }
    if (falling == true){                        // if the sensor values are falling
      if (Sensor > lastSensor){                  // if current reading is bigger than last reading
        falling = false;                         // a trough has been reached
        drop = Peak - Trough;                    // difference = signal amplitude
        Peak = 0;                                // setting Peak to 0 here helps get rid of noise
// THIS IF STATEMENT IS HOW THE HEARTBEAT IS FOUND IN PULSE SENSOR WAVEFORM         
        if (drop > 20 && drop <300){               // ignore noise in signal. adjust as needed
          timeBeat();                            // go work out the BPM
          digitalWrite(LED,HIGH);                // start pin 13 LED blink
        }                 
       }else if (Sensor < lastSensor){           // otherwise, if current reading is smaller we?re still falling 
         Trough = Sensor;                        // record the next potential trough      
         lastSensor = Sensor;                    // keep track of falling signal
       }   
      }
    
}// END VOID LOOP


void timeBeat(){
        time = millis();                          // take note of the current time
        beats[beatCounter] = time - lastTime;     // record miliseconds since the last pulse in beats array
        lastTime = time;                          // stay up to date! 
        beatCounter ++;                           // move array pointer to next position in array
        if (beatCounter == 10){                   // if we've taken 10 readings, it's time to derive heart rate
          QuantifiedSelf = getBPM();              // go derive the heart rate
          Serial.print("q");                      // send the heart rate to Processing sketch (or other)
          Serial.println(QuantifiedSelf);         // 'q' = heart rate
//          Serial.println(QuantifiedSelf, BYTE);
          beatCounter = 0; 
        }
}// END OF timeBeat FUNCTION


// This function will return a value for heart rate (Beats Per Minute)
int getBPM(){
    int dummy;                          // used in sorting
    int mean;                           // used in averaging
    boolean done = false;               // clear sorting flag    
// this simple sorting routine will arrange values in the beat array from lowest to highest 
    while(done != true){                
    done = true;
    for (int j=0; j<9; j++){           // simple swap sorts numbers from lowest to highest
      if (beats[j] > beats[j + 1]){     // sorting numbers here
        dummy = beats[j + 1];
        beats [j+1] = beats[j] ;
        beats[j] = dummy;
        done = false;
       }
     }
   }
// this FOR loop selects the longer beat time values to avoid incorrect heart rate readings
   for(int k=1; k<9; k++){              // exclude lowest and highest values from averaging 
    mean += beats[k];                   // add beat times together
   }
   mean /=8;                            // averaging
   mean = 60000/mean;                   // divide 60 seconds by average pulse length
   return mean;                         // return beats per minute
}// END OF getBPM function

Processing Code (JAVA)

public void serialEvent (Serial myPort) throws InterruptedException {

   int inByte = 0;
   int HByte = 0; 
   int serial =0;
   char delim ;
   if (gsr == true)
   {
       inByte = myPort.read();
       gsrValue=inByte;
       println("GSR : "+gsrValue);
       gsr = false;
       return;
   }
   if (hr == true)
   {
     String inData = myPort.readStringUntil('\n');
//	   int inData = myPort.read();
      inData = trim(inData);               // trim the \n off the end
      pulseRate = (Integer.parseInt(inData));
      System.out.println(pulseRate);
       hr = false;
       return;
   }
   if ((gsr == false) & (hr==false))
   {
       serial = myPort.read();
       delim = (char) serial;
       if (delim == 'q'){          // leading 'q' means heart rate data
           hr = true;
            }

       if (delim == 'A'){          // leading 'a' means gsr
           gsr = true;
               }
       return;
   }
}

I read values(data) from 2 different pins. This data has the following structure
Worst Case
“A”+byte
“q000\n”

Best Case
“A”+byte
“q00\n”

The sketch program works well on Serial Monitor but in Processing code the values get confused!!! The baud rate is the same for both programs 57600.

Where do I make mistake?!?!?!?!?

I am newbie in the arduino programming, but the points that I thinking of are:

1 way to solve the mismatching problem between Processing and arduino is to send from sketch a whole String. But on my occasion I want to send them separately for some important for me reasons....

The second solution is to add a time late in both codes (sketch & processing)...

The last option is what I am looking for. By if the data is not standard it is hard to calculate delays...

The sketch program works well on Serial Monitor but in Processing code the values get confused!!!

What does this mean? Show some sample output from the Serial Monitor and some sample output from Processing. Perhaps there is a simple pattern to the “confusion” that you just aren’t seeing.

Perhaps posting all of your Processing code would help, too. We can’t see how you have arranged for the serialEvent() function to be called.