problem reading serial data

Hello,

i am new to Arduino and i have a problem reading some serial data with the arduino hardware.

The data is send from a pc using the com port at 9600 baud (9600 8N1). Example data:

CA 00 00 03 00 05 7E 04 C9 CB 00 CB 01 CC B2 8D

Interesting for me are the bytes after 7E so i started with the following:

int redPIN = 9;

byte incomingByte;

void setup() {
  Serial.begin(9600);
}
  
  
void loop() {
  if(Serial.available() >0) {
      incomingByte = Serial.read();
      
      switch(incomingByte) {
        case 0x7E:
          startByte();
        default:
          break;
      }
  }
}

int startByte() {
  //blink();
  byte value;
  value = Serial.read();
  if(value==0x04) {
    blink();
  }
}

int blink()
{
  analogWrite(redPIN, 255);
  delay(10);
  analogWrite(redPIN, 0);
}

Now it seems that it recognizes the 7E and startByte() will be called but after that i can´t get the additional bytes read like the value (0x04) in the startByte() function. blink() won´t be called.
The blink() function is only for debugging so don´t wonder g

Any ideas where the problem is?

best regards
Wotan

the serial.read() inside your function is being called when there is no data in the buffer, therefore returning junk (the function is non-blocking). Even if your sending computer is fast, and the characters are sent back to back, the arduino is so much faster than the serial communication speed that you are inside your function call well before the start bit of that second byte has started down the wire.

you need a test like this:

while (!serial.available())
   { ; }

before the serial.read (or any serial.read, for that matter).

-j

yes, thats it.

thank you kg4wsv