Centre LCD text which is variable in length

I am using a 20 x 1 large character LCD (the size of a usual 40 x 2 lcd) this is my test lcd for what will be a 5 foot long 'next stop' interior display for my bus driving simulator.

I recieve text in a string over the serial port, parse it into the individual bits of text, and i simply read the relevant string from the buffer and print the the text for the interior display to the lcd.

What i need to do is get the length of the text to be sent to the lcd, do some maths then centre it, or add padding so it is displayed in the middle of the lcd,

The text can vary from 5 to 20 characters, and often there are 2 strings of text changing over and over to show one stop name that is longer than 20 characters.

Googling shows a post on the arduino.cc forum from 2014 i believe, where someone posted the following code to do this :

/*
row = Zeile, 0 bis 3
text = Displaytext
ltr = 0 = linksbündig, 1 = mittig, 2 = rechtsbündig
*/
void lcdText(int row, String text, int ltr){
 
  int offset = 0;

 
  switch(ltr){
   
    case(0)://Text links
      lcd.setCursor ( offset, row );
      lcd.print(text);
    break;
   
    case(1)://Text mittig
      offset = (displayCharLength - text.length())/2;
      lcd.setCursor ( offset, row );
      lcd.print(text);
    break;

    case(2)://Text rechts
      offset = (displayCharLength - text.length());
      lcd.setCursor ( offset, row );
      lcd.print(text);
    break;
   
  }
}

void lcdTextClear(int row){
  lcd.setCursor ( 0, row );          //select the row
  lcd.print("                    "); //Clear the row
}

Im am really trying to learn this programming stuff (currently learning the proper way to handle strings)
But i can't quite figure out what else i need to do to make the above code work, and searching for a working example draws a blank.

I know to others who know programming this will be a simple thing, but i am struggling, but trying to learn.

Pretty simple.

    int wid = 20; //for your 20x1
    int row = 0;  //always 1st row      
    int len = strlen(msg);
    lcd.setCursor((20 - len) / 2, row);
    lcd.print(msg);

Untested. Typed straight into Browser.

Thankyou, that works perfectly.

This topic was automatically closed after 120 days. New replies are no longer allowed.