How to empty the buffer for Serial port? I have a Yun that accepts commands via the bridge (note the below code is part of a very simple virtual keyboard that accepts commands then runs Keyboard.println on them:

#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
HardwareSerial *port;

void setup() {
  port = &amp;Serial1;
  port-&gt;begin(9600);
}

void loop() {
  if (port-&gt;available()) {
    String cmd = port-&gt;readString();

    if(cmd.length() &gt; 1){
      String instruction = cmd;
      int arg_comma_index = 0;
      arg_comma_index = instruction.indexOf(",");
      String func = instruction.substring(0, arg_comma_index);
      String args = instruction.substring(arg_comma_index + 1, instruction.length() + 1 );

      Keyboard.begin();
      Keyboard.println(args);
      Keyboard.end();
    }
    port-&gt;read(); // Try to throw away whatever's left to prevent looping (which is still happening).
  }
}


If I send it a short string:  


The first time, immediately after starting the sketch, it works.
The second time, it works but loops anywhere from 1-5 times.
The third time, it loops more times still.
If I leave the device running (even if not operating it), the number of times it loops goes up when I finally do send it an instruction. I'm seeing 20-75 loops after less than 15 minutes of uptime.


Clearly the loops where no instruction is being received are still building up something here. I've tried:


Restarting the port each void loop().
Flushing the port at the top and/or bottom of each void loop().
Setting cmd = "" at the end of each void loop().
Checking peek(), available(), and readString() - after I send it one instruction, they return the same values every single time they loop.
It's quite simple to empty the serial buffer - you just read all the data that is in the buffer and throw it away:

while (port-&gt;available()) {
    port-&gt;read();
}