#include <LiquidCrystal_I2C.h>
const uint8_t lcd_width = 16;
const uint8_t lcd_height = 2;
LiquidCrystal_I2C lcd( 0x27, lcd_width, lcd_height );
class ScrollText
{
public :
void start( const char * text, const uint8_t line = 0 )
{
str = text;
str_length = strnlen( str, lcd_width );
x = 0;
y = line;
x_max = lcd_width - str_length;
direction = 1;
timer_timestamp = 0;
lcd.setCursor( x, y );
lcd.print( str );
}
void stop()
{
direction = 0;
}
void loop()
{
if ( direction != 0 )
{
const uint32_t timestamp = millis();
if ( timestamp - timer_timestamp >= 100 )
{
timer_timestamp = timestamp;
// Move right
if ( direction == 1 )
{
if ( x < x_max )
{
lcd.setCursor( x++, y ); // Go to the actual position, set next position one to the right of the old string
lcd.print( ' ' ); // Erase the first character of the old string
lcd.print( str );
if ( x == x_max )
{
direction = -1;
}
}
}
// Move left
else if ( direction == -1 )
{
if ( x > 0 )
{
lcd.setCursor( --x, y ); // Set next position one to the left of the old string, and go to this new position
lcd.print( str );
lcd.print( ' ' ); // Erase the last character of the old string
if ( x == 0 )
{
direction = 1;
}
}
}
}
}
}
private :
char * str;
uint8_t str_length;
uint8_t x;
uint8_t y;
uint8_t x_max;
int8_t direction;
uint32_t timer_timestamp;
};
ScrollText scrollText;
void setup()
{
lcd.init();
lcd.backlight();
lcd.setCursor( 1, 0 );
lcd.print( "Scroll example" );
scrollText.start( "Hi", 1 );
}
void loop()
{
scrollText.loop();
}