简体   繁体   中英

How to store two seperate lines on Arduino LCD from Serial Read

With my current code one character is read at a time, so the serial read of two separate lines is read as one large input. This causes both lines to be written on the same line of my LCD display on my Arduino. Is there any way to have a null character or a break line to get these inputs to write on different lines?

EDIT: Sorry, I should've specified that the input text will be of variable length.

Here is my Arduino code:

     #include <LiquidCrystal.h>
     #include <string.h>

    // These are the pins our LCD uses.
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    // initalize the lcd, and button input at zero.
    int lcd_key     = 0;
    int adc_key_in  = 0;

    void setup()
    {
     Serial.begin(9600); //Set the serial monitor.
     lcd.begin(16, 2); //Set the LCD
    }
    char line1;
    void loop()
   {

    if (Serial.available() > 0) { //If the serial monitor is open it will read a value.
    line1 = Serial.read();
    delay(10);
    Serial.print(line1);

  }
}

When the LCD is initialized, I'm guessing its default position would be 0,0 (ie first row and first column). Then for each character you read from the serial input, you print it to the LCD, and increase the column. If you get a newline in the input, then reset the LCD position to 1,0 (ie second row and first column). Continue reading and printing.


Example pseudo-code:

int current_line = 0;
int current_col = 0;

void loop(void)
{
    char ch = read_char_from_serial();

    if (ch == '\n')
    {
        current_line++;
        current_col = 0;
    }
    else
    {
        lcd_goto(current_line, current_col++);
        lcd_put_char(ch);
    }
}

LCDs have a buffer for 1st line and for the second line at consecutive addresses, depending on LCD model (usually 40 or 64 characters per line) You could send a fixed number of characters for the first line right-padded with spaces then the second line. example: First line<30 spaces>Second line

You might also need to set LCD (lcd.begin) not to scroll the display)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM