here is the battery related code from my battery powered temp sensor. Took a while to get the battery correct. Before this thread I had not seen any other code correcting for battery max / min voltages. I am using the 3.7V li-ion cells which actually seem to top out at 4.2V. I cap the percent at 99 for Vera.
float fmap(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void loop()
{
delay(dht.getMinimumSamplingPeriod());
int sensorValue = analogRead(BATTERY_SENSE_PIN);
// 1M, 330K divider across battery and using internal ADC ref of 1.1V
// Sense point is bypassed with 0.1 uF cap to reduce noise at that point
// ((1e6+330e3)/330e3)*1.1 = Vmax = 4.43 Volts
// 4.43/1023 = Volts per bit = 0.0043336591723688
// 4.2 = 100% 2.5 = 0%
float batteryV = sensorValue * 0.004333659;
float batteryVmap = fabs(fmap(batteryV, 2.5, 4.2, 0.0, 1000.0));
int batteryPcnt = batteryVmap / 10;
if(batteryPcnt >= 100){
batteryPcnt = 99;