#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define OLED display size
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Define I2C address
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Analog pin for battery voltage
#define BATTERY_PIN A0
// Voltage divider resistors (if used)
#define R1 10000 // 10k ohm
#define R2 10000 // 10k ohm
// Maximum and minimum battery voltages
#define MAX_BATTERY_VOLTAGE 4.2
#define MIN_BATTERY_VOLTAGE 3.0
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize OLED display
if (!display.begin( SSD1306_PAGEADDR, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
display.display();
// Display welcome message
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.println(F("Battery Monitor"));
display.display();
delay(2000);
}
void loop() {
// Read analog value
int analogValue = analogRead(BATTERY_PIN);
// Convert to voltage (Assuming a 5V reference and 10-bit ADC)
float voltage = analogValue * (5.0 / 1023.0);
// If using a voltage divider, adjust for the divider ratio
voltage = voltage * ((R1 + R2) / R2);
// Calculate battery capacity percentage
float capacity = map(voltage * 100, MIN_BATTERY_VOLTAGE * 100, MAX_BATTERY_VOLTAGE * 100, 0, 100);
capacity = constrain(capacity, 0, 100);
// Print values to the serial monitor
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.print(" V, Capacity: ");
Serial.print(capacity);
Serial.println(" %");
// Display values on OLED
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Voltage
display.setCursor(0, 0);
display.print(F("Voltage: "));
display.print(voltage, 2);
display.println(F(" V"));
// Capacity
display.setCursor(0, 20);
display.print(F("Capacity: "));
display.print(capacity, 0);
display.println(F(" %"));
// Battery bar
display.drawRect(0, 40, 100, 10, SSD1306_WHITE); // Outer rectangle
display.fillRect(1, 41, capacity, 8, SSD1306_WHITE); // Fill based on capacity
display.display();
delay(1000); // Update every second
}
nano:12
nano:11
nano:10
nano:9
nano:8
nano:7
nano:6
nano:5
nano:4
nano:3
nano:2
nano:GND.2
nano:RESET.2
nano:0
nano:1
nano:13
nano:3.3V
nano:AREF
nano:A0
nano:A1
nano:A2
nano:A3
nano:A4
nano:A5
nano:A6
nano:A7
nano:5V
nano:RESET
nano:GND.1
nano:VIN
nano:12.2
nano:5V.2
nano:13.2
nano:11.2
nano:RESET.3
nano:GND.3
oled1:GND
oled1:VCC
oled1:SCL
oled1:SDA
r1:1
r1:2
r2:1
r2:2