Serial reading problem. First letter not received.

Hi!

I’d like to send a string from my computer to Arduino via USB, then print in on a 16*2 LCD. The problem is, that the first letter is not always displayed. I sent the same text (“Trying serial”) three times, twice it worked well, once it printed “rying serial”, and so randomly every 3rd or 4th times. (I tried increasing the delay, and it didn’t help.)

Here’s the sketch:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

char input [32] = "";

void kiir (char output[32]){
  for (int j = 0; (j < 32 && output[j] != '\0'); j++){
    if (j == 16) {
      lcd.setCursor(0,1);
    }
    lcd.print(output[j]);
  }
}

void setup(){
  Serial.begin(9600);
  lcd.begin(16, 2);
}
void loop(){
  int i = 0;
  if (Serial.available()){
    lcd.clear();
    delay(1000);
  }
  while( Serial.available() > 0 && i < 32) {
    input[i] = Serial.read();
    i++;
    input[i] = '\0';
  }
  if (i > 0) {
    kiir(input);
    input[0] = '\0';
  }
}

I’m still getting familiar with the language.

Yes that is how you have written it. You are getting the first character but the immediately over writing it with the rest of the string.
Remove the dealy altogether, gather bytes until you see the carriage return character and then print.
Or print as you get them and only do a LCD clear after a carriage return an the first character.

Work through your code assuming that Serial.available() returned 2 (say) and see what happened.

Mark

Thank you very much! Now it works. Here’s the working sketch if you’re interested

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

char input [32] = "";

void kiir (char output[32]){
  for (int j = 0; (j < 32 && output[j] != '\0'); j++){
    if (j == 16) {
      lcd.setCursor(0,1);
    }
    lcd.print(output[j]);
  }
}

void setup(){
  Serial.begin(9600);
  lcd.begin(16, 2);
}
void loop(){
  int i = 0;
  if (Serial.available() > 0){
    lcd.clear();
    Serial.readBytesUntil('\r',input,32);
  }
  if (input[0] != '\0') {
    kiir(input);
    for (int i = 0; i < 32; i++) {
      input[i] = '\0';
    }
  }
}

Even better would be

void loop(){
  int i = 0;
  Serial.readBytesUntil('\r',input,32);
  led.clear();
  kiir(input);
  for (int i = 0; i < 32; i++) {
    input[i] = '\0';
  }
}

and as readBytesUntil returns the number of bytes read you can get rid of the for loop.

Mark
}