Interface I2C LCD with an ESP32

To interface an I2C LCD with an ESP32, you need to connect the LCD to the ESP32 using the I2C protocol and then write code to control it. Here’s how to do that:

Hardware Connection:

    Here’s the wiring:

    • VCC 5V or 3.3V on ESP32 (based on your LCD’s operating voltage)
    • GND GND on ESP32
    • SDA GPIO 21 on ESP32
    • SCL GPIO 22 on ESP32

    Arduino Code:

    The easiest way to interface with an I2C LCD is using the LiquidCrystal_I2C library. Below is the code to display a simple message on the LCD.

    Steps:

    1. Install the LiquidCrystal_I2C library from the Arduino IDE (if not already installed).
      • Go to Sketch → Include Library → Manage Libraries…
      • Search for LiquidCrystal_I2C and install it.
    2. Code to interface the I2C LCD with ESP32:
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    
    // Define I2C pins (ESP32-specific default pins)
    #define SDA_PIN 21
    #define SCL_PIN 22
    
    // Create an object of the LiquidCrystal_I2C class
    // LCD(0x27, 16, 2) -> I2C address, number of columns, number of rows
    LiquidCrystal_I2C lcd(0x27, 16, 2); 
    
    void setup() {
      // Start Serial Monitor
      Serial.begin(115200);
    
      // Initialize I2C with custom SDA and SCL pins
      Wire.begin(SDA_PIN, SCL_PIN);
    
      // Initialize LCD
      lcd.init();  // some libraries use init() instead of begin()
      
      // Turn on the backlight
      lcd.backlight();
      
      // Print a message to the LCD
      lcd.setCursor(0, 0); // Start at the first row, first column
      lcd.print("Hello, ESP32!");
    
      lcd.setCursor(0, 1); // Move to the second row
      lcd.print("I2C LCD test.");
    }
    
    void loop() {
      // Nothing to do here
    }
    

    Explanation:

    • LiquidCrystal_I2C lcd(0x27, 16, 2);: Initializes the LCD with the I2C address (0x27 is commonly used, but it might vary for your LCD) and defines a 16×2 character display.
    • lcd.begin();: Initializes the LCD screen.
    • lcd.backlight();: Turns on the backlight.
    • lcd.setCursor(x, y);: Moves the cursor to the position (x, y) on the screen (x is the column, y is the row).
    • lcd.print("text");: Prints text to the LCD at the cursor position.

    Notes:

    • I2C Address: The address 0x27 is common, but some I2C LCD modules use 0x3F. You can scan for the address using an I2C scanner if you don’t know it.
    • Wiring: Ensure the SDA and SCL pins are correctly connected (GPIO 21 and GPIO 22 by default on ESP32).