Hi Stimmer,
I found kicking out the circular buffer a great demonstration "out of the box" thinking.
I have tested your implementation with ArduinoISP. I think this is a good real life use scenario of the serial port, with lots of messages of different sizes (though relatively small) in both directions. I powered my leonardo from the due's 3v3 and modified ArduinoISP to use SerialUSB instead of Serial. It worked well: I could upload download the bootloader to/from the leonardo several times.
Nevertheless dropping the serial buffer also has consequences for feeding the due lots of small messages. Each message is received in a separate bank and you only have two of them. Take for example this shell script:
n=0
while true; do
echo "$n" > /dev/ttyACM1
echo $?
sleep 1
let "n = $n + 1"
done
I ran this sketch on the due:
static const int led = 13;
static const int button = 3;
void setup() {
// initialize serial:
SerialUSB.begin(9600);
Serial.begin(115200);
pinMode(led, OUTPUT);
pinMode(button, INPUT);
digitalWrite(button, HIGH);
}
void loop() {
// if there's any serial available, read it:
int i = 0;
if (digitalRead(button)) {
while (SerialUSB.available() > 0) {
char c = SerialUSB.read();
Serial.write(c);
i++;
}
}
Serial.print("i=");
Serial.println(i);
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
If you press the button for a few seconds, some of the messages are lost.
Odd enough the return code of echo is always 0.
I am not sure where the bytes get lost. And maybe it can be prevented with stty calls, but a circular buffer would prevent this. A circular buffer which you fill up with memcpy would also make sense as an implementation.