arduino / ArduinoCore-samd

Arduino Core for SAMD21 CPU
GNU Lesser General Public License v2.1
472 stars 720 forks source link

Serial.peek() causes Serial.available() to decrement #405

Closed per1234 closed 5 years ago

per1234 commented 5 years ago

Arduino IDE 1.8.10 Hourly Build 2019/04/18 12:33, Arduino SAMD Boards @ https://github.com/arduino/ArduinoCore-samd/commit/31104a1828234943728a4e843b87f003bc90d62d / Arduino SAMD Beta Boards @ https://github.com/arduino/ArduinoCore-samd/commit/67bf93e52e52ccb75142bbbeb6588ecf9b042952, Windows 10 64 bit

The value returned by Serial.available() is sometimes decremented after calling Serial.peek(). Since Serial.peek() does not remove data from the buffer, this is the incorrect behavior and is inconsistent with any other implementation of peek() in Arduino's code that I've used.

Demonstration sketch:

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    Serial.print("available pre-peek: ");
    Serial.println(Serial.available());
    Serial.peek();
    Serial.print("available post-peek: ");
    Serial.println(Serial.available()); // should be the same as the pre-peek value

    // clear the Serial input buffer
    while (Serial.available()) {
      Serial.read();
    }
  }
}

After uploading the above sketch and sending some data over Serial, the expected behavior is that the return value of the post-Serial.peek() call to Serial.available() should match the return value of the pre-Serial.peek() call to Serial.available().

facchinm commented 5 years ago

Hey @per1234 , thanks for the perfect report. Is Serial the USB Serial (on MKRs) or the UART serial (programming port on the Zero) ? There's a problem anyway but in case of USB it could be related with https://github.com/arduino/ArduinoCore-samd/issues/272

per1234 commented 5 years ago

It's the USB serial that this issue applies to. I tested with the UART and it doesn't have this issue.

I hadn't considered the ambiguity caused by it being called SerialUSB on the Zero.

per1234 commented 5 years ago

it could be related with #272

If so, I'd expect this issue would occur with the call to Serial.peek() removed from the demonstration sketch above or replaced by a delay, but I can only reproduce this issue when Serial.peek() is called in the demonstration sketch.

I can also reproduce https://github.com/arduino/ArduinoCore-samd/issues/272 using the demonstration sketch provided there, though not the part of it where available() is reported to sometimes incorrectly return 1.