Last active
July 31, 2019 20:54
-
-
Save tomazas/7452454b798a11e05ec3ef4deeaccfe2 to your computer and use it in GitHub Desktop.
Example of measuring atmega VCC using the bandgap method (no external hardware or voltage divider needed).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example of measuring atmega VCC using the bandgap method (no external hardware or voltage divider needed). | |
Based on: https://jeelabs.org/2012/05/04/measuring-vcc-via-the-bandgap/ | |
*/ | |
// Arduino Nano / Atmega328 tested | |
static int vccRead () { | |
ADMUX = bit(REFS0) | 14; // use Vref=VCC and measure internal bandgap channel 1.1V | |
delayMicroseconds(250); // wait for bandgap to stabilize | |
bitSet(ADCSRA, ADEN); // enable ADC | |
bitSet(ADCSRA, ADSC); // start conversion | |
while (ADCSRA & (1<<ADSC)); // wait till conversion stops | |
return ADC; // return value in 0-1023 range | |
} | |
void setup() { | |
Serial.begin(9600); | |
Serial.println("bandgap:"); | |
} | |
// adc = 1100 / vcc * 1024 | |
void loop() { | |
byte x = vccRead(); | |
Serial.print("vcc="); | |
Serial.println(1100 * 1023L / x); // power supply (VCC) voltage | |
delay(500); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment