/**
* Displays text sent over the serial port (e.g. from the Serial Monitor) on
* an attached LCD.
* https://wiki.52pi.com/index.php?title=Z-0234
*/

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>

String topLine;
String bottomLine;
String incomingString;

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
    lcd.begin();
    lcd.backlight();

    // Initialize the serial port at a speed of 9600 baud
    Serial.begin(9600);
}

void loop()
{
    // If characters arrived over the serial port...
    if (Serial.available())
    {
        // Wait a bit for the entire message to arrive
        delay(100);
        // Clear the screen
        lcd.clear();
        lcd.setCursor(0, 0);
        // Write all characters received with the serial port to the LCD.
        while (Serial.available() > 0)
        {
            incomingString = Serial.readString();
            Serial.println(incomingString);
            if (incomingString[0] != '1')
            {
                topLine = incomingString;
            }
            else
            {
                if (incomingString != "123456" && (incomingString.length() < 2 || (incomingString[1] != 't' && incomingString[1] != 'T')))
                {
                    bottomLine = "";
                }
                else
                {
                    bottomLine = incomingString;
                    bottomLine[0] = ' ';
                    bottomLine[1] = ' ';
                }
            }

            lcd.print(topLine);
            lcd.setCursor(0, 1);
            lcd.print(bottomLine);
        }
    }
}