Serial.findUntil() reads data from the serial buffer until a target string of given length or terminator string is found.
Serial.findUntil() inherits from the Stream utility class.
Use the following function to search for a given target string until finding a terminator.
Serial.findUntil(target, terminal)
The function admits the following objects and parameters:
Serial: serial port object. See the list of available serial ports for each board on the Serial main page.target: the string to search for. Allowed data types: char.terminal: the terminal string in the search. Allowed data types: char.The function returns true if the target string is found before the terminator, otherwise false. Data type: bool.
The following code waits for the target string OK to appear before the terminator CANCEL:
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("Type a message. Looking for 'OK', but will stop if 'CANCEL' appears.");
}
void loop() {
if (Serial.available()) {
// Try to find "OK", but stop early if "CANCEL" is found first
if (Serial.findUntil("OK", "CANCEL")) {
Serial.println("Found OK before CANCEL!");
} else {
Serial.println("Did not find OK (CANCEL appeared first or timed out).");
}
}
delay(1000);
}