I want to be able to send a uint16_t value over serial in raw hexadecimal bytes that will be picked up and converted back into the same data type on a different board. Think I've already sorted out the receiver code but am having a bit of trouble working out how to actually send the data.
The only reason I want to send the value in this format instead of just printing individual characters is due to bandwidth concerns. The more bandwidth I can save here, means more data I can transmit elsewhere. Keep in mind I need to work with a fixed baud rate so just increasing it isn't an option.
Code on receiving end takes raw hex data from serial buffer and converts into 6, 2 byte unsigned integers and stores in the array 'CSp_Temp' at address 'i' (IE: address 1 = 3104, address 2 = 1304).
for(byte i = 0; i <= CNum_Temp-1; i++){ //CNum_Temp is currently defined as 6
char buf[1]; //initialize buffer with two addresses (0,1)
buf[0] = Serial1.read(); //Store first byte of transmission in addr 0 (big endian)
buf[1] = Serial1.read(); //Store second byte in addr 1
uint16_t a = (buf[0]<<8)+buf[1]; //Hopefully converts hex to decimal
CSp_Temp[i] = a; //Adds decimal to array at address i
}
Would like to stick to standard c and c++ where possible.
Is it? The solution you have been given does not match your original request. The data is not transmitted in hex. It's transmitted in binary.
You said
which indicates some confusion. When we say "hex" what we really mean is ASCII characters representing the value as hexadecimal digits. For example the decimal value 255 is represented as "FF" which is 2 characters or 2 bytes or 16 bits. So hex is not "raw", it's an encoding. And in it's encoded form, it needs twice as many bits as the original value in binary (which is the true "raw" format for all data on any digital computer).
I think your suggestion is what @zx31 needs. If you replace the word "hex" with "binary" in @zx31 's original post, it makes more sense and fits your suggested solution. I think @zx31 doesn't understand what "hex" is and how that's different to binary.
Sorry @PaulRB, I should have clarified a bit better to avoid confusion on your end. I originally wanted to develop a script that converts a decimal number (uint16_t) into two hexadecimal bytes that I could pipe into the Serial.write function, which to my understanding takes a hexadecimal value and automatically converts it to binary to send over serial. An example of this is: Serial.write(0x45); // will write 0100 0101 to the cable.
'Raw' hex may not be a conventional term, but most people were still able interpret what was meant.
Luckily @jfjlaros gave a much more efficient and elegant solution to this problem.
When you write a value such as 0x45 into a sketch it is purely a convenience for humans reading the value because it is easier for use to visualise the value as 2 binary values, each if 4 bits (0100 and 0101) than if you wrote 69 in decimal and tried to visualise it as 01001010