We cannot tell. What’s the source of your quoted explanation above? Where did you find the indexes such as
bytes? (For future readers, please also provide the device brand and type.)
If the quote is taken from documentation for your sensor, and if you’ve got the byte indexes correct, and if the values are sent MSB first, and if the values are sent as signed integer numbers, and if they don’t need to be divided by some factor to get decimal numbers, then: yes. But we cannot tell from the information you’re providing.
Looking at the example payload (for which we still don’t know the expected values either!), it seems that
byte is (hexadecimal) 0xFF, and so is
It’s crucial you understand the shifting. Let’s decipher the next two bytes, those for
compass_y: FD and 09, when displayed in the human readable hexadecimal notation. In binary notation, those are the bit sequences 11111101 and 00001001.
- A left shift of 8 bits in
11111101 << 8 yields
00000000 00000000 11111101 00000000).
- Next, a bitwise OR in
11111101 00000000 | 00001001 yields
Please follow the links above and read the documentation.
As we’re shifting 8 bits (which is a full byte) at a time, the above is much easier to read in hexadecimal:
- For the byte
FD, the shifting
FD << 8 yields
00 00 FD 00.
00 00 FD 00 | 09 yields
00 00 FD 09.
00 00 FD 09 as a large positive number, 64.777. Instead, if it can indeed be negative, you’ll need the sign extension that I linked to above. That would result in:
Now, applying the above to
byte one would get 0xFFFFFFFF for
compass_x, which is exactly -1. That might be correct, but I cannot tell. Finally, for
compass_z you would get 0x00000007 (here, no sign propagating applies).
Finally, even with the above shifting and sign extension,
Math.atan2(0xFFFFFD09, 0xFFFFFFFF) * 180 / Math.Pi will still give you
If those are expected edge cases, then you could use the following to suppress the
NaN which TTN does not like:
heading: isNaN(heading) ? null : heading,
That’s the ternary operator already mentioned in Decrypting messages for dummies as well.
In your case, the formula is wrong. Debugging will show that
Math.atan2(-759, -1) * 180 yields -282.98 just fine. However,
-282.98 / undefined is NaN. You’ll need the uppercase
Math.PI instead. (And you still might want to check all of the above.)
Bonus, to limit the number of decimals, use:
// Unary plus operator to cast string result of toFixed to number
heading: isNaN(heading) ? null : +heading.toFixed(1)