Tuesday 25 February 2014

Teensy Scrolling text!

Today I have been playing around with the screen, this time reading from the serial port and printing the message. The code to read from USB is really simple and can be found in the examples so I won't go into that.

What I want to do is do scrolling text over two lines! The inbuilt function scrollDisplayLeft() doesn't really do the job and it scrolls the whole panel so I rolled my own function.

Very quickly the code is below:

 #include <Wire.h>   
 #include <LiquidCrystal_I2C.h>  
 // Set the LCD address to 0x27 for a 16 chars and 2 line display  
 LiquidCrystal_I2C lcd(0x27, 16, 2);  
 String oldContent; //Keep this between usb reads();  
 void setup(){  
  lcd.begin();  
  Serial.begin(9600); // USB is always 12 Mbit/sec  
  oldContent=""; //Initialise this variable  
 }  
 void loop(){  
  String content = getString(); //Get the USB content  
  //If there was USB content display it  
  if (content != ""){  
   content.concat(" "); //Add another character  
   oldContent = content;//Save the content  
  }  
  //If there is something to display  
  if (oldContent!=""){  
   displayMessage(oldContent); //show me!  
  }else{  
   //Otherwise check again soon!  
   delay(250);  
  }  
 }  
 String getString(){  
  String content = ""; //Set up return variable  
  char character; //char to read from USB  
  while(Serial.available()) { //While there is more to read, do more  
    character = Serial.read(); //Read the char  
    content.concat(character); //Add it to the return variable  
    delay (10); //make sure we don't act too quickly and assume it's over before it really is  
  }  
  return content;   
 }  
 void displayMessage(String message){  
  if (message!=""){ //Make sure there is something to show  
    lcd.home(); //Start at row 1  
    printRows(message,0); //print the message, possibly on 2 rows  
    delay(2500); //Show the first screen for a while, give people a change to read  
    for (int posCounter = 0; posCounter < message.length(); posCounter++){ //For all of the chars  
     printRows(message,posCounter); //print the message, possibly on 2 rows  
     delay(600);// Wait a bit as the LCD refresh is bad  
    }  
    delay(600); // Little extra wait, possibly not needed  
  }   
 }  
 void printRows(String message, int pos){  
    lcd.clear();//Clear the screen again  
    lcd.setCursor(0,0); //Got to line 1  
    lcd.print(message.substring(pos,pos+16)); //Get row 1 and print it  
    if (message.length() >16){ //Check for a row 2  
     lcd.setCursor(0, 1); //Set to the second row  
     lcd.print(message.substring(pos+16,pos+32)); //Print row 2  
    }  
 }  

Not rocket science but it might help someone.

No comments:

Post a Comment