Skip to content

Instantly share code, notes, and snippets.

@rafacouto
Created February 10, 2020 01:39
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 rafacouto/71b7439174a11d4f74a14f2bc935b2fe to your computer and use it in GitHub Desktop.
Save rafacouto/71b7439174a11d4f74a14f2bc935b2fe to your computer and use it in GitHub Desktop.
#include <Arduino.h>
#include <stdint.h>
#include <avr/io.h>
uint16_t vcc_millivolts(uint8_t delay_us = 50)
{
// select AVCC as reference and switch the internal band-gap (1.1V)
ADMUX = 0b01011110;
// stabilize input
_delay_us(delay_us);
// start ADC conversion and wait to finish
ADCSRA |= (1 << ADSC);
while (!(ADCSRA & (1 << ADIF)));
// AVCC = Vbg * 1023 / ADC
return (1100UL * 1023) / ADC;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(vcc_millivolts(), DEC);
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment