Serial.write of 64 bits unsigned integers (or longer)

dorin

Member
Hello all,
I would like to see a code that sends fast to the USB interface 64 bits integers.
below is a copy of a code that does fail, although it is able to send a regular 32 bit integer.
The line that fails to compile is commented out, ( //Serial.write(integer64); )

I am guessing that for sending 64 bits integers one needs to treat them as arrays, and I would appreciate some sugestions.

Sincerely,
Dorin


********Code below ***********
unsigned long long integer64 = 0; // shifted sum of values
unsigned long integer32 = 0;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

Serial.print("Sending integer3 and integer64");
Serial.write(integer32);
//Serial.write(integer64);
}

void loop() {
// put your main code here, to run repeatedly:
}
 
If you just want to send the low 8 bits, as Serial.write(integer32) does, use this:

Serial.write((byte)integer64);

If you want to send all 8 bytes, use this:

Serial.write((char *)&integer64, 8);

If you want to print as human readable ASCII characters:

Serial.print(integer64);
 
Just to add a more generic solution:

Serial.write((char *)&myInt,sizeof(myInt));

will work for both 32 or 64 bit ints and most other data types as long as the size can be calculated correctly.

Please keep in mind that the other end of the serial link will be receiving a series of bytes NOT an int32_t or any other larger data type. The program at the other end needs to group these bytes and interpret them correctly, that normally requires you to insert some sort of header or start pattern into the data and then possibly a checksum or end marker.

On the plus side most systems are little endian these days so you probably won't have to worry about which order the bytes need to go in.

This is why sending values as text is often a lot simpler. Slower, both over the wire and in terms of processor load, but a lot simpler.
 
Back
Top