im doing a simple code to show battery full/medium/minimum.
board is arduino nano powered by 3.7v lipo battery directly on 5v pin & GND. is my battVolt correct? the "370 - 340 - 310" value?
i copy this code somewhere but the original said for 2x AA battery (1.5v each) and the value is "270 - 240 - 210".
anyway here is my sketch
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <avr/sleep.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
int battVolts;
#define batteryInterval 10000
double lastBatteryTime = 0;
void setup () {
battVolts = getBandgap(); //Determine what actual Vcc is, (X 100), based om known bandgap voltage.
}
// Returns actual value of Vcc (X 100)
int getBandgap(void) {
const long InternalReferenceVoltage = 1056L; // Adjust this value to your boards specific internal BG voltage x1000
// REFS1 REFS0 --> 0 1, AVcc internal ref. -Selects AVcc external reference
// MUX3 MUX2 MUX1 MUX0 --> 1110 1.1V (VBG) -Selects channel 14, bandgap voltage, to measure
ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);
// Start a conversion
ADCSRA |= _BV( ADSC );
// Wait for it to complete
while ( ( (ADCSRA & (1 << ADSC)) != 0 ) );
// Scale the value
int results = (((InternalReferenceVoltage * 1024L) / ADC) + 5L) / 10L; // calculates for straight line value
return results;
}
void loop () {
if (millis() >= lastBatteryTime + batteryInterval) {
lastBatteryTime = millis();
battVolts = getBandgap();
}
display.clearDisplay();
// battery indicator
display.drawRect(119, 5, 6, 8, WHITE);
// battery indicator for 3.7v LiPo.
if (battVolts > 370) {
// full
display.fillRect(120, 5, 4, 7, WHITE);
} else if (battVolts > 340) {
// medium
display.fillRect(120, 8, 4, 5, WHITE);
} else if (battVolts > 310) {
// minimum
display.fillRect(120, 10, 4, 3, WHITE);
} else {
// empty
}
display.display();
}