0

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)?

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • 1
    Arduino is not C, deleted tag. This is demonstrated by `Serial.println("Serial.available() = " + String(Serial.available()));` – Weather Vane Aug 04 '17 at 21:08
  • setup() is only called once. you should define a loop() function and move the last 3 lines of code of setup() into it for continuous operation. – Michaël Roy Aug 05 '17 at 14:27

2 Answers2

1

have you tried Serial.readString() to parse the entire missing characters?

Joaquin Peraza
  • 343
  • 1
  • 15
0

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.

D Krueger
  • 2,446
  • 15
  • 12