ESPHome -- Scroll LCD Display Lines

I built an ESPHome project that uses a gpio lcd display. For that project, I wanted the lines on the lcd display to scroll when they were too long to fit on the screen. Here is a gist of the yaml that makes the lines scroll. I’ll also paste the code here:

substitutions:
  lcd_width: '16'
  lcd_height: '2'
  scroll_speed: 1s
  line_1: 'Long line that we want to scroll'
  line_2: 'Another long line that does not fit on the screen'

display:
  - platform: lcd_gpio
    dimensions: ${lcd_width}x${lcd_height}
    data_pins:
      - D0
      - D1
      - D2
      - D3
    enable_pin: D6
    rs_pin: D5
    id: lcd
    update_interval: $scroll_speed
    lambda: |-
      static int p1 = 0;
      static int p2 = 0;

      // These lines could instead come from something like a text sensor.
      char* line1 = $line_1;
      int length1 = strlen(line1);
      if (length1 > $lcd_width) length1 = $lcd_width;
      
      const char* line2 = $line_2;
      int length2 = strlen(line2);
      if (length2 > $lcd_width) length2 = $lcd_width;

      int spacesLength = length1 >= $lcd_width ? 0 : $lcd_width - length1 + 1;
      char spaces[spacesLength];
      for (int i = 0; i < spacesLength - 1; i++) spaces[i] = ' ';
      spaces[spacesLength - 1] = '\0';
      
      it.printf("%.*s%s%.*s", length1, line1 + p1, spaces, length2, line2 + p2);

      p1++;
      if(p1 > (int)strlen(line1) - $lcd_width) {
        p1 = 0;
      }
      p2++;
      if(p2 > (int)strlen(line2) - $lcd_width) {
        p2 = 0;
      }
4 Likes