Hey guys, I've been playing around with a command interpreter I recently wrote. I found that if I didn't add a delay when processing new Serial data, my new Serial data might come in two separate chunks, or more. 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. I'd love some feedback on this. Thanks! Oh, and I hope the comments don't get in the way...they are supposed to be there to help, but who knows if they will or not.
void setup()
{
//let's start by starting some serial communication
Serial.begin(57600);
}
//then initialize some needed variables here...
//character array to store the command
char command[30];
//index for character array
int i = 0;
//lets us know if a command is available to be processed or not
boolean commandAvailable = false;
//how many times will the program check to see if serial is
//available from the buffer before flagging the command as read?
#define TRIES 50
//a variable that will be used again and again for checking the above
int tries = TRIES;
void loop()
{
//check if serial is available and that we haven't exceeded the number of tries
//and that we haven't gone past the size of the command
if (Serial.available() > 0 && tries > 0 && i < sizeof(command))
{
command[i++] = Serial.read(); //store a byte in the array, then increment the index
commandAvailable = true; //a command will eventually be ready...
//we will keep checking for data at the buffer for <code>TRIES</code>
//number of times until we are convinced there is no more data to be read at this time.
tries = TRIES;
}
else
{
//we either:
//1. didn't find any data at the buffer, or
//2. we've exceeded the command size, or
//3. we have looked for data an appropriate number of times.
//Thus, we need to decrement <code>tries</code> to say that we've looked
//for data yet another time.
tries--;
}
//if we have a command available and we have reached zero
//indicating we have looked for data <code>TRIES</code> number
//of times, we are ready to see the command.
if (tries <= 0 && commandAvailable)
{
//let's get rid of all that other data in case the buffer still has some left in it.
Serial.flush();
//print out the command we received
Serial.println(command);
//reset the index for the next time
i = 0;
//reset the number of tries for next time
tries = TRIES;
//confirm that we've checked the command, so mark this false
commandAvailable = false;
//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;
}
}
}