I'm receiving 16 bytes from a sensor via serial and I want to assign the last 8 to 4 seperate variables pairwise so 2 bytes per variable.
These are my bytes printed out as an array.
84 68 65 84 0 0 0 0 1 0 0 0 82 82 65 73
Is it possible to assign the bytes to variables directly from serial or do I have to put it all into an array and split it?
This is how I do it now and it "sort of" works but it seems messy.
If you create a struct with the appropriate variables in it for the complete message then if you copy the message into the struct all the values will be available for use.
Intuitively, using the struct approach seem like the cleaner way to do this? However I need to read up on it to understand it properly.
Btw, I need the first 8 bytes as well for reading whether there's a registered target.
I tried reading the last 8 bytes into 4 2 byte arrays and convert them to integers and I get what seems like correct readings. Is this wrong?
byte TDAT_Distance[2];
Serial1.readBytes(TDAT_Distance, 2);
unsigned int distance = ((TDAT_Distance[1]<<8)+TDAT_Distance[0]);
}
int y1 = Serial.read()<<8|Serial.read(); //assuming MSByte arrives first
int y2 = Serial.read()<<8|Serial.read();
int y3 = Serial.read()<<8|Serial.read();
int y4 = Serial.read()<<8|Serial.read();
The compiler doesn't guarantee that the first Serial.read() in each statement is executed first. Changing the compiler version or even the optimization level might break your program if you rely on the order of execution like this.
christop:
The compiler doesn't guarantee that the first Serial.read() in each statement is executed first. Changing the compiler version or even the optimization level might break your program if you rely on the order of execution like this.
christop:
The compiler doesn't guarantee that the first Serial.read() in each statement is executed first. Changing the compiler version or even the optimization level might break your program if you rely on the order of execution like this.
1. Serial Buffer (Fig-1) of the UART Port is a FIFO (first-in first-out) type buffer. So, consecutive Serial.read() operations should always bring out data byte from the topmost location of the buffer.
2. Do you want to mean that the order of execution of the following two read() operations may not be from left to right?
int y1 = Serial.read()<<8|Serial.read(); //assuming MSByte arrives first