Skip to content

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

Closed
@per1234

Description

@per1234

Arduino IDE 1.8.10 Hourly Build 2019/04/18 12:33, Arduino SAMD Boards @ 31104a1 / Arduino SAMD Beta Boards @ 67bf93e, 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().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions