From 951bfc0625f966b8462be40318b9020558ed0a3e Mon Sep 17 00:00:00 2001 From: Jorropo Date: Sat, 7 Sep 2024 06:18:22 +0200 Subject: [PATCH] fix getRangingResult to properly account for signed numbers I got numbers like this as I approached the slave (raw values before converting to meters): ``` Ranged: 8 Ranged: 6 Ranged: 3 Ranged: 3 Ranged: 5 Ranged: 5 Ranged: 5 Ranged: 6 Ranged: 1 Ranged: 1 Ranged: 800000 Ranged: 800003 Ranged: 800003 ``` This is because the ToF becomes smaller than the correction factor resulting in a negative number. This patch performs Sign Extension from 24bits to 32bits. This result in returning a negative meter value which makes more sense than an impossibly big one. --- src/modules/SX128x/SX1280.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/modules/SX128x/SX1280.cpp b/src/modules/SX128x/SX1280.cpp index 7692c0a8..a887b801 100644 --- a/src/modules/SX128x/SX1280.cpp +++ b/src/modules/SX128x/SX1280.cpp @@ -176,7 +176,8 @@ float SX1280::getRangingResult() { RADIOLIB_ASSERT(state); // calculate the real result - uint32_t raw = ((uint32_t)data[0] << 16) | ((uint32_t)data[1] << 8) | data[2]; + uint32_t uraw = ((uint32_t)data[0] << 16) | ((uint32_t)data[1] << 8) | data[2]; + int32_t raw = (uraw & ((1<<23) - 1)) | (uraw >> 23 << 31); return((float)raw * 150.0 / (4.096 * this->bandwidthKhz)); }