battery.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include <string.h>
  11. #include "freertos/FreeRTOS.h"
  12. #include "freertos/timers.h"
  13. #include "esp_system.h"
  14. #include "esp_log.h"
  15. #include "driver/adc.h"
  16. #include "battery.h"
  17. /*
  18. There is a bug in esp32 which causes a spurious interrupt on gpio 36/39 when
  19. using ADC, AMP and HALL sensor. Rather than making battery aware, we just ignore
  20. if as the interrupt lasts 80ns and should be debounced (and the ADC read does not
  21. happen very often)
  22. */
  23. #define BATTERY_TIMER (10*1000)
  24. static const char *TAG = "battery";
  25. static struct {
  26. float sum, avg;
  27. int count;
  28. TimerHandle_t timer;
  29. } battery;
  30. /****************************************************************************************
  31. *
  32. */
  33. int battery_value_svc(void) {
  34. return battery.avg;
  35. }
  36. /****************************************************************************************
  37. *
  38. */
  39. #ifdef CONFIG_SQUEEZEAMP
  40. static void battery_callback(TimerHandle_t xTimer) {
  41. battery.sum += adc1_get_raw(ADC1_CHANNEL_7) / 4095. * (10+174)/10. * 1.1;
  42. if (++battery.count == 30) {
  43. battery.avg = battery.sum / battery.count;
  44. battery.sum = battery.count = 0;
  45. ESP_LOGI(TAG, "Voltage %.2fV", battery.avg);
  46. }
  47. }
  48. #endif
  49. /****************************************************************************************
  50. *
  51. */
  52. void battery_svc_init(void) {
  53. #ifdef CONFIG_SQUEEZEAMP
  54. ESP_LOGI(TAG, "Initializing battery");
  55. adc1_config_width(ADC_WIDTH_BIT_12);
  56. adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_0);
  57. battery.timer = xTimerCreate("battery", BATTERY_TIMER / portTICK_RATE_MS, pdTRUE, NULL, battery_callback);
  58. xTimerStart(battery.timer, portMAX_DELAY);
  59. #endif
  60. }