-
Notifications
You must be signed in to change notification settings - Fork 35
/
Vcc.cpp
78 lines (61 loc) · 2.43 KB
/
Vcc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Vcc - A supply voltage measuring library for Arduino
Created by Ivo Pullens, Emmission, 2014
Inspired by:
http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Vcc.h"
Vcc::Vcc( const float correction )
: m_correction(correction)
{
}
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define ADMUX_VCCWRT1V1 (_BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1))
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
#define ADMUX_VCCWRT1V1 (_BV(MUX5) | _BV(MUX0))
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
#define ADMUX_VCCWRT1V1 (_BV(MUX3) | _BV(MUX2))
#else
#define ADMUX_VCCWRT1V1 (_BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1))
#endif
float Vcc::Read_Volts(void)
{
// Read 1.1V reference against AVcc
// set the reference to Vcc and the measurement to the internal 1.1V reference
if (ADMUX != ADMUX_VCCWRT1V1)
{
ADMUX = ADMUX_VCCWRT1V1;
// Bandgap reference start-up time: max 70us
// Wait for Vref to settle.
delayMicroseconds(350);
}
// Start conversion and wait for it to finish.
ADCSRA |= _BV(ADSC);
while (bit_is_set(ADCSRA,ADSC)) {};
// Result is now stored in ADC.
// Calculate Vcc (in V)
float vcc = 1.1*1024.0 / ADC;
// Apply compensation
vcc *= m_correction;
return vcc;
}
float Vcc::Read_Perc(const float range_min, const float range_max, const boolean clip)
{
// Read Vcc and convert to percentage
float perc = 100.0 * (Read_Volts()-range_min) / (range_max-range_min);
// Clip to [0..100]% range, when requested.
if (clip)
perc = constrain(perc, 0.0, 100.0);
return perc;
}