Skip to content

Commit 13dfa0a

Browse files
fabiobaltiericarlescufi
authored andcommitted
sensors: shell: implement rounding for q31_t
Since the sensor shell command was converted to use qt31_t, all the integer values started to show up as rounded up by a fractional unit when displayed, due to the conversion always rounding down. Fix that by using the recently introduced DIV_ROUND_CLOSEST and handling rounding up to next integer explicitly. Before: channel idx=44 gauge_state_of_charge value=83.999999 after: channel idx=44 gauge_state_of_charge value=84.000000 Signed-off-by: Fabio Baltieri <[email protected]>
1 parent 409b15c commit 13dfa0a

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

drivers/sensor/sensor_shell.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <zephyr/rtio/rtio.h>
1515
#include <zephyr/shell/shell.h>
1616
#include <zephyr/sys/iterable_sections.h>
17+
#include <zephyr/sys/util.h>
1718

1819
LOG_MODULE_REGISTER(sensor_shell);
1920

@@ -286,8 +287,14 @@ static void sensor_shell_processing_callback(int result, uint8_t *buf, uint32_t
286287

287288
scaled_value = llabs(scaled_value);
288289
numerator = (int)FIELD_GET(GENMASK64(31 + shift, 31), scaled_value);
289-
denominator =
290-
(int)((FIELD_GET(GENMASK64(30, 0), scaled_value) * 1000000) / INT32_MAX);
290+
denominator = (int)DIV_ROUND_CLOSEST(
291+
FIELD_GET(GENMASK64(30, 0), scaled_value) * 1000000,
292+
INT32_MAX);
293+
294+
if (denominator == 1000000) {
295+
numerator++;
296+
denominator = 0;
297+
}
291298

292299
if (channel >= ARRAY_SIZE(sensor_channel_name)) {
293300
shell_print(ctx->sh, "channel idx=%d value=%s%d.%06d", channel,

0 commit comments

Comments
 (0)