EasyManua.ls Logo

Freenove ESP32 - Page 88

Default Icon
159 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Need support? support@freenove.com
86
Chapter 6 Battery
www.freenove.com
BatteryPower.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "BatteryPower.h"
void setupAdc(){
analogReadResolution(12);
analogSetAttenuation(ADC_11db);
adcAttachPin(PIN_ANALOG_IN);
}
uint32_t getBatteryVoltage(){
uint32_t adc_reading = 0;
for (int i = 0; i < NUM_OF_SAMPLES; i++){
adc_reading += analogRead(PIN_ANALOG_IN);
}
adc_reading /= NUM_OF_SAMPLES;
uint32_t voltage = adc_reading*3300/4096;
return voltage * VOLATAGE_RATIO;
}
ADC data sampling accuracy setting. Here it is set to 12 bits. 2^12=4096, so the sampling data range of ADC
is 0-4095.
4
analogReadResolution(12);
ADC sampling voltage range setting of ESP32, which is 0-3.3V. ADC_11db represents the maximum range.
Combined with the above analogReadResolution() function, when the voltage of the ADC collection point is
0V, the value collected by the ADC is 0; when the voltage of the ADC collection point is 3.3V, the value
collected by the ADC is 4095.
5
analogSetAttenuation(ADC_11db);
Associate the ADC configuration to the pin.
6
adcAttachPin(PIN_ANALOG_IN);
Use analogRead(PIN_ANALOG_IN) to capture the ADC value at the ESP32 pin.
Continuously collect NUM_OF_SAMPLES ADC values at the ESP32 pins and calculate the average.
10
11
12
13
14
uint32_t adc_reading = 0;
for (int i = 0; i < NUM_OF_SAMPLES; i++){
adc_reading += analogRead(PIN_ANALOG_IN);
}
adc_reading /= NUM_OF_SAMPLES;
Convert the ADC value to the actual measured voltage value. The unit is millivolts.
15
uint32_t voltage = adc_reading*3300/4096;
We know from the previous introduction that the voltage at the ESP32 pin is 1/4 of the battery voltage.
Therefore, the voltage value of the battery can be obtained by multiplying the voltage value measured by the
ADC by VOLATAGE_RATIO(4).
16
return voltage * VOLATAGE_RATIO;

Related product manuals