Transfering an int as two bytes on the Arduino

Daniel picture Daniel · Oct 10, 2013 · Viewed 16.8k times · Source

I'm sampling at high frequencies and need to transmit the 10-bit ADC value via UART out of my Arduino.

By default, it uses a byte per character. So if doing an analogRead would yield the value of "612", it would send via UART "6" as one byte, "1" as one byte, "2" as one byte, and the line terminator as the last byte.

Given that my sampling rate is truncated by this communication, it's important that it's as efficient and uniform as possible, so I'm trying to force it to use two bytes to transmit that data, doesn't matter what the data actual is (by default it would use three bytes to transmit "23", four bytes to transmit "883" and five bytes to transmit "1001").

Currently, I'm doing something like this, which is the best way I've found:

int a = 600; //Just an example
char high = (char)highByte(a);
char low = (char)lowByte(a);
Serial.print(high);
Serial.println(low);

Currently this uses three bytes (including \n) regardless of the value. Is there an even more efficient method?

Just printing it with something like

Serial.print(foo, BIN);

Doesn't work at all. It actually uses one byte per every single bit of the binary representation of foo, which is quite silly.

Answer

ladislas picture ladislas · Oct 10, 2013

I might be missing something, but why don't you use Serial.write(byte)?

You can use a methode like this one:

void writeIntAsBinary(int value){
    Serial.write(lowByte(value));
    Serial.write(highByte(value));
}

what are you planning to do with the data on your computer?