adc_common.c 1.1 KB

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