battery.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #define BATTERY_TIMER (10*1000)
  18. static const char TAG[] = "battery";
  19. #ifdef CONFIG_SQUEEZEAMP
  20. static struct {
  21. float sum, avg;
  22. int count;
  23. TimerHandle_t timer;
  24. } battery;
  25. #endif
  26. /****************************************************************************************
  27. *
  28. */
  29. #ifdef CONFIG_SQUEEZEAMP
  30. static void battery_callback(TimerHandle_t xTimer) {
  31. battery.sum += adc1_get_raw(ADC1_CHANNEL_7) / 4095. * (10+174)/10. * 1.1;
  32. if (++battery.count == 30) {
  33. battery.avg = battery.sum / battery.count;
  34. battery.sum = battery.count = 0;
  35. ESP_LOGI(TAG, "Voltage %.2fV", battery.avg);
  36. }
  37. }
  38. #endif
  39. /****************************************************************************************
  40. *
  41. */
  42. void battery_svc_init(void) {
  43. #ifdef CONFIG_SQUEEZEAMP
  44. ESP_LOGI(TAG, "Initializing battery");
  45. adc1_config_width(ADC_WIDTH_BIT_12);
  46. adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_0);
  47. battery.timer = xTimerCreate("battery", BATTERY_TIMER / portTICK_RATE_MS, pdTRUE, NULL, battery_callback);
  48. xTimerStart(battery.timer, portMAX_DELAY);
  49. #endif
  50. }