Serial.read() - first read is not correct.

Hello, I am sending data through Serial2. First this code send letter ‘s’ - then the other serial device responds with ‘s’. Whenever I restart Arduino, the very first received inChar letter is “⸮” , and after normally I receive ‘s’. Im trying to understand why and how to fix it but so far I have failed.

void sendData() {

  char inChar = Serial2.read();
  Serial.println(inChar);
  Serial2.print('s');
  delay(100);
    if (inChar == 's') {
      for (int i = 0; i < 12; i++) {
        Serial.print('<');
        Serial.print(liczby[i]);
        Serial.print(">");
      }
      Serial.println();
      for (int i = 0; i < 12; i++) {
        Serial2.print('<');
        Serial2.print(liczby[i]);
        Serial2.print(">");
      }
      Serial2.print('e');
    }
  }

You did check that there’s something to read before you read it?

Somewhere else, in the code you didn’t post?

Umm I have changed it as below and it seems to work :slight_smile: To be honest I have tried it before, but the result was the same, looks like I have screwed something earlier. Thank you.
Edited: Well, I thought it works, but still it’s the same, just there is no more question mark.

  • Arduino sends ‘s’
  • Serial device sends ‘s’
  • Arduino doesn’t see first ‘s’ sent by Serial device so it doesn’t send any data
  • After some time Arduino sends another ‘s’
  • Serial device sends ‘s’
  • Now Arduino receive ‘s’ and send data - from now on everything is working fine.
void sendData() {
  Serial2.print('s');
  if (Serial2.available() > 0) {
    char inChar = Serial2.read();
    Serial.println(inChar);
    if (inChar == 's') {
      for (int i = 0; i < 12; i++) {
        Serial.print('<');
        Serial.print(liczby[i]);
        Serial.print(">");
      }
      Serial.println();
      for (int i = 0; i < 12; i++) {
        Serial2.print('<');
        Serial2.print(liczby[i]);
        Serial2.print(">");
      }
      Serial2.print('e');
    }
  }
}

It's always a good idea to have a startup sequence that discards any unwanted garbage that may be in the Serial system.

...R

piggybank:

Serial.println();

for (int i = 0; i < 12; i++) {
       Serial2.print(’<’);
       Serial2.print(liczby[i]);
       Serial2.print(">");
     }
     Serial2.print(‘e’);
   }
 }
}

Why have you used opening/closing double quotes in the following code instead of opening/closing single quotes?

Serial2.print(">");

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.