Serial is starting to really hack me off

if I do this

void setup()
{
  Serial.begin(115200); // DEBUG
  Serial1.begin(115200); // init serial port
}

void loop()
{
  if(Serial1.available() > 0)
  {
    Serial.println(Serial1.read(), HEX);
    Serial.println(Serial1.read(), HEX);
    Serial.println(Serial1.read(), HEX);
    Serial.println(Serial1.read(), HEX);
    Serial.println(Serial1.read(), HEX);
  }
}

I get the following, which is exactly what my device is sending out, confirmed with a PC and software to spy on the port.

C5
3
2
0
C4

if I do this however

byte input[5];

void setup()
{
  Serial.begin(115200); // DEBUG
  Serial1.begin(115200); // init serial port
}

void loop()
{
  if(Serial1.available() > 0)
  {
    input[0] = Serial1.read();
    input[1] = Serial1.read();
    input[2] = Serial1.read();
    input[3] = Serial1.read();
    input[4] = Serial1.read();
    Serial.println(input[0], HEX);
    Serial.println(input[1], HEX);
    Serial.println(input[2], HEX);
    Serial.println(input[3], HEX);
    Serial.println(input[4], HEX);
  }
}

I get this crap

C5
FF
FF
FF
FF
3
2
0
C4
FF

anyone care to shed some light?

You may be reading the serial buffrer faster than it is being filled.

 if(Serial1.available() > 0)
  {
    input[0] = Serial1.read();
    input[1] = Serial1.read();
    input[2] = Serial1.read();
    input[3] = Serial1.read();
    input[4] = Serial1.read();

You are checking if you have at least one byte and then reading 5. Maybe:

 if(Serial1.available() >= 5)

Serial.read() returns -1 if there's nothing to read in the serial buffer. 0xFF is the representation of -1.

Because you are reading and writing at the same speed you luck out and essentially wait for the next character to arrive.

When you write into an array there is no waiting so you get

char, -1, -1, -1, -1

then you print, meanwhile the other characters are arriving so when you get back to the reading they are there.

So the first code worked purely by dumb luck.


Rob