Skip to content

Commit 1e11250

Browse files
authored
fix(icm20948): Fix endianness and scaling of magnetometer data (#597)
1 parent 2889c2a commit 1e11250

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

components/icm20948/src/icm20948.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -698,9 +698,9 @@ Icm20948<I>::Value Icm20948<I>::read_magnetometer(std::error_code &ec) {
698698
}
699699
float sensitivity = get_magnetometer_sensitivity();
700700
Value value = {
701-
static_cast<float>(raw.x) / sensitivity,
702-
static_cast<float>(raw.y) / sensitivity,
703-
static_cast<float>(raw.z) / sensitivity,
701+
static_cast<float>(raw.x) * sensitivity,
702+
static_cast<float>(raw.y) * sensitivity,
703+
static_cast<float>(raw.z) * sensitivity,
704704
};
705705
// update values
706706
mag_values_ = value;
@@ -1021,7 +1021,17 @@ Icm20948<I>::RawValue Icm20948<I>::get_gyroscope_raw(std::error_code &ec) {
10211021

10221022
template <espp::icm20948::Interface I>
10231023
Icm20948<I>::RawValue Icm20948<I>::get_magnetometer_raw(std::error_code &ec) {
1024-
return get_raw(RegisterBank0::MAG_DATA, ec);
1024+
// the magnetometer data is read through the I2C master, but it has a
1025+
// different endianess than the accelerometer and gyroscope data.
1026+
auto raw_mag = get_raw(RegisterBank0::MAG_DATA, ec);
1027+
if (ec) {
1028+
return {0, 0, 0};
1029+
}
1030+
return {
1031+
static_cast<int16_t>(((raw_mag.x & 0xFF00) >> 8) | ((raw_mag.x & 0xFF) << 8)),
1032+
static_cast<int16_t>(((raw_mag.y & 0xFF00) >> 8) | ((raw_mag.y & 0xFF) << 8)),
1033+
static_cast<int16_t>(((raw_mag.z & 0xFF00) >> 8) | ((raw_mag.z & 0xFF) << 8)),
1034+
};
10251035
}
10261036

10271037
template <espp::icm20948::Interface I>

0 commit comments

Comments
 (0)