[SOLVED] Sending analog input value (10 bits) over Serial (8 bits) ???

To send a 10-bit analog value from A3 over Serial, I need to split the bits into two bytes on the first Arduino, and then recombine these bytes on the second Arduino. Below is my guess about what the code might look like.

I'm hoping you'll find it very simple to correct for me, into matching lines that actually work.

And of course, many THANKS! :slight_smile:

byte lowByte, highBite;
int A3ValueToSend, A3ValueReceived ;

//              *** get value ***  
A3ValueToSend = analogRead(A3);   

//        *** split into two bytes ***
    lowByte  = (A3ValueToSend >> 2);
highByte = (A3ValueToSend << 8);

//   *** (send the two bytes to other Arduino) ***

//       *** Recombine the two bytes ***  
A3ValueReceived = (lowByte << 2) + (highBytge  >> 8);

https://www.arduino.cc/en/Reference/HighByte
https://www.arduino.cc/en/Reference/LowByte

There are many ways, even a struct or union is possible.
Also Serial.print(A3ValueToSend) will work, but then the readable text is send.
Do you want to send the binary data via Serial ? Or a readable text ?

The words 'lowByte' and 'highByte' are already in use for the functions, so I rather not make variables with the same name.

A3ValueToSend = analogRead(A3);  
low = lowByte( A3ValueToSend);
high = highByte( A3ValueToSend);
A3ValueReceived = word( high, low);

Thank you, Koepel !

I figured I was probably making things far more complicated than they need to be.

You're simple solution -- provided in your code example -- is perfect.

And thank you for the links, helping me underestand the principles more clearly.

The previous poster is correct that there are many ways to solve this problem. If you are just looking for corrections to your code, however, you want to change this:

//        *** split into two bytes ***
    lowByte  = (A3ValueToSend >> 2);
    highByte = (A3ValueToSend << 8);

//       *** Recombine the two bytes ***  
A3ValueReceived = (lowByte << 2) + (highBytge  >> 8);

To this:

//        *** split into two bytes ***
    lowByte  = (A3ValueToSend & 0xff);
    highByte = ((A3ValueToSend >> 8) & 0xff);

//       *** Recombine the two bytes ***  
A3ValueReceived = ((int)highByte  << 8) + lowByte;

For example if your 10 bit value was 0x345, then lowByte will be 0x45 (0x345 & 0xff) and highByte will be 0x3 ((0x345 >> 8) & 0xff).

Thank you, BigBobby,

I'm switching to your code example, because I beleive it is closer to the machine code behind the scenes, and therefore will run faster. :slight_smile:

Thank you, BigBobby,

I'm switching to your code example, because I beleive it is closer to the machine code behind the scenes, and therefore will run faster. :slight_smile:

To the compiler it's all the same.

From arduino.h

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))