// esp32_i2c_lcd_scroll.ino
// Simple scrolling text on a 16x2 I2C LCD using LiquidCrystal_I2C
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// ----- CONFIG -----
#define LCD_ADDR 0x27 // change to 0x3F if your module uses that address
#define LCD_COLS 16
#define LCD_ROWS 2
LiquidCrystal_I2C lcd(LCD_ADDR, LCD_COLS, LCD_ROWS);
// The text to scroll (can be long)
const char scrollText[] = "Hello from ESP32! This is a scrolling demo on a 16x2 I2C LCD. ";
// extra spaces at end give a gap between repeats
// Optional static second-line text (set empty "" to keep blank)
const char secondLine[] = "ESP32 I2C LCD";
const unsigned long scrollDelayMs = 100; // speed: smaller = faster
void setup() {
Serial.begin(115200);
delay(50);
Serial.println("LCD scroll demo starting...");
lcd.init(); // initialize LCD
lcd.backlight(); // switch backlight on (if supported)
// If second line is used, print it (trim to LCD_COLS)
if (strlen(secondLine) > 0) {
char tmp[LCD_COLS + 1];
strncpy(tmp, secondLine, LCD_COLS);
tmp[LCD_COLS] = '\0';
lcd.setCursor(0, 1);
lcd.print(tmp);
}
}
void loop() {
scrollLine(scrollText, LCD_COLS, scrollDelayMs);
}
// Scrolls a string across a single LCD line (row 0).
// If text length <= cols, just prints it centered/left.
void scrollLine(const char *text, uint8_t cols, unsigned long delayMs) {
size_t len = strlen(text);
// If fits in display width, just show and pause
if (len <= cols) {
lcd.setCursor(0, 0);
lcd.print(text);
// fill rest with spaces to clear any old chars
for (uint8_t i = len; i < cols; ++i) lcd.print(' ');
delay(delayMs * 2); // keep visible a bit
return;
}
// For longer text, slide window of width 'cols' across the string,
// and wrap around so it continuously scrolls.
// We'll create a buffer of text repeated twice with spaces for smooth wrap.
String s = String(text);
// Append enough spaces at the end to create visible gap already included in text variable.
// To ease wrap, make a doubled string:
String doubled = s + s;
for (size_t offset = 0; offset < s.length(); ++offset) {
// Extract substring of length cols starting at offset
String window = doubled.substring(offset, offset + cols);
lcd.setCursor(0, 0);
lcd.print(window);
delay(delayMs);
}
}