Skip to content

Instantly share code, notes, and snippets.

@TotallyInformation
Created October 23, 2013 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TotallyInformation/7116767 to your computer and use it in GitHub Desktop.
Save TotallyInformation/7116767 to your computer and use it in GitHub Desktop.
Read the battery status of an Arduino
long readVcc() {
// Read 1.1V reference against AVcc
// set the reference to Vcc and the measurement to the internal 1.1V reference
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
uint8_t high = ADCH; // unlocks both
long result = (high<<8) | low;
// CALIBRATED FOR SHRIMP ON MID BREADBOARD
/*
Default scale constant = 1125300L
scale_constant = internal1.1Ref * 1023 * 1000
internal1.1Ref = 1.1 * Vcc1 (per voltmeter) / Vcc2 (per readVcc() function)
See: http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
*/
result = 1364000L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
return result; // Vcc in millivolts
}
@fr33z3
Copy link

fr33z3 commented Nov 15, 2022

It seems that writing to ADMUX on low voltage crashes sketch.

@nuxeh
Copy link

nuxeh commented Feb 24, 2023

In my mind this is much clearer, self-documenting code than the common example found on the arduino forum. Works a charm, and makes it quite explicit how to calibrate for a given chip's Vcc, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment