#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

#define OLED_RESET    -1
#define SCREEN_ADDRESS 0x3C // Change this address if necessary, commonly 0x3D or 0x3C

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int batteryPin = A0; // Analog pin connected to the potentiometer
int batteryLevel = 0; // Initialize battery level variable

void setup() {
  pinMode(batteryPin, INPUT);
  Serial.begin(9600);

  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ;
  }
  display.display();
  delay(2000);
  display.clearDisplay();
}

void loop() {
  // Read the analog value from the potentiometer
  int potValue = analogRead(batteryPin);

  // Map the analog value to the battery level (0-100%)
  batteryLevel = map(potValue, 0, 1023, 0, 100);

  // Clear the previous contents of the display
  display.clearDisplay();

  // Display battery icon (a simple rectangle)
  int batteryWidth = map(batteryLevel, 0, 100, 0, SCREEN_WIDTH / 2);
  display.fillRect(SCREEN_WIDTH - batteryWidth, 0, batteryWidth, 10, SSD1306_WHITE);
  display.drawRect(SCREEN_WIDTH / 2 - 1, 0, SCREEN_WIDTH / 2 + 1, 10, SSD1306_WHITE);
  
  // Display battery level percentage
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 15);
  display.print("Battery Level: ");
  display.print(batteryLevel);
  display.print("%");

  // Update the display
  display.display();

  // Print battery level to serial monitor for debugging
  Serial.print("Battery Level: ");
  Serial.print(batteryLevel);
  Serial.println("%");

  delay(1000); // Update the display every second
}