I'm working with a Bluetooth module (HC-05) connected to the Arduino (Mega 2560). With my android device I'm sending commands to the Arduino. I use this code to receive the data:
String message;
void readDataFromBluetooth() {
if(btSerial.available()) {
while(btSerial.available()) {
message += char(btSerial.read());
}
char command[message.length()];
message.toCharArray(command, message.length());
// debug
String replyStr = message + " - " + String(receivedMessage.length())+ " - "+ String(command)+ " - "+ String(strlen(command));
Serial.println(replyStr);
message = "";
processCommand(command); // a method where I use strcmp to compare and execute the necessary code
}
}
As you can see I'm printing the results for debugging, and I've noticed that the char array command is a character short in respect to the string message. For example, if I send "HELLO" from Android, message will be "HELLO", but command will be "HELL". So in the Serial Monitor I'll see something like:
HELLO - 5 - HELL - 4
You are using serial.available() to find the end of the command string, rather than parsing the incoming data.
Just because there are not character incoming right now, does not mean that there won't be more coming down the pipe in another millisecond, and does not mean that the message (whatever it is) is definitely finished. Maybe there's nothing on the serial right now because the data is buffered. Maybe there's nothing there because you set the serial to 9600, and that's actually pretty slow (one character per 1.04 milliseconds).
You have to work out a way of figuring out when the command is finished like looking for a space or a newline. You can't rely on Serial.available() to do that job.[/code]