Merge pull request #254 from pyro9/master

Update adc_vbat.ino to also work with nrf52840
This commit is contained in:
hathach authored and GitHub committed 2019-05-06 11:05:58 +07:00
commit bcc41ffcd4
1 file changed
+29 -43
@@ -1,10 +1,21 @@
#define VBAT_PIN (A7)
#define VBAT_MV_PER_LSB (0.73242188F) // 3.0V ADC range and 12-bit ADC resolution = 3000mV/4096
#ifdef NRF52840_XXAA // if this is for nrf52840
#define VBAT_PIN (A6)
#define VBAT_DIVIDER (0.5F) // 150K + 150K voltage divider on VBAT
#define VBAT_DIVIDER_COMP (2.0F) // Compensation factor for the VBAT divider
#else
#define VBAT_PIN (A7)
#define VBAT_DIVIDER (0.71275837F) // 2M + 0.806M voltage divider on VBAT = (2M / (0.806M + 2M))
#define VBAT_DIVIDER_COMP (1.403F) // Compensation factor for the VBAT divider
#endif
int readVBAT(void) {
int raw;
#define REAL_VBAT_MV_PER_LSB (VBAT_DIVIDER_COMP * VBAT_MV_PER_LSB)
float readVBAT(void) {
float raw;
// Set the analog reference to 3.0V (default = 3.6V)
analogReference(AR_INTERNAL_3_0);
@@ -22,38 +33,23 @@ int readVBAT(void) {
analogReference(AR_DEFAULT);
analogReadResolution(10);
return raw;
// Convert the raw value to compensated mv, taking the resistor-
// divider into account (providing the actual LIPO voltage)
// ADC range is 0..3000mV and resolution is 12-bit (0..4095)
return raw * REAL_VBAT_MV_PER_LSB;
}
uint8_t mvToPercent(float mvolts) {
uint8_t battery_level;
if(mvolts<3300)
return 0;
if (mvolts >= 3000)
{
battery_level = 100;
}
else if (mvolts > 2900)
{
battery_level = 100 - ((3000 - mvolts) * 58) / 100;
}
else if (mvolts > 2740)
{
battery_level = 42 - ((2900 - mvolts) * 24) / 160;
}
else if (mvolts > 2440)
{
battery_level = 18 - ((2740 - mvolts) * 12) / 300;
}
else if (mvolts > 2100)
{
battery_level = 6 - ((2440 - mvolts) * 6) / 340;
}
else
{
battery_level = 0;
}
if(mvolts <3600) {
mvolts -= 3300;
return mvolts/30;
}
return battery_level;
mvolts -= 3600;
return 10 + (mvolts * 0.15F ); // thats mvolts /6.66666666
}
void setup() {
@@ -66,23 +62,13 @@ void setup() {
void loop() {
// Get a raw ADC reading
int vbat_raw = readVBAT();
float vbat_mv = readVBAT();
// Convert from raw mv to percentage (based on LIPO chemistry)
uint8_t vbat_per = mvToPercent(vbat_raw * VBAT_MV_PER_LSB);
// Convert the raw value to compensated mv, taking the resistor-
// divider into account (providing the actual LIPO voltage)
// ADC range is 0..3000mV and resolution is 12-bit (0..4095),
// VBAT voltage divider is 2M + 0.806M, which needs to be added back
float vbat_mv = (float)vbat_raw * VBAT_MV_PER_LSB * VBAT_DIVIDER_COMP;
uint8_t vbat_per = mvToPercent(vbat_mv);
// Display the results
Serial.print("ADC = ");
Serial.print(vbat_raw * VBAT_MV_PER_LSB);
Serial.print(" mV (");
Serial.print(vbat_raw);
Serial.print(") ");
Serial.print("LIPO = ");
Serial.print(vbat_mv);
Serial.print(" mV (");