9 years, 10 months ago.

Is UINT14_MAX set wrong?

This code looks wrong:

  1. define UINT14_MAX 16383 if (acc > UINT14_MAX/2) acc -= UINT14_MAX;

as it means 0x3FFF mapes to zero - when it should probably map to -1; I recoded as:

  1. define UINT14_MAX 16384 if (acc > UINT14_MAX>>1) acc -= UINT14_MAX;

Which seemed to give better behaviour when accln passes through zero

Question relating to:

samux MMA8451Q accelerometer library

Actually my code is wrong as well, encodes 0x2000 as 0x2000 not -0x2000. So bit more thought, given the confusion on right shifting -ve numbers: <code>

  1. define MSB 0x2000 if (acc&MSB) acc -= 2*MSB </code>
posted by David Summers 04 Jan 2015

1 Answer

9 years, 10 months ago.

It is easier to read the code you place here if you wrap it with <<code>> and <</code>> tags.

I would say that UINT14_MAX is set to the correct value but as you have noticed, it isn't being used correctly to extend the signed 14-bit value to 16-bits. Another way to accomplish the same thing would be to left shift away the two upper unused bits and then use an arithmetic shift back to the right to get the proper sign extended value:

acc = (acc << (16 - 14)) >> (16 - 14);

Thanks for the <<code>><<code>><</code>> trick - yes noticed my question had become manged in posting, but not yet on top of the mbed interface :)

Your solution assumes that acc is a signed 16bit integer, which of course it is - but am not sure I like that assumption. Also is it well defined what <<code>>-4>>2<</code>> means? I generally only think of shift opperators in the unsigned int world, where its clear what they mean.

posted by David Summers 31 Dec 2014