简体   繁体   中英

Serial.read() skips over serial input

Trying to send serial messages using Arduino Uno and standard IDE. Ran into issue parsing the serial message sent to the device.

See that if I include this line Serial.println("Serial.available() = " + String(Serial.available())); I will be able to read the rest of the message. If this is commented out I will only see the first letter of the message and skip over the rest. Attached image of output that I'm seeing with and without the added line of code.

// the setup routine runs once when you press reset:
void setup() {

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  while (!Serial) {} // wait for serial to be initialized

  Serial.println("Setup called. Serial port ready.");

  Serial.println("Waiting for time sync message...");
  while (!Serial.available()) {}
  processSyncMessage();
}

void processSyncMessage() {

  // parse first letter of message
  char messageHeader = (char) Serial.read();

  switch (messageHeader) {
    case TIME_HEADER:
       // do processing
      break;
    default:
      Serial.println("Unknown message sent with header: " + String(messageHeader));

      // must include this line in order to see the entire message sent
      // just calling a println or a Serial.available() doesn't work ????
      Serial.println("Serial.available() = " + String(Serial.available()));

      Serial.println("---start of message");
      for (int r = 0; r != -1; r = Serial.read()) {
        Serial.print((char) r);
      }
      Serial.println();
      Serial.println("---end of message");
      break;
  }
}

Missing Buffer

With printout

Is this somehow related to a buffer? Can I flush it somehow with fflush(SOME_SECRET_BUFFER) ?

您是否尝试过Serial.readString()来解析所有丢失的字符?

Serial data is transmitted and received one character at a time. At 9600 baud, the transmission rate is approximately one character per millisecond.

The code assumes that once the first character has arrived, all of them have. This is not the case. The addition of the println consumes CPU time, and therefore has the effect of adding a delay. This delay allows the rest of the original message to be received.

A receive function with an appropriate timeout for your application is needed here.

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