|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <esp_log.h> |
| 8 | +#include <esp_adc/adc_oneshot.h> |
| 9 | +#include "ble_hid.h" |
| 10 | +#include "bsp/esp-bsp.h" |
| 11 | +#include "battery_adc.h" |
| 12 | +#include "adc_battery_estimation.h" |
| 13 | + |
| 14 | +static const char *TAG = "BATTERY-ADC"; |
| 15 | + |
| 16 | +static TaskHandle_t battery_monitor_task_handle; |
| 17 | +static void battery_monitor_task(void *pvParameters); |
| 18 | + |
| 19 | +/* Pull up resistor value. Unit: KOhm */ |
| 20 | +#define PULL_UP_RESISTOR (51) |
| 21 | +/* Pull down resistor value. Unit: KOhm */ |
| 22 | +#define PULL_DOWN_RESISTOR (100) |
| 23 | + |
| 24 | +esp_err_t battery_adc_init(void) |
| 25 | +{ |
| 26 | + if (battery_monitor_task_handle != NULL) { |
| 27 | + ESP_LOGW(TAG, "Battery monitor task already created! "); |
| 28 | + return ESP_OK; |
| 29 | + } |
| 30 | + |
| 31 | + if (xTaskCreate(battery_monitor_task, "battery_monitor", 4096, NULL, 2, &battery_monitor_task_handle) != pdPASS) { |
| 32 | + return ESP_ERR_NO_MEM; |
| 33 | + } |
| 34 | + |
| 35 | + return ESP_OK; |
| 36 | +} |
| 37 | + |
| 38 | +static void battery_monitor_task(void *pvParameters) |
| 39 | +{ |
| 40 | + ESP_UNUSED(pvParameters); |
| 41 | + adc_battery_estimation_t config = { |
| 42 | + .internal = { |
| 43 | + .adc_unit = KBD_BATTERY_MONITOR_ADC_UNIT, |
| 44 | + .adc_bitwidth = ADC_BITWIDTH_DEFAULT, |
| 45 | + /* Theoretical battery voltage measurement range is about 2.45 to 2.78V. |
| 46 | + * So set the input attenuation to 12 dB (about 4x) */ |
| 47 | + .adc_atten = ADC_ATTEN_DB_12 |
| 48 | + }, |
| 49 | + .adc_channel = KBD_BATTERY_MONITOR_CHANNEL, |
| 50 | + .lower_resistor = PULL_DOWN_RESISTOR, |
| 51 | + .upper_resistor = PULL_UP_RESISTOR, |
| 52 | + }; |
| 53 | + |
| 54 | + adc_battery_estimation_handle_t adc_battery_estimation_handle = adc_battery_estimation_create(&config); |
| 55 | + if (adc_battery_estimation_handle == NULL) { |
| 56 | + ESP_LOGE(TAG, "Initialize adc battery estimation failed! "); |
| 57 | + vTaskDelete(battery_monitor_task_handle); |
| 58 | + vTaskDelay(portMAX_DELAY); |
| 59 | + } |
| 60 | + |
| 61 | + float capacity = 0.0f; |
| 62 | + |
| 63 | + while (1) { |
| 64 | + adc_battery_estimation_get_capacity(adc_battery_estimation_handle, &capacity); |
| 65 | + ble_hid_battery_report((int) capacity); |
| 66 | + |
| 67 | + /* Sample period. */ |
| 68 | + vTaskDelay(pdMS_TO_TICKS(10000)); |
| 69 | + } |
| 70 | +} |
0 commit comments