1 /*
2 * Copyright (c) 2019 Peter Bigot Consulting, LLC
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/drivers/adc.h>
8
adc_gain_invert(enum adc_gain gain,int32_t * value)9 int adc_gain_invert(enum adc_gain gain,
10 int32_t *value)
11 {
12 struct gain_desc {
13 uint8_t mul;
14 uint8_t div;
15 };
16 static const struct gain_desc gains[] = {
17 [ADC_GAIN_1_6] = {.mul = 6, .div = 1},
18 [ADC_GAIN_1_5] = {.mul = 5, .div = 1},
19 [ADC_GAIN_1_4] = {.mul = 4, .div = 1},
20 [ADC_GAIN_1_3] = {.mul = 3, .div = 1},
21 [ADC_GAIN_2_5] = {.mul = 5, .div = 2},
22 [ADC_GAIN_1_2] = {.mul = 2, .div = 1},
23 [ADC_GAIN_2_3] = {.mul = 3, .div = 2},
24 [ADC_GAIN_4_5] = {.mul = 5, .div = 4},
25 [ADC_GAIN_1] = {.mul = 1, .div = 1},
26 [ADC_GAIN_2] = {.mul = 1, .div = 2},
27 [ADC_GAIN_3] = {.mul = 1, .div = 3},
28 [ADC_GAIN_4] = {.mul = 1, .div = 4},
29 [ADC_GAIN_6] = {.mul = 1, .div = 6},
30 [ADC_GAIN_8] = {.mul = 1, .div = 8},
31 [ADC_GAIN_12] = {.mul = 1, .div = 12},
32 [ADC_GAIN_16] = {.mul = 1, .div = 16},
33 [ADC_GAIN_24] = {.mul = 1, .div = 24},
34 [ADC_GAIN_32] = {.mul = 1, .div = 32},
35 [ADC_GAIN_64] = {.mul = 1, .div = 64},
36 [ADC_GAIN_128] = {.mul = 1, .div = 128},
37 };
38 int rv = -EINVAL;
39
40 if ((uint8_t)gain < ARRAY_SIZE(gains)) {
41 const struct gain_desc *gdp = &gains[gain];
42
43 if ((gdp->mul != 0) && (gdp->div != 0)) {
44 *value = (gdp->mul * *value) / gdp->div;
45 rv = 0;
46 }
47 }
48
49 return rv;
50 }
51