Skip to content

Commit 72e5ff7

Browse files
drivers: adc: enhance millivolt conversion with 64-bit support
This commit updates the adc_raw_to_millivolts function to use 64-bit arithmetic. It is necessary when the intermediate result is higher than the maximum value of uint32_t. It also adds a range check to ensure the conversion result does not exceed the limits of int32_t, providing an assertion message for out-of-range values. Signed-off-by: Martin Hoff <[email protected]>
1 parent 36bc2f3 commit 72e5ff7

File tree

1 file changed

+8
-3
lines changed
  • include/zephyr/drivers

1 file changed

+8
-3
lines changed

include/zephyr/drivers/adc.h

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,11 +1155,16 @@ typedef int (*adc_raw_to_x_fn)(int32_t ref_mv, enum adc_gain gain, uint8_t resol
11551155
static inline int adc_raw_to_millivolts(int32_t ref_mv, enum adc_gain gain, uint8_t resolution,
11561156
int32_t *valp)
11571157
{
1158-
int32_t adc_mv = *valp * ref_mv;
1159-
int ret = adc_gain_invert(gain, &adc_mv);
1158+
int64_t adc_mv = (int64_t)*valp * (int64_t)ref_mv;
1159+
int ret = adc_gain_invert_64(gain, &adc_mv);
11601160

11611161
if (ret == 0) {
1162-
*valp = (adc_mv >> resolution);
1162+
adc_mv = adc_mv >> resolution;
1163+
if (adc_mv > INT32_MAX || adc_mv < INT32_MIN) {
1164+
__ASSERT_MSG_INFO("conversion result is out of range");
1165+
}
1166+
1167+
*valp = (int32_t)adc_mv;
11631168
}
11641169

11651170
return ret;

0 commit comments

Comments
 (0)