Skip to content

Commit 22a3304

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 9dfac5a commit 22a3304

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
@@ -894,11 +894,16 @@ typedef int (*adc_raw_to_x_fn)(int32_t ref_mv, enum adc_gain gain, uint8_t resol
894894
static inline int adc_raw_to_millivolts(int32_t ref_mv, enum adc_gain gain, uint8_t resolution,
895895
int32_t *valp)
896896
{
897-
int32_t adc_mv = *valp * ref_mv;
898-
int ret = adc_gain_invert(gain, &adc_mv);
897+
int64_t adc_mv = (int64_t)*valp * (int64_t)ref_mv;
898+
int ret = adc_gain_invert_64(gain, &adc_mv);
899899

900900
if (ret == 0) {
901-
*valp = (adc_mv >> resolution);
901+
adc_mv = adc_mv >> resolution;
902+
if (adc_mv > INT32_MAX || adc_mv < INT32_MIN) {
903+
__ASSERT_MSG_INFO("conversion result is out of range");
904+
}
905+
906+
*valp = (int32_t)adc_mv;
902907
}
903908

904909
return ret;

0 commit comments

Comments
 (0)