scrolling one line on a 16×2 lcd

I’m working on an arduino morse code keyer and will be using a 16×2 lcd like this:

/images/16x2lcd.jpg

I want to have some static text on the top line, while the bottom line scrolls. The built in arduino lcd library will do scrolling, but not a single line. There are other code examples showing how to do this, but they all seem overly complicated to me. Here is the solution that I came up with.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <LiquidCrystal.h>

LiquidCrystal lcd(11, 10, 9, 8, 7, 6);

char line2[17] = "                 "; // initialize line2 (16 characters plus 1 null terminator)

void setup() {
   lcd.begin(16, 2); //initialize lcd
}

void loop(){
     char str[] = "This is a scrolling string."; // string to scroll
     for (int i = 0 ; i <= sizeof(str); i++) {   // loop through the string
        update_lcd_buffer(str[i]);               // update lcd with each character 
        delay(500);
     }
     

}

void update_lcd_buffer(char c) {
  char *buffer = &line2[1];    // create pointer to the second character of line2
  strncpy(line2, buffer, 16);  // set line2 = the second character of line2 to the end 
  line2[15] = c;               // append our new char to end of line2
  lcd.clear();                 // clear the screen
  lcd.setCursor(0, 0);         // set cursor to beginning of first line
  lcd.print("Static string."); // print the static string on the first line
  lcd.setCursor(0, 1);         // set cursor to beginning of second line
  lcd.print(line2);            // print line2
  
}

The code basically keeps a 16 character string in line2 at all times. It starts with 16 spaces. Each call of update_lcd_buffer will remove the first character from the string and add the supplied character to the end of the string. It does this by creating a pointer to the second character of the string called buffer. It then copies the contents of the buffer back to the line2 variable. Then it adds the new character to the end of the string. Then it updates the lcd with the new data.

I don’t know if this is the best way of doing this, but it works well for my purpose and it is much simpler and more concise code than most of the examples I’ve seen.