Serial.find() trouble

Hi, I need to find a symbol in the serial port sent to the hardware, and then execute a command to send an SMS to a specific number, but unfortunately this only works in the first case. Does anyone know what the problem is? Code:

if (Serial.available()>0) {
if (Serial.findUntil(target1,"\0")){
buff = Serial.readString();
sendSMS("number1",buff);
Serial.println(buff);
}
else if (Serial.findUntil("002","\0")){
buff = Serial.readString();
sendSMS("number2",buff);
Serial.println(buff);
}
else if (Serial.findUntil("003","\0")){
buff = Serial.readString();
sendSMS("number3",buff);
Serial.println(buff);
}
}

Finduntil consumes characters from the serial port. If you have sent 002, those characters were read and discarded looking for target1.

You need to read the data into a buffer and then check which one you got.

Thank you for your explanation. I'm still a beginner and I don't really understand it.Can you tell me what search functions are available in the buffer? Just when I tried to use stream.find arduino ide didn't like it.

Try readBytesUntil

It's impractical to search in the serial input buffer. You have to read the incoming serial data into a buffer that you have declared in your program. Then you can use strcmp() or strncmp() to find the sequences you are looking for, in that buffer.

This is double terminated. A string constant "003" already has a terminating null embedded.

Thank you, but the string.startsWith function helped me

Great!

Thanks

It's helpful if you post your solution, so other people can benefit from it if they have the same problem.

Solving the problem:If, as in my case, it is necessary to find a certain character at the beginning of the transmitted data in order to execute a certain program, then instead of using the Serial function.find should use the string.startsWith function after writing the data from the port to the buffer with the Serial.ReadString function.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.