Hi everyone! I'm new to arduino, and for my first project I wanted to build a simple serial menu. (code below)
while(!Serial.available());
char choice = Serial.parseInt();
while(Serial.available()) Serial.read(); //get rid of CR
switch(choice) {
case 1:
// some code
break;
case 2:
char content[1024];
while(!Serial.available());
String contentStr = Serial.readString();
// some code to save contentStr on sd card (it works);
break;
case 3:
// some code
break;
case 4:
// some code
break;
default:
// print invalid option
break;
}
My problem is the following: case 2 does its job as it should, but my menu does not recognize any case below it (ex: if i press 5 i should get the invalid option message, if I press 4 the code from case 4 should execute, but I get nothing, etc.).
If i comment the line: String contentStr = Serial.readString(); in case 2 suddenly all the other cases work.
Can somebody explain to me this strange behaviour? I should mention that I use that same method of reading a string in other functions (not in a switch) and it works and I get the expected output.
Without knowing the rest of the code, hard to guess what's wrong. You use blocking while loops which is not a good idea. You could try to use Serial.readStringUntil('\n') instead of what you got. If you are using an AVR based MCU, the String data type may cause malfunction.
Because you initialize a local variable in 'case 2:' you can't reach any case after that without skipping the initialization. To fix it, either make the variable MORE local (local to case 2):
case 2:
{
char content[1024];
while(!Serial.available());
String contentStr = Serial.readString();
// some code to save contentStr on sd card (it works);
}
break;
or don't initialize the local variable in the declaration:
case 2:
char content[1024];
while(!Serial.available());
String contentStr ;
contentStr = Serial.readString();
// some code to save contentStr on sd card (it works);
break;