I am executing a function in Arduino by giving String input to the serial monitor.
The issue here is when I enter SHOW$
, the function showData()
works but when I enter the same SHOW$
, it doesn't gets called.
I want to call the function showData()
every time i enter the SHOW$
text into the serial console.
My question here is to what mistake I am doing here, and what is the solution for this.
String strReq = "";
char inChar = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available())
{
inChar = Serial.read();
if (inChar == '$') {
Serial.println(" Received String :");
Serial.print(strReq);
if (strReq.equalsIgnoreCase("SHOW"))
showData();
Serial.flush();
strReq = "";
} else {
strReq = strReq + inChar;
}
}
}
void showData() {
Serial.print("Showing Information");
}
2 Answers 2
The root of your problem seems to be not knowing what Serial.flush()
does.
It pre-Arduino 1.0.0 times Serial.flush()
used to clear any data in the serial's RX buffer. It would throw it away. In your code that would throw away the line ending \r\n
that is sent along with the command.
However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer. This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.
This change was not widely documented, but it is mentioned in the manual:
Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)
So with Serial.flush()
acting like it does in current versions, you would get a different string the second time around. You would see:
SHOW$
\r\nSHOW$
\r\nSHOW$
and so on.
You have come up with a "fix", which uses String::trim()
to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings. However it would be far better to ignore them in the first place and not need to do the trimming.
The simplest way would be to only add characters to your string if they are printable:
if (inChar == '$') {
Serial.println(" Received String :");
Serial.print(strReq);
if (strReq.equalsIgnoreCase("SHOW"))
showData();
Serial.flush();
strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
strReq = strReq + inChar;
}
A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.
The solution was to use String.trim() function. Thanks guys for giving a quick reply on the question.
Explore related questions
See similar questions with these tags.
else if (inChar >= 32) {