Skip to content

Commit eecda41

Browse files
authored
Merge pull request #21 from bareboat-necessities/codex/investigate-unrealistic-magnetic-readings
Fix BMM150 sign-extension to prevent inflated magnetometer values
2 parents 3fcf8d4 + 62fbd7b commit eecda41

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

atomS3R_bmi270_fifo/MagReader.h

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,16 @@ class MagReader
184184

185185
static int16_t signExtend(int16_t value, uint8_t bits)
186186
{
187-
const int16_t shift = 16 - bits;
188-
return (value << shift) >> shift;
187+
const int16_t signBit = static_cast<int16_t>(1U << (bits - 1));
188+
const int16_t valueMask = static_cast<int16_t>((1U << bits) - 1U);
189+
190+
value &= valueMask;
191+
if ((value & signBit) != 0)
192+
{
193+
value = static_cast<int16_t>(value - static_cast<int16_t>(1U << bits));
194+
}
195+
196+
return value;
189197
}
190198

191199
static void decodeBMM150Raw(const uint8_t auxData[BMI2_AUX_NUM_BYTES], int16_t &magX, int16_t &magY, int16_t &magZ)

0 commit comments

Comments
 (0)