#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define TEXT_LEFT 0
#define TEXT_CENTER 1
#define TEXT_RIGHT 2
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO: A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO: 2(SDA), 3(SCL), ...
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void drawTextAlign(const String &buf, int row_top, int alignment)
{
int16_t x1, y1;
uint16_t w, h;
display.setTextWrap(false);
display.getTextBounds(buf, 0, row_top, &x1, &y1, &w, &h); //calc width of new string
if (alignment == TEXT_RIGHT)
display.setCursor(SCREEN_WIDTH - w, row_top);
else
if (alignment == TEXT_CENTER)
display.setCursor((SCREEN_WIDTH - w)/2, row_top);
else
if (alignment == TEXT_LEFT)
display.setCursor(0, row_top);
display.print(buf);
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS))
{
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay(); // first delete buffer content
}
void loop()
{
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1);
display.clearDisplay();
drawTextAlign("Hello World", 0, TEXT_LEFT);
drawTextAlign("2023", 8, TEXT_LEFT);
display.display();
delay(1000);
display.clearDisplay();
drawTextAlign("Hello World", 0, TEXT_CENTER);
drawTextAlign("2023", 8, TEXT_CENTER);
display.display();
delay(1000);
display.clearDisplay();
drawTextAlign("Hello World", 0, TEXT_RIGHT);
drawTextAlign("2023", 8, TEXT_RIGHT);
display.display();
delay(1000);
}