Serial Issues Arduino and Processing

Hi,

I am trying to send multiple servo angles via a serial connection from Processing to Arduino. However, when I run both programs, the connection seems to be flakey -- sometimes it works, and other times it doesn't. I have included some of my code below this message. I would really appreciate any help.

Thank you very much!

Processing

    servoID = 210; 
    servo1Angle = anglebeta2; 
    myPort.write(servo1Angle);
    myPort.write(servoID);
    
    servoID = 211;
    servo2Angle = angleSigma2;
    myPort.write(servo2Angle);
    myPort.write(servoID);

Arduino

#include<Servo.h>
Servo servo1;
int s1_curr_ang = 30;
int s2_curr_ang =  95;

void setup() {
    servo1.attach(14);
    servo2.attach(15);

    Serial.begin(19200);
    Serial.println("Ready");
}

void loop() {
servo1.write(s1_curr_ang);
servo2.write(s2_curr_ang);
delay(100);
if ((Serial.available() == 4)) {
    base = Serial.read();  // these are all integers
    baseID = Serial.read();
    shoulder = Serial.read();
    shoulderID = Serial.read();
    
    if ((baseID > 209) && (base<199) && (shoulderID>209) && (shoulder<199)) {
      s1_curr_ang = base;
      s2_curr_ang = shoulder;
    }
  }
}
if ((Serial.available() == 4)) {

The == should be replaced with >=.

Are servoID, servo1Angle, and servo2Angle bytes in the Processing program?

Are base, baseID , shoulder, and shoulderID all bytes in the Arduino program?

Are you aware that serial data delivery follows the USPS business, where delivery is not guaranteed? The only guarantee is that an attempt will be made to deliver the data.

If any one of the 4 bytes sent does not make it, all subsequent data will be wrong, until 3 more bytes get lost.

Hi,

Thank you very much for the prompt reply.

All of those variables are integers in their respective programs.

I wasn't aware that the serial connection could miss some bytes, but this makes sense given what I saw in my debug printbacks.

Is there a way to make the communication more reliable?

I would appreciate receiving any hints.

Thank you very much, once again.

I always recommend start and end markers for packets:
.

Read serial data until you see a start marker (<). Then, read until and store the data in an array until you see an end marker (>). If there are 4 bytes in the array, the data is probably good. If there are fewer than 4 or more than 4, toss that incomplete/corrupt packet.

The variables should all be byte, since that is the type of data being sent.

Hi,

Thank you very much for the idea. It is very helpful. I am going to try it right now.

Thank you very much! I got this to work! Your advice was really helpful! I learned something new today.

--mtwister