 # Equation to combine 2 bytes and break them?

Hi there! Im new to understanding bytes and stuff. I'm working with a CAN instrument panel. Control of the speedometer is a tiny bit tricky as it uses 2 bytes in an 8 byte array. Bytes 4 and 5. I think I know how I want to do the majority of my work? But I need help with figuring out how to code into 2 separate bytes.

map(MPH, 0, 318, 0, 65405) I think? 65405 because this is the value that the speedometer "maxes" out at when bytes 4,5 are sent (255, 125) And I think the math for this is byte4*256+byte5?

The map function will return any decimal value anywhere between 0 and 65405 if I understand it correctly, and I dont know how to break that properly into Byte4, byte5 every time. Like if it returns 0, or 10, or 57 ect.

here’s an approach that casts the “int” containing 65405 into a byte array

results

``````disp
1    2    3    4    5    6    7    0
disp
1    2    3    4  215  255    7    0
``````
``````#define N_BYTE  8
byte msg [N_BYTE] = { 1, 2, 3, 4, 5, 6, 7 };
int  value        = 65495;

// -----------------------------------------------------------------------------
void disp (
byte *arr,
int   nByte )
{
char s ;
Serial.println (__func__);

for (int i = 0; i < nByte; i++)  {
sprintf (s, " %4d", arr [i]);
Serial.print (s);
}
Serial.println ("");
}

// -----------------------------------------------------------------------------
void setup (void)
{
Serial.begin (115200);

disp (msg, N_BYTE);

byte *p = (byte*) &value;
msg  = p;
msg  = p;

disp (msg, N_BYTE);
}

// -----------------------------------------------------------------------------
void
loop (void)
{
}
``````

Or another approach…

``````uint8_t lo, hi;
uint16_t value;

// 2 bytes to 16-bit value...
lo = 0x34;
hi = 0x12;
value = (hi << 8) | lo;
// value is now 0x1234

// 16-bit value to 2 bytes
value = 0x4567;
lo = value;
hi = value >> 8;
// lo is now 0x67 and hi 0x45
``````

Arduino.h supplies a couple of handy macros:

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

They probably should have added this one:

``````#define toWord(high, low) ( (((uint16_t)(high)) << 8) + ((uint8_t)(low)) )
``````

Thank you so much! This is the code I ended up going with and it is accurate through the entire scale.

`````` int mappedSpeed = map (CurrentSpeed, 0, 318, 0, 65405);
Speedometer = mappedSpeed;
Speedometer = mappedSpeed>> 8;
``````