patpin
December 17, 2019, 9:37pm
1
Hello,
I never have the right result on a compare with this code
void setup(){
Serial.begin(115000);
}
void loop()
{
char message[20];
int charsRead;
if (Serial.available() > 0) {
charsRead = Serial.readBytesUntil('\n', message, sizeof(message) - 1);
message[charsRead] = '\0';
Serial.print("You entered: ");
Serial.println(message);
}
Serial.print("You entered: ");
Serial.println(message);
Serial.print("compare to PC=");Serial.println(strcmp(message,"PC")==0);
strcpy(message,"");
Serial.println("----");
delay(2000);
}
even when I enter PC in the serial monitor send box. Somebody can help?
Robin2
December 17, 2019, 9:50pm
2
Maybe the strstr() function would be more suitable. It checks for string within a string.
...R
Serial Input Basics - simple reliable non-blocking ways to receive data.
What have you got the Line ending set to in the Serial monitor ?
patpin
December 17, 2019, 10:12pm
5
Robin2:
Maybe the strstr() function would be more suitable. It checks for string within a string.
...R
Serial Input Basics - simple reliable non-blocking ways to receive data.
This was the good solution!!! It gives the searched string when the search string is present, otherwise NULL. THanks !!
I never have the right result on a compare with this code
What do you consider to be the right result when you enter PC ?
patpin:
NL & CR
Your "message" contains extra '\r' at the end.
1. When your codes are executed, the following results are found on the Serial Monitor (SM) before entering any data from the InputBox of Serial Monitor. The behavior of the Serial Monitor should not be like this as stated; the Serial Monitor should remain until data/string is entered.
Figure-1:
Figure-2:
2. Let us adjust your codes as follows so that the string entered from the InputBox of SM appear on the OutputBox of the Serial Monitor.
char message[20];
int charsRead;
void setup()
{
Serial.begin(115000);
}
void loop()
{
//char message[20];
//int charsRead;
//if (Serial.available() > 0)
// {
byte n = Serial.available();
if ( n != 0)
{
charsRead = Serial.readBytesUntil('\n', message, sizeof(message) - 1);
message[charsRead] = '\0';
Serial.print("You entered: ");
Serial.println(message);
// }
// Serial.print("You entered: ");
// Serial.println(message);
// Serial.print("compare to PC=");
//Serial.println(strcmp(message, "PC") == 0);
//strcpy(message, "");
// Serial.println("----");
}
delay(2000);
}
Figure-3: