First byte jumbled up with the second byte

Hello there, I’m trying to read an array of bytes from my serial device after sending out a fixed command from Arduino. However, I noticed that the first byte returned has jumbled up with the second byte. Can someone please tell me what is wrong with my code?

char incoming[100];

void setup() {
Serial.begin(115200);
}

void loop() {

byte command[] = {0xDD, 0x01, 0x05};
Serial.write(command, 3);
Serial.readBytes(incoming,100);

Serial.println(incoming[1],HEX);
Serial.println(incoming[2],HEX);

delay(100);

}

Expected first byte : 0x01
Expected second byte : 0xDD

Instead, when I read incoming[1], I got 0xFFFFFFDD. It seems that the first byte somehow has jumbled up with the second byte.

Please post your entire sketch, not just a snippet.

Sorry, this is the entire code.

char incoming[100];

void setup() {
Serial.begin(115200);
}

void loop() {

byte command[] = {0xDD, 0x01, 0x05};
Serial.write(command, 3);
Serial.readBytes(incoming,100);

Serial.println(incoming[1],HEX);
Serial.println(incoming[2],HEX);

delay(100);

}

Try byte incoming[100];

aarg:
Try byte incoming[100];

Now the first byte is read as 0xDD (instead of 0xFFFFFFDD), the first byte 0x01 went missing.

ophirian:
I the first byte is read as 0xDD (instead of 0xFFFFFFDD), the first byte 0x01 went missing.

Again please, this time with meaning.

AWOL:
Again please, this time with meaning.

Now the first byte is read as 0xDD (instead of 0xFFFFFFDD), where 0xDD is supposed to be the second byte returned from my device.

Have a look at Serial Input Basics. Simple reliable ways to receive data.

...R

Instead, when I read incoming[1], I got 0xFFFFFFDD. It seems that the first byte somehow has jumbled up with the second byte.

Array indices start at 0, not 1. You really haven't a clue what you got, because there is NO print() overload that PROPERLY handles printing an int in HEX format.

ophirian:
Expected first byte : 0x01
Expected second byte : 0xDD

Instead, when I read incoming[1], I got 0xFFFFFFDD. It seems that the first byte somehow has jumbled up with the second byte.

Sign extension.

Your byte is being treated as a signed rather than an unsigned quantity. So when it is padded out to 32 bits, the compiler adds the 1s so as to keep the numeric value (-34) the same.

To fix, either make 'incoming' an array of byte rather than an array of char, or cast it like so

Serial.println((byte)incoming[1],HEX);
Serial.println((byte)incoming[2],HEX);