kaavyab
September 19, 2020, 6:44am
1
Hy,
wishing good day .
am unable to do string compare for the following code . Please suggest any solution for this as soon as possible.
Compare string of the serial interface using strcmp and Serial.read() - Programming Questions - Arduino Forum
I got code form the above link.
[code]
void setup()
{
Serial.begin(9600);
}
void loop()
{
char inSerial[5];
int i=0;
delay(1000);
if (Serial.available() > 0)
{
while (Serial.available() > 0) {
inSerial[i]=Serial.read(); //read data
i++;
}
inSerial[i]='\0';
Check_Protocol(inSerial);
}
};
void Check_Protocol(char inStr[])
{
Serial.print("Command: ");
Serial.println(inStr);
Serial.println("Check_Protocol");
if(strcmp(inStr,"ON")==0) Serial.println("on");
else if(strcmp(inStr,"OFF")==0) Serial.println("off");
}
[/code]
What have you got Line ending set to in the Serial monitor ?
If it is set to anything except No line ending then the string will include the line ending character(s) so will not match either "ON" or "OFF"
Try printing the length of inStr before testing its value. Is it what you expect ?
kaavyab
September 19, 2020, 7:14am
3
Thank you for fast response.
Here in serial port , it is taking enter also a character . how can i avoid that .
kaavyab
September 19, 2020, 7:30am
4
Hy thank you .. i got to know my mistake and solved it .
here is the code .
void setup()
{
Serial.begin(9600);
}
void loop()
{
char inSerial[5];
int i=0;
delay(1000);
if (Serial.available() > 0)
{
while (Serial.available() > 0) {
inSerial[i]=Serial.read(); //read data
i++;
}
inSerial[i]='\0';
Check_Protocol(inSerial);
}
};
void Check_Protocol(char inStr[])
{
Serial.print("Command: ");
Serial.println(inStr);
Serial.println("Check_Protocol");
if(strcmp(inStr,"ON\n")==0) Serial.println("on");
else if(strcmp(inStr,"OFF\n")==0) Serial.println("off");
}
I am glad that you got it working. Personally I would prevent the CR or LF from being added to the string if one is received. That way any combination of them used as a terminator would work without more tests at the validation stage
You might find it helpful to read Serial input basics - updated
Robin2
September 19, 2020, 7:37am
6
UKHeliBob:
If it is set to anything except No line ending then the string will include the line ending character(s) so will not match either "ON" or "OFF"
Using the strstr() function rather than strcmp() can avoid that problem.
...R