About Lesson
Code to Test the OLED Display:
To interact with the OLED, you’ll need the Adafruit SSD1306 and Adafruit GFX libraries.
1. Install Libraries:
- Open the Arduino IDE.
- Go to
Sketch
>Include Library
>Manage Libraries...
. - Search for and install Adafruit SSD1306 and Adafruit GFX libraries.
C++
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Define the OLED display width and height
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Create an instance of the SSD1306 display object
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Start the OLED display
if (!display.begin(SSD1306_I2C_ADDRESS, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
// Clear the buffer
display.clearDisplay();
// Set text size and color
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Display a message
display.setCursor(0, 10);
display.println(F("Hello, ESP32!"));
display.display();
}
void loop() {
// Nothing to do in loop for this example
}
Key Points in the Code:
- SSD1306_I2C_ADDRESS: The I2C address of the display is typically
0x3C
, but some OLEDs might use0x3D
. You can check this using an I2C scanner (Found Here) - Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1): This initializes the display with I2C communication.
- display.begin(): Initializes the OLED display. If it fails, it stops the execution.