#include <Wire.h> //เรียกใช้I2Cของesp32
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);
//(ขนาดจอ128*64ต่อที่ขาที่เท่าไร)
// Battery icon bitmap (replace with your own bitmap)
#define batteryIconWidth 24
#define batteryIconHeight 12
const unsigned char battful [] = {
0xFF, 0xFF, 0xF8, 0x80, 0x00, 0x08, 0xBE, 0xFB, 0xE8, 0xBE, 0xFB, 0xE8, 0xBE, 0xFB, 0xEC, 0xBE,
0xFB, 0xEC, 0xBE, 0xFB, 0xEC, 0xBE, 0xFB, 0xEC, 0xBE, 0xFB, 0xE8, 0xBE, 0xFB, 0xE8, 0x80, 0x00,
0x08, 0xFF, 0xFF, 0xF8,
};
const unsigned char batthalf [] = {
0xFF, 0xFF, 0xF8, 0x80, 0x00, 0x08, 0xBE, 0xFB, 0xE8, 0xBE, 0xFA, 0x28, 0xBE, 0xFA, 0x2C, 0xBE,
0xFA, 0x2C, 0xBE, 0xFA, 0x2C, 0xBE, 0xFA, 0x2C, 0xBE, 0xFA, 0x28, 0xBE, 0xFB, 0xE8, 0x80, 0x00,
0x08, 0xFF, 0xFF, 0xF8,
};
const unsigned char battlow [] = {
0xFF, 0xFF, 0xF8, 0x80, 0x00, 0x08, 0xBE, 0xFB, 0xE8, 0xBE, 0x8A, 0x28, 0xBE, 0x8A, 0x2C, 0xBE,
0x8A, 0x2C, 0xBE, 0x8A, 0x2C, 0xBE, 0x8A, 0x2C, 0xBE, 0x8A, 0x28, 0xBE, 0xFB, 0xE8, 0x80, 0x00,
0x08, 0xFF, 0xFF, 0xF8,
};
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextColor(WHITE, BLACK);
display.setCursor(64, 100);
display.print("hello");
display.display();
}
void drawBatteryIcon_full(uint8_t x, uint8_t y) {
display.drawBitmap(x, y, battful, batteryIconWidth, batteryIconHeight, SSD1306_WHITE);
}
void drawBatteryIcon_half(uint8_t x, uint8_t y) {
display.drawBitmap(x, y, batthalf, batteryIconWidth, batteryIconHeight, SSD1306_WHITE);
}
void drawBatteryIcon_low(uint8_t x, uint8_t y) {
display.drawBitmap(x, y, battlow, batteryIconWidth, batteryIconHeight, SSD1306_WHITE);
}
void loop() {
// Read the battery voltage in millivolts
int batteryVoltage = analogRead(A0); // Connect battery voltage divider to A0
// Convert the analog reading to actual voltage
float voltage = (batteryVoltage / 4095.0) * 3.3 * 2; // Assuming a voltage divider factor of 2
// Calculate the battery percentage (adjust as needed)
int batteryPercentage = map(voltage, 3.0, 4.2, 0, 100);
// Display the battery icon and percentage on the OLED
display.clearDisplay();
if (voltage > 3.20)
{
drawBatteryIcon_full(0, 0); // Display battery icon at (0, 0)
}
else if (voltage > 2.85)
{
drawBatteryIcon_half(0, 0); // Display battery icon at (0, 0)
}
else
{
drawBatteryIcon_low(0, 0); // Display battery icon at (0, 0)
}
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(batteryIconWidth + 4, 0);
display.print(F("Battery:"));
display.setCursor(batteryIconWidth + 4, 10);
display.print(voltage);
display.print(F("V"));
display.display();
// Print the battery percentage to the Serial Monitor
Serial.print(F("Battery Percentage: "));
Serial.print(voltage);
Serial.println(F("V"));
delay(1000); // Delay for 1 second (adjust as needed)
}