Hi @crisljtc_89 ,
the main issue has already been pointed out in post #7 by @b707:
You clear the string before it can be evaluated.
However also this construction seems to be prone to error:
String respuesta="";
while (Serial2.available() > 0) {
char receivedChar = Serial2.read();
if (receivedChar == '\n') {
Serial.println(respuesta);
delay(1000); // Print the received message in the Serial monitor
respuesta = ""; // Reset the received message
} else {
respuesta += receivedChar; // Append characters to the received message
}
}
Just assume that some characters on Serial2 are delayed. Serial2.available() would be 0 and the sketch would leave the while() loop with an inconsistent message and in the next loop it would clear the string, read the rest of the message and probably have trouble to synchronize again.
A solution could be to
- set respuesta = "" as you do here just before the while() loop
- use a second String variable to collect the Serial input (e.g. call it String tempString;)
- set repuesta = tempString and clear tempString if a \n was received
String tempString = "";
void loop(){
// ...
String respuesta = "";
while (Serial2.available() > 0) {
char receivedChar = Serial2.read();
if (receivedChar == '\n') {
respuesta = tempString;
tempString = "";
Serial.println(respuesta);
delay(1000); // Print the received message in the Serial monitor
} else {
tempString += receivedChar; // Append characters to the received message
}
}
// ...
Now a (hopefully) valid message, at least closed by '\n' will be available from after the while()-loop until the sketch reaches the while() loop again OR respuesta will be an empty string.
Not tested but should work ...