battery.c 1.5 KB

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