No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

adc.c 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * adc.c
  3. *
  4. * Copyright (c) 2024 Thomas Buck (thomas@xythobuz.de)
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * See <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdio.h>
  19. #include "pico/stdlib.h"
  20. #include "hardware/adc.h"
  21. #include "adc.h"
  22. #define ADC_NUM 2
  23. #define ADC_PIN (26 + ADC_NUM)
  24. #define ADC_VREF 3.3
  25. #define ADC_RANGE (1 << 12)
  26. #define ADC_CONVERT (ADC_VREF / (ADC_RANGE - 1))
  27. #define BAT_R1 10000.0f
  28. #define BAT_R2 18000.0f
  29. #define FILTER_OLD 0.75f
  30. #define FILTER_NEW (1.0f - FILTER_OLD)
  31. static float filtered = 0.0f;
  32. static float bat_read(void) {
  33. float v_adc = adc_read() * ADC_CONVERT;
  34. // Vadc = Vbat * R2 / (R1 + R2)
  35. float v_bat = v_adc / (BAT_R2 / (BAT_R1 + BAT_R2));
  36. return v_bat;
  37. }
  38. void bat_init(void) {
  39. adc_init();
  40. adc_gpio_init( ADC_PIN);
  41. adc_select_input( ADC_NUM);
  42. filtered = bat_read();
  43. }
  44. float bat_get(void) {
  45. filtered = (filtered * FILTER_OLD) + (bat_read() * FILTER_NEW);
  46. return filtered;
  47. }