 # Measuring the voltage of the power supply with MEGA2560

Hello everyone,

I have a remote control powered by batteries delivering a voltage between 3.6 up to 5V. A Pololu stepup converter is used to generate a stable 9V for Vin of the MEGA2560. A Nextion 4.3" display(IN = 80 mA continous) is connected with the 5V GND of the MEGA2560 and a HC12 module (IH = 80 mA max) with 3.3V GND. Everything works properly. Now I want to display the charge status of the battery on the Nextion display. As test I flashed the following sketch

``````int analogInput = 1;
int refresh = 1000;
int vout = 0;
int vin = 0;
int value = 0;

float R1 = 0.0;    // R1
float R2 = 1.0;     // R2

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

void loop(){

if (value >= 1023) {
Serial.println("Maximum value reached!!");
delay(refresh);
return;
}
else if (value <= 0) {
Serial.println("No voltage!!");
delay(refresh);
return;
}

vout = (value * readVcc() / 1000) / 1024.0;
vin = vout / (R2/(R1+R2));
Serial.print(vin);
Serial.println(" volt");
delay(refresh);
}

long result;
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2);
result = 1126400L / result;
return result;
}
``````

I put the battery + to analogue input 1. I checked by measurement that the GNDs of the step up converter are connected.
As example result I get the following from the serial monitor
187733
0 volt
160914
522 volt
563200
209 volt
375466
209 volt
281600
523 volt
281600
523 volt
563200
348 volt
1101
149 volt
225280
261 volt
281600
174 volt
-1
174 volt
281600
174 volt
1101
209 volt

When measuring the battery voltage directly with a voltmeter I get a stable 4.57 V. This does not comply with the monitor results which seem to be more randomly generated. Now I am confused if it is a programming or a circuit issue. Can someone help me out? PS. The resistors R1 and R2 are left out since the voltage is below 5V and battery can be charged via USB supply.