problem with decoding 2-byte altitude

Hi all,

I've got an annoying problem and I haven't found the solution so far.

Basically I've got 2 bytes coming in through the serial port which is an altitude in meters. The user guide says as follows:

0x00 0x00 = -32768 meters
0xFF 0x00 = 0 meters
0xFF 0xFF = +32767 meters

I'd like to store this value correctly into an integer for angle calculations, but can't figure out how to do that.

I don't think this is a difficult problem, but I can't seem to find the right approach. Could anybody put me on the right track?

Thanks a bunch!

The user guide says as follows:

I think the user guide is wrong.

With 0x0000 at one end, and 0xFFFF at the other, the midpoint ought to be 0xx8000 or 0x7FFF, not 0xFF00.

int altitude = Serial.parseInt();

outsider:
int altitude = Serial.parseInt();

That won't work when the sender is sending binary data.

Well, how 'bout:

int altitude = Serial.read() <<8;
altitude += Serial.read();

outsider:
Well, how 'bout:

int altitude = Serial.read() <<8;

altitude += Serial.read();

Well, that would seem logical, except that a value of 0 means -32768 somethings (feet? inches? microns?), and a value of 0xFFFF means 32767 somethings, so at a minimum some offset is needed.

But, until we understand why the user guide claims that 0xFF00 means 0 somethings, how to deal with the two bytes is pure conjecture.

And, it assumes that both bytes have already arrived.

Agreed, 0x8000, 0, and 0x7fff would make sense, and I think i should have said:

int altitude = Serial.read();
altitude <<= 8;
altitude += Serial.read();

But I’m not too up on serial (yet).

So, the value comes in as a two-byte signed int, in meters, big end first. This is about as simple as it can possibly be. I’d tweak outsider’s code to this

int altitude = Serial.read();
altitude <<= 8;
altitude |= Serial.read();

but it doesn’t matter all that much.

… actually: -32768 is nine bits. What? Are you sure that’s what the user guide says?

Thanks for all the replies.
You were absolutely right: the user guide was completely off (actually not a commercially available product, just a description about an old software which might have changed).

So it was dead simple after all:

0xFF9C = -100m
0x0064 = +100m

To convert with the bitwise operations works perfect, thanks!

I don't seem to be able to simulate '0m' though. Any thoughts?

Thanks a lot!
Jens

jensvanhoof:
0xFF9C = -100m
0x0064 = +100m

To convert with the bitwise operations works perfect, thanks!

I don't seem to be able to simulate '0m' though. Any thoughts?

Well, if FF9C is -100, and 0064 is +100, you sould be able to add them (in hex) to get zero.

C and 4 is 16. So that's zero, carry one. 9 and 6 and one is 16, so again that's zeo and carry the one. 0 and F and 1 is 16, same again and what do you know - zero is 0x0000!