//let's get rid of all that other data in case the buffer still has some left in it.
//write over the command space so we don't see previous characters
//for a shorter command next time
for (int i = 0; i < sizeof(command); i++)
command[i] = 0;
Lovely. Insert NULLS in every position because you don't understand what NULL-terminated means.
How fast does loop() operate? Let's assume that no serial data is sent.
1) Check for serial data (Serial.available() gets called. It computes and returns the difference between two pointers - two uint8_t accesses and a subtraction operation).
2) Compare the result to 0. It's not greater, so
3) Decrement tries (an int access, a subtract, and an int store)
4) Another if test with an int access, a compare, a byte access and another compare
How long do you think this will take to execute? I'll wait while you figure it out. Remember the Arduino operates at 16MHz, so each operation takes 62.5 nanoseconds.
As one person mentioned before, adding the delay is a "band-aid" solution to the problem. Here's a way I found that will prevent that reliably, though it may still be seen as a crutch to the program.