#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define OLED display parameters
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin is not used in I2C mode
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Define analog pin and voltage divider ratio
#define BATTERY_PIN 34 // ADC pin where battery voltage is read
#define VOLTAGE_DIVIDER_RATIO 3.0 // Assuming a 12V battery and a divider that scales it down
// Battery voltage limits
#define BATTERY_MIN_VOLTAGE 1.5
#define BATTERY_MAX_VOLTAGE 13.5
void setup() {
// Initialize serial for debugging
Serial.begin(115200);
// Initialize OLED display with I2C address 0x3C
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Loop forever if the display cannot be initialized
}
// Clear the display buffer
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
}
void loop() {
// Read the raw analog value from the battery pin
int rawValue = analogRead(BATTERY_PIN);
// Convert raw value to actual battery voltage
float batteryVoltage = rawValue / 4095.0 * 3.3 * VOLTAGE_DIVIDER_RATIO;
// Calculate the battery level as a percentage
float batteryLevel = (batteryVoltage - BATTERY_MIN_VOLTAGE) / (BATTERY_MAX_VOLTAGE - BATTERY_MIN_VOLTAGE) * 100;
if (batteryLevel > 100) batteryLevel = 100;
if (batteryLevel < 0) batteryLevel = 0;
// Display battery voltage and percentage on the OLED
display.clearDisplay();
display.setCursor(0, 0);
display.print("Battery Voltage: ");
display.print(batteryVoltage);
display.println("V");
display.setCursor(0, 20);
display.print("Battery Level: ");
display.print(batteryLevel);
display.println("%");
// Draw a battery level bar
int barWidth = batteryLevel / 100.0 * 100;
display.drawRect(0, 40, 100, 10, WHITE); // Battery bar outline
display.fillRect(0, 40, barWidth, 10, WHITE); // Filled battery bar
display.display();
// Print values for debugging on the Serial Monitor
Serial.print("Battery Voltage: ");
Serial.print(batteryVoltage);
Serial.print(" V, ");
Serial.print("Battery Level: ");
Serial.print(batteryLevel);
Serial.println("%");
// Delay for a short period before reading again
delay(1000);
}