Measuring Arduino Mega voltage

Hello,

I am trying to measure the input voltage on my Arduino Mega clone according to Nick Gammon's page (https://www.gammon.com.au/forum/?id=11497). I measured the constant InternalReferenceVoltage = 1050 and ran the getBandgap function as given on his page. However, I end up with weird numbers on the Serial output:

-235.52 V
-117.76 V
-296.96 V
-235.52 V
0.00 V
1.05 V
1.05 V
1.05 V
-117.76 V
-235.52 V
-117.76 V
-117.76 V
-296.96 V
-235.52 V
-117.76 V
0.00 V
-117.76 V
0.00 V

My laptop would have been dead if it could give out -300 volts :smiley:
There is nothing connected to the Mega.

Do you have any idea what could be going on?

I previously did the same procedure on a Nano and it reliably calculates its Vin, so I am not sure what I could be doing wrong. Is my Mega damaged?

Hi, your link does not work. Please post your code.

Ops, sorry, I got the url name and address reversed. Now it works. Here is the code itself from the IDE:

const long InternalReferenceVoltage = 1050;  // Adjust this value to your board's specific internal BG voltage

void setup(void)
  {
    Serial.begin(115200);    
    // analogReference (INTERNAL);
    // analogReference (INTERNAL1V1); 
    // analogReference (INTERNAL2V56);
    // analogRead (A0);  // force voltage reference to be turned on
  }
    
void loop(void)
  {
    Serial.print(getBandgap () * 0.01);
    Serial.println(" V");
    delay(1000);
  }
 
// Code courtesy of "Coding Badly" and "Retrolefty" from the Arduino forum
// results are Vcc * 100
// So for example, 5V would be 500.
int getBandgap () 
  {
  // REFS0 : Selects AVcc external reference
  // MUX3 MUX2 MUX1 : Selects 1.1V (VBG)  
   ADMUX = bit (REFS0) | bit (MUX3) | bit (MUX2) | bit (MUX1);
   ADCSRA |= bit( ADSC );  // start conversion
   while (ADCSRA & bit (ADSC))
     { }  // wait for conversion to complete
   int results = (((InternalReferenceVoltage * 1024) / ADC) + 5) / 10; 
   return results;
  } // end of getBandgap