Understanding the Serial.readString() function
The Serial.readString() function is a part of the Arduino Serial Library, which enables communication between the microcontroller and the computer or other external devices.
This function allows the microcontroller to read a string of characters sent from a serial connection. The function reads data from the serial buffer and returns the data in the form of a String object.
This function is inherited from the Stream class.
Syntax
The syntax of this function is as follows:
Parameters
This function does not take any parameters. It only reads the serial port object.
Returns
Returns a String containing the characters received through the serial port. The string ends with the last character received, which is often a newline character (\n). If no characters are available in the serial buffer, the function returns an empty string (“”).
Note: If the end line character is available in data, the function will not terminate early. The string returned may contain the carriage return characters.
Example Code
Below code demonstrate use of Serial.readString() function in Arduino programming:
Below code demonstrate use of Serial.readString() function in Arduino programming:
Serial.begin(9600);
}
void loop() {
Serial.println("Enter data:");
while (Serial.available() == 0) {} //wait for data available
String teststr = Serial.readString(); //read until timeout
teststr.trim(); // remove any \r \n whitespace from String end
Serial.print("Data Input: ");
Serial.println(teststr);
if (teststr == "hello") {
Serial.println("Hello to you too!");
} else {
Serial.println("I'm sorry, I didn't understand your input.");
}
}
In the setup() function serial communication is enabled using a baud rate of 9600.
In the loop() function, the code prompts the user to enter data by printing “Enter data:” to the serial monitor. It then waits for data to be available by checking if the serial buffer is empty using the Serial.available() function.
Once data is available, the code reads the data as a String using the Serial.readString() function and removes any whitespace characters at the end of the String using the trim() function.
The code then compares the input String to the String “hello”. If the input String is “hello”, the code responds by printing “Hello to you too!” to the serial monitor. Otherwise, it prints “I’m sorry, I didn’t understand your input.” to the serial monitor. The loop() function then repeats, prompting the user for more input.
Output
In the output we can see different strings that code reads from the user and matches it with the string “hello”.
Conclusion
The Serial.readString() function in Arduino reads serial data sent from a computer or other devices to the board. Using this function, we can read and compare the input serial string data to generate output responses such as controlling sensors and hardware devices.