portfolio

OLED Code

Course Content
Session 1: Introduction to ESP32
Objective: Get familiar with the ESP32 microcontroller and set up the development environment.
0/5
Session 2: Interfacing with Sensors and Displays
Learn how to connect a DHT22 sensor and an OLED display to the ESP32.
0/4
Session 4: Programming the OLED Display
Objective: Write code to display information on the OLED display.
0/4
Session 5: Integrating Sensor Data with OLED Display
Objective: Combine sensor readings with OLED display functionality.
0/1
Session 6: Setup WIFI Capability
0/1
Session 7: Adding a Webserver
0/1
Session 8: Wrap-up
0/1
ESP32 Basics
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 use 0x3D. 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.