Thank You for You suggestions and update on the sketch.
The batteries can discharge in -20 / +55 deg. If the rover operate on the field, then the temperature can make a significant impact on battery capacity.
Just to make the study complete:
For external reference voltage version, I followed this
link and made a schematic for 12V version.
Is used for Analog Pin A1. So analogReference(INTERNAL2V56); obsoleted.
The data sheet for LM 4040 is attached. The script can be figured out.
Now I turned my attention to septillion's easy calibration proposal.
Let say initially I have 12.1V on battery (measured with DMM).
After voltage divider: UA0 = 12.1V * 10k * (10k + 47k) = 2.122V
If I run separately analogRead(BatVoltPin) this will give somewhere adcValue = 434.
If during the operation, I get let say adcValue' = 378, due to linearity:
12.1V/434 = Vcc/378 -> Vcc = 12.1V * 378 / 434 = 10.538 V (actual battery voltage during operation)
The updated sketch for Your kind consideration and review:
const unsigned long BatVIni = 12100; //mV measure only one time, when connected to the circuit
const unsigned long AdcValueIni = 434; // to get, run once separately analogRead(BatVoltPin),
// in the same time when BatVini measured. Only one time required.
const unsigned long BatRatio = BatVIni / AdcValueIni;
const unsigned long BatVoltMax = 13500; //mV
const unsigned long BatVoltMin = 10400; //mV
const byte BatVoltPin = A0; //Analog pin # A0
const unsigned int NrSamples = 1000; // Usually from 5 to 10000
byte batteryPercentage() {
unsigned int adcValue = averageRead(BatVoltPin); // let say it is 378
unsigned int batVoltage = adcValue * BatRatio; //mV; let say it is 10538 mV
Serial.print("Batery voltage [mV]: ");
Serial.println(batVoltage);
byte percentage = 100 * (batVoltage - batVolt_Min) / (batVolt_Max - batVolt_Min); // to be improved
Serial.print("Battery level [%]: "); //<= statement ends, next line please!
Serial.println(percentage);
return percentage;
}
unsigned int averageRead(byte pin){
unsigned long total = 0;
for(unsigned int i = 0; i < NrSamples; i++)
{
total += analogRead(pin);
}
total += nSamples / 2; // add half a bit
return (total / NrSamples);
}
