This writeup will discuss the Serial.readStringUntil() function in-depth and cover an example code of this function in Arduino programming.
What is the Serial.readStringUntil() function?
The Serial.readStringUntil() function is a part of the Serial library in the Arduino programming language. It is used to read data from the serial port of the Arduino board until a specific character is detected. The function returns a String object that contains the data read from the serial port.
Syntax
The syntax for the Serial.readStringUntil() function is as follows:
Parameters
The function takes a single argument, which is the terminator character.
Terminator character: The character to search for in the received data stream. Allowed data types are char.
Returns
The Serial.readStringUntil() function returns the complete String read from serial buffer once the terminator character is received
Note: The Serial.readStringUntil() function discards the terminator character.
Example Arduino Code
Following example code explains the working of Serial.readStringUntil() function in Arduino programming.
Serial.begin(9600);
}
void loop() {
// Checks if there is any data available to be read from the serial buffer
if (Serial.available() > 0) {
/* Reads a string from the serial buffer until it encounters the '\n' character, which indicates the end of the string*/
String inputString = Serial.readStringUntil('\n');
// Prints the received string to the serial monitor
Serial.print("Received String: ");
Serial.println(inputString);
}
}
In the setup() function, the serial communication is begun by defining the baud rate.
In the loop() function, the sketch checks data from the serial buffer using the Serial.available() function. If there is data available, the sketch reads a string from the serial buffer until it encounters the ‘\n’ character using the Serial.readStringUntil() function.
Once the string has been read, it is stored in a variable called inputString. Finally, the sketch prints the received string to the serial monitor.
Output
In the output we can see different strings printed on the serial monitor.
Conclusion
The Serial.readStringUntil() is a useful function in the Arduino programming language that allows for the reading of strings from the serial port until a defined terminator character is received. This function simplifies the process of working with serial data. For more details on Serial.readStringUntil() function read the article.