2018-06-02 22:23:50 +02:00
|
|
|
#ifdef HAS_BATTERY_PROBE
|
|
|
|
|
|
|
|
#include "globals.h"
|
|
|
|
#include <driver/adc.h>
|
|
|
|
#include <esp_adc_cal.h>
|
|
|
|
|
2018-06-03 15:20:55 +02:00
|
|
|
#define DEFAULT_VREF 1100 // to be done: use adc2_vref_to_gpio() to obtain a better estimate
|
|
|
|
#define NO_OF_SAMPLES 64 // we do multisampling
|
2018-06-02 22:23:50 +02:00
|
|
|
|
|
|
|
// Local logging tag
|
|
|
|
static const char TAG[] = "main";
|
|
|
|
|
2018-06-03 15:20:55 +02:00
|
|
|
static void print_char_val_type(esp_adc_cal_value_t val_type)
|
|
|
|
{
|
|
|
|
if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) {
|
|
|
|
ESP_LOGI(TAG,"ADC calibration using efuse Two Point Value");
|
|
|
|
} else if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) {
|
|
|
|
ESP_LOGI(TAG,"ADC calibration using eFuse Vref");
|
|
|
|
} else {
|
|
|
|
ESP_LOGI(TAG,"ADC calibration using default Vref");
|
2018-06-02 22:23:50 +02:00
|
|
|
}
|
2018-06-03 15:20:55 +02:00
|
|
|
}
|
2018-06-02 22:23:50 +02:00
|
|
|
|
|
|
|
uint16_t read_voltage(void)
|
|
|
|
{
|
2018-06-03 00:05:53 +02:00
|
|
|
static const adc1_channel_t channel = HAS_BATTERY_PROBE;
|
2018-06-03 14:07:26 +02:00
|
|
|
static const adc_atten_t atten = ADC_ATTEN_DB_11;
|
2018-06-03 00:05:53 +02:00
|
|
|
static const adc_unit_t unit = ADC_UNIT_1;
|
|
|
|
|
2018-06-03 15:20:55 +02:00
|
|
|
//configure ADC1
|
2018-06-03 13:23:03 +02:00
|
|
|
ESP_ERROR_CHECK(adc1_config_width(ADC_WIDTH_BIT_12));
|
|
|
|
ESP_ERROR_CHECK(adc1_config_channel_atten(channel, atten));
|
2018-06-02 22:23:50 +02:00
|
|
|
|
2018-06-03 15:20:55 +02:00
|
|
|
//calibrate ADC1
|
2018-06-02 22:23:50 +02:00
|
|
|
esp_adc_cal_characteristics_t *adc_chars = (esp_adc_cal_characteristics_t *) calloc(1, sizeof(esp_adc_cal_characteristics_t));
|
|
|
|
esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, ADC_WIDTH_BIT_12, DEFAULT_VREF, adc_chars);
|
2018-06-03 15:20:55 +02:00
|
|
|
print_char_val_type(val_type);
|
2018-06-03 15:02:09 +02:00
|
|
|
|
2018-06-03 15:20:55 +02:00
|
|
|
//multisample ADC1
|
2018-06-02 22:23:50 +02:00
|
|
|
uint32_t adc_reading = 0;
|
|
|
|
for (int i = 0; i < NO_OF_SAMPLES; i++) {
|
2018-06-03 00:05:53 +02:00
|
|
|
adc_reading += adc1_get_raw(channel);
|
2018-06-02 22:23:50 +02:00
|
|
|
}
|
2018-06-03 00:05:53 +02:00
|
|
|
|
2018-06-02 22:23:50 +02:00
|
|
|
adc_reading /= NO_OF_SAMPLES;
|
2018-06-03 00:05:53 +02:00
|
|
|
|
2018-06-02 22:23:50 +02:00
|
|
|
//Convert adc_reading to voltage in mV
|
|
|
|
uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, adc_chars);
|
2018-06-03 14:07:26 +02:00
|
|
|
#ifdef BATT_FACTOR
|
|
|
|
voltage *= BATT_FACTOR;
|
|
|
|
#endif
|
2018-06-03 15:02:09 +02:00
|
|
|
ESP_LOGI(TAG,"Raw: %d / Voltage: %dmV", adc_reading, voltage);
|
2018-06-02 22:23:50 +02:00
|
|
|
return voltage;
|
|
|
|
}
|
|
|
|
#endif // HAS_BATTERY_PROBE
|