Skip to content

Commit b7bbee8

Browse files
authored
add src
1 parent 370977a commit b7bbee8

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/CPUVolt.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*\ =========================================================================
2+
|*|
3+
|*| CPUVolt.cpp
4+
|*|
5+
|*| Function to use the internal registers in the ATMega cpu to calculate
6+
|*| the processors AVcc:
7+
|*|
8+
|*| =========================================================================
9+
\*/
10+
11+
#include <avr/io.h>
12+
#include <Arduino.h>
13+
14+
#include "CPUVolt.h"
15+
16+
signed long readVcc() {
17+
// Read 1.1V reference against AVcc
18+
// Set the reference to Vcc and the measurement to the internal 1.1V reference
19+
20+
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
21+
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
22+
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
23+
ADMUX = _BV(MUX5) | _BV(MUX0);
24+
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
25+
ADMUX = _BV(MUX3) | _BV(MUX2);
26+
#else
27+
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
28+
#endif
29+
30+
delay(2); // Wait for Vref to settle
31+
ADCSRA |= _BV(ADSC); // Start conversion
32+
while (bit_is_set(ADCSRA, ADSC)); // measuring
33+
34+
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
35+
uint8_t high = ADCH; // unlocks both
36+
37+
long result = (high << 8) | low; // convert to 32 bit signed value
38+
39+
result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1 * 1023 * 1000
40+
return result; // Vcc in millivolts
41+
}

src/CPUVolt.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*\ =========================================================================
2+
|*|
3+
|*| Library to use the internal registers in the ATMega cpu to calculate
4+
|*| the processor's Vcc voltage:
5+
|*|
6+
|*| =========================================================================
7+
\*/
8+
9+
#ifndef CPUVOLT_H_INC
10+
#define CPUVOLT_H_INC
11+
12+
signed long readVcc();
13+
14+
#endif

0 commit comments

Comments
 (0)