Hey all,
I have been playing around with some serial communication and have the following issue: Every time i execute a function to send a command to a slave and then read the answer from it, the Serial.available() function causes another global variable to be overwritten. I know this sounds weird... let me explain a little more.
I have an LCD with 3 buttons, which control a menu displayed on the LCD. I keep track where I am in the menu with a variable called 'menu' (int). In a timed loop (using interrupts) I check the buttons and then modify the variable 'menu' appropriately. There is a switch/case statement that prints the menu text corresponding to the number in 'menu'.
The following code is responsible for reading the answer into array (which is later converted).
void SerialRead(int port){
Start:
if (Serial.available() < 0){
goto Start;
}
int i=0;
while (Serial.available() > 0){
array[i] = Serial.read();
i++;
}
}
I have narrowed the problem down to this segment. Meaning, if I don't execute this function (but everything else) there is no problem at all. As soon as this function is called, my 'menu' variable gets somehow overwritten and the menu is not displayed anymore.
I put a default case in my Switch/Case statement (as explained above) to print 'menu' on the LCD. As expected, this works and it shows a really high number (3395) which indicated that we are in menu index 3395...
I have spent a couple hours already troubleshooting but without luck. However, I was able to narrow the problem down to a single line of code:
while (Serial.available() > 0){
As soon as I replace the expression with something else (like i<2) the problem disappears.
I have done some research online and found a post in this forum about an Serial.available() issue. They claimed that a delay needed to be inserted after a Serial.read and before Serial.available() is executed again.
Has anyone encountered a similar issue? Any suggestions what it might be/what might solve it? Is there a bug in the serial library that could cause it?
I am aware that interrupts could cause such issues, but since I can narrow it down to a single line of code I find the repeatability a little odd.