How to Read String in Arduino Serial Port

Ammar Ali Feb 02, 2024
  1. Reading String Using Serial.readString() Function in Arduino
  2. Reading String Using Serial.readStringUntil() Function in Arduino
How to Read String in Arduino Serial Port

In this tutorial, we will discuss how to read a string from the serial port using the Serial.readString() function and Serial.readStringUntil() function in Arduino.

Reading String Using Serial.readString() Function in Arduino

The Serial.readString() function reads characters from the serial and stores them into a string. It will terminate if it times out. See setTimeout() to set the timeout of the Serial.readString() function. See the below example.

String myString;
void setup() { Serial.begin(9600); }
void loop() {
  if (Serial.available()) {
    myString = Serial.readString();
    Serial.println(myString);
  }
}

In the above code, myString is a variable of type String to store the string from the serial port. The Serial.available() function is used to check if data is available on the serial port or not. if data is available at the serial then we will read it into a string and after that, we are printing the received string on the serial monitor.

Reading String Using Serial.readStringUntil() Function in Arduino

The Serial.readStringUntil() function reads characters from the serial port until a specific character arrives and stores them into a string. It will terminate if it times out. See setTimeout() to set the timeout of the Serial.readStringUntil() function. See the below example.

String myString;
char myChar = 'a';
void setup() { Serial.begin(9600); }
void loop() {
  if (Serial.available()) {
    myString = Serial.readStringUntil(myChar);
    Serial.println(myString);
  }
}

In the above code, myString is a variable of type String to store the string from the serial port, and myChar is a variable of type char used to store the terminator character. The Serial.available() function is used to check if data is available on the serial port or not. If data is available at the serial, then we will read it into a string, and after that, we print the received string on the serial monitor. Note that the Serial.readStringUntil() only reads a string up to the terminator character.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - Arduino String

Related Article - Arduino Serial