Declare Variables:
// Battery variables
static byte bPin = A11;
static byte battEn = 4;
// Battery range 3.4 - 4.22v
// Voltage divider resistor values.
float R1 = 10000;
float R2 = 10000;
float vDivider;
float voltage;
int percent;
Put in Setup:
pinMode(battEn, OUTPUT);
Use in Loop:
// Battery measurements and calculations
vDivider = (R2 / (R1 + R2));
digitalWrite(battEn, HIGH);
delay(50);
voltage = analogRead(bPin);
voltage = (voltage / 1024) * 3.35;
voltage = voltage / vDivider;
delay(50);
digitalWrite(battEn, LOW);
percent = (voltage - 3.4) / 0.008;
if (percent > 100) {
percent = 100;
}