# Internal volts in arduino for percent battery

I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0% and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.

``````long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.println( readVcc(), DEC );
delay(1000);
}
``````
• Are we talking about the calculation X = (V - 3)* 100/(4.2 - 3) where V is the voltage (in volts) and X is the percentage? When V = 3 this gives X = 0, when V = 4.2 this gives X = 100
– JIm Dearden
Sep 2, 2014 at 20:21
• @jim readVCC() returns a voltage in mV, so adjust for that and add as a answer :D
– Passerby
Sep 2, 2014 at 20:38
• Mind you that the band gap reference is reasonably stable over time, but its absolute value in not very accurate. You may want to 'calibrate' the returned result from your readVcc function. Sep 2, 2014 at 21:00
• The charge on my arduino and something I'm doing wrong it gives me error :-( Sep 2, 2014 at 21:38
• Where did the code you posted come from? That's some pretty cryptic code. Sep 3, 2014 at 1:19

`map()`
``````unsigned char level = map(readVcc(), 3000, 4200, 0, 100);