74 lines
1.6 KiB
C
74 lines
1.6 KiB
C
|
#include "battery.h"
|
||
|
#include <driver/adc.h>
|
||
|
#include <esp_adc_cal.h>
|
||
|
#include <esp_log.h>
|
||
|
#include <soc/adc_channel.h>
|
||
|
|
||
|
|
||
|
static const char* LOG_TAG = "OdroidBattery";
|
||
|
|
||
|
static const adc1_channel_t BATTERY_READ_PIN = ADC1_GPIO36_CHANNEL;
|
||
|
static const gpio_num_t BATTERY_LED_PIN = GPIO_NUM_2;
|
||
|
|
||
|
static esp_adc_cal_characteristics_t gCharacteristics;
|
||
|
|
||
|
void Odroid_InitializeBatteryReader()
|
||
|
{
|
||
|
// Configure LED
|
||
|
{
|
||
|
gpio_config_t gpioConfig = {};
|
||
|
|
||
|
gpioConfig.mode = GPIO_MODE_OUTPUT;
|
||
|
gpioConfig.pin_bit_mask = 1ULL << BATTERY_LED_PIN;
|
||
|
|
||
|
ESP_ERROR_CHECK(gpio_config(&gpioConfig));
|
||
|
}
|
||
|
|
||
|
// Configure ADC
|
||
|
{
|
||
|
adc1_config_width(ADC_WIDTH_BIT_12);
|
||
|
adc1_config_channel_atten(BATTERY_READ_PIN, ADC_ATTEN_DB_11);
|
||
|
adc1_config_channel_atten(BATTERY_READ_PIN, ADC_ATTEN_DB_11);
|
||
|
|
||
|
esp_adc_cal_value_t type = esp_adc_cal_characterize(
|
||
|
ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, &gCharacteristics);
|
||
|
|
||
|
// The ESP32 in the Odroid Go should have its fuse set with a pre-calibrated vref
|
||
|
assert(type == ESP_ADC_CAL_VAL_EFUSE_VREF);
|
||
|
}
|
||
|
|
||
|
ESP_LOGI(LOG_TAG, "Battery reader initialized");
|
||
|
}
|
||
|
|
||
|
uint32_t Odroid_ReadBatteryLevel(void)
|
||
|
{
|
||
|
const int SAMPLE_COUNT = 20;
|
||
|
|
||
|
|
||
|
uint32_t raw = 0;
|
||
|
|
||
|
for (int sampleIndex = 0; sampleIndex < SAMPLE_COUNT; ++sampleIndex)
|
||
|
{
|
||
|
raw += adc1_get_raw(BATTERY_READ_PIN);
|
||
|
}
|
||
|
|
||
|
raw /= SAMPLE_COUNT;
|
||
|
|
||
|
|
||
|
// Voltage divider reports half actual voltage
|
||
|
uint32_t voltage = 2 * esp_adc_cal_raw_to_voltage(raw, &gCharacteristics);
|
||
|
|
||
|
return voltage;
|
||
|
}
|
||
|
|
||
|
void Odroid_EnableBatteryLight(void)
|
||
|
{
|
||
|
gpio_set_level(BATTERY_LED_PIN, 1);
|
||
|
}
|
||
|
|
||
|
void Odroid_DisableBatteryLight(void)
|
||
|
{
|
||
|
gpio_set_level(BATTERY_LED_PIN, 0);
|
||
|
}
|
||
|
|