#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); // initalize the display
unsigned long millis_time; // fps
unsigned long millis_time_last; // fps
int fps; // actual FPS value
char fps_buffer[10]; // buffer for converting FPS to string
const uint8_t BATTERY_BOX_START_X = 100;
const uint8_t BATTERY_BOX_START_Y = 2;
const uint8_t BATTERY_BOX_WIDTH = 23;
const uint8_t BATTERY_BOX_HEIGHT = 6;
const uint8_t BATTERY_CHG_OFFSET = 5;
// A variable to test our code.
uint8_t percent = 100;
// This is the battery fill mode
// BATTERY_MODE_SOLID = 1 means the battery bitmap will be filled with
// a solid rectangle according to the battery charge.
// BATTERY_MODE_SOLID = 0 means the battery will be filled with a
// rectangle subdivided in 3. If the battery level is 66% or more, it will
// draw 3 rectangles. If it's 33% or more, it will draw 2 rectangles. It will
// draw 1 rectagle if the battery is less than 33%.
#define BATTERY_MODE_SOLID 1
// This is the main function, and the one you will want to transplant to your
// code. Pass the battery charge percent and it will draw the battery with
// the corresponding charge level.
void showBatteryLevel(uint8_t percent)
{
uint8_t width;
if (percent > 100) {
percent = 100;
}
if (BATTERY_MODE_SOLID)
{
width = (percent * BATTERY_BOX_WIDTH) / 100;
u8g2.drawBox(BATTERY_BOX_START_X, BATTERY_BOX_START_Y, width, BATTERY_BOX_HEIGHT);
u8g2.drawBox(126,3,2,4);
u8g2.drawFrame(BATTERY_BOX_START_X-2,0,27,10);
}
else
{
uint8_t bars;
if (percent >= 66)
{
// Show three bars
bars = 3;
} else if (percent >= 33)
{
// Show two bars
bars = 2;
} else if (percent > 0)
{
// Show one bar
bars = 1;
} else {
// Show nothing
bars = 0;
}
uint8_t offset = BATTERY_BOX_START_X;
for (uint8_t i = 0; i < bars; i++)
{
u8g2.drawBox(offset, BATTERY_BOX_START_Y, 15, BATTERY_BOX_HEIGHT);
offset += BATTERY_CHG_OFFSET;
}
}
//u8g2.sendBuffer();
}
void setup(void)
{
u8g2.begin(); // initialize u8g2 drawing
u8g2.setFont(u8g2_font_chargen_92_tr); // set U8G font
}
void loop(void)
{
u8g2.clearBuffer(); // clear U8G2 drawing buffer
u8g2.setDrawColor(1); // white color
// Some test code to scan all the battery levels
showBatteryLevel(percent);
if (percent)
percent--;
else
percent = 100;
u8g2.sendBuffer(); // send U8G2 buffer to the display
// calculate the FPS
millis_time_last = millis_time; // store last millisecond value
millis_time = millis(); // get millisecond value from the start of the program
fps = round(1000.0/ (millis_time*1.0-millis_time_last)); // calculate FPS (frames per second) value
}