18 lines
603 B
C
18 lines
603 B
C
#define ADC_PIN 10 // GPIO10 on WEMOS S2 Mini
|
|
|
|
const float R1 = 100000.0; // 100k ohms
|
|
const float R2 = 47000.0; // 47k ohms
|
|
const float ADC_MAX = 4095.0; // 12-bit ADC resolution
|
|
const float V_REF = 3.3; // Reference voltage for ESP32-S2 ADC
|
|
|
|
float readBatteryVoltage() {
|
|
int rawADC = analogRead(ADC_PIN);
|
|
float voltage = (rawADC / ADC_MAX) * V_REF;
|
|
return voltage * (R1 + R2) / R2; // Scale to actual battery voltage
|
|
}
|
|
|
|
int batteryPercentage(float voltage) {
|
|
if (voltage >= 4.2) return 100;
|
|
if (voltage <= 3.0) return 0;
|
|
return (voltage - 3.0) * 100 / (4.2 - 3.0); // Linear mapping
|
|
} |