I have an Arduino connected to an XBee and am using the below sub to handle new serial data received; it is called once per iteration of the main loop.
DEBUG_GREEN is just a digital output pin connected to a green LED which I use to check that data is being received and processed
boolean rec = false;
boolean newRec = false;
String recPacket = "";
void handleSerial(){
//Read byte from serial port
//Wait until receive a * (start packet) then set receiving to true
//If receiving is true then add each additional byte to master string
//if byte is ! (end packet) then set receiving to false and set flag for new data received
//new data received is then processed elsewhere
unsigned char inByte;
if (rec==false) {
inByte = Serial.read();
if (inByte == '*'){
recPacket = "";
rec = true;
}
}
while ((Serial.available() > 0) & (rec == true)){
digitalWrite(DEBUG_GREEN, HIGH);
inByte = Serial.read();
if (inByte == '!') {
rec = false;
newRec = true;
} else {
recPacket = recPacket + String(inByte);
delayMicroseconds(1000); //Adding this in seems to fix the problem/ substantially reduce its frequency
}
}
digitalWrite(DEBUG_GREEN, LOW);
}
The problem is that sometimes, generally after several minutes of operation, the code will hang with DEBUG_GREEN illuminated. Based on moving the LED on/ off flags around to see where code execution gets to, It appears to hang after either Serial.available() or Serial.read() are called (it has hung after both). I cannot find any pattern to when it hangs in terms of the data which is being processed, the time the device has been on for etc.
Can anyone see anything wrong with the above code which would cause this behaviour, in particular whether there are known problems associated with calling Serial.available() and Serial.read() to rapidly? Adding the delayMicroseconds(1000) line shown in the above code seems to solve/ reduce the problem, changing the value to 500 does not.
Any advice much appreciated.