Skip to content

Commit 46e3b96

Browse files
committed
drivers: adc: fix mV conversion error with high resolution ADC data
Fix the overflow encountered with too high resolution ADC output data when using adc_raw_to_millivolts. This is done by using int64_t instead of a int32_t for the internal computations. Signed-off-by: Johan Lafon <[email protected]>
1 parent 40cd35e commit 46e3b96

File tree

3 files changed

+5
-5
lines changed

3 files changed

+5
-5
lines changed

drivers/adc/adc_common.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
#include <zephyr/drivers/adc.h>
88

99
int adc_gain_invert(enum adc_gain gain,
10-
int32_t *value)
10+
int64_t *value)
1111
{
1212
struct gain_desc {
1313
uint8_t mul;

drivers/adc/adc_emul.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ static int adc_emul_get_chan_value(struct adc_emul_data *data,
406406
{
407407
struct adc_emul_chan_cfg *chan_cfg = &data->chan_cfg[chan];
408408
uint32_t input_mV;
409-
uint32_t ref_v;
409+
uint64_t ref_v;
410410
uint64_t temp; /* Temporary 64 bit value prevent overflows */
411411
int err = 0;
412412

include/zephyr/drivers/adc.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ enum adc_gain {
7171
* @retval -EINVAL if the gain could not be interpreted
7272
*/
7373
int adc_gain_invert(enum adc_gain gain,
74-
int32_t *value);
74+
int64_t *value);
7575

7676
/** @brief ADC references. */
7777
enum adc_reference {
@@ -880,11 +880,11 @@ static inline int adc_raw_to_millivolts(int32_t ref_mv,
880880
uint8_t resolution,
881881
int32_t *valp)
882882
{
883-
int32_t adc_mv = *valp * ref_mv;
883+
int64_t adc_mv = ((uint64_t) *valp) * ref_mv;
884884
int ret = adc_gain_invert(gain, &adc_mv);
885885

886886
if (ret == 0) {
887-
*valp = (adc_mv >> resolution);
887+
*valp = (uint32_t) (adc_mv >> resolution);
888888
}
889889

890890
return ret;

0 commit comments

Comments
 (0)