How to Convert Char to String in Arduino

Ammar Ali Feb 02, 2024
  1. Convert char to String Using the String() Function in Arduino
  2. Convert char to String Using the Serial.readString() Function in Arduino
  3. Practical Considerations
How to Convert Char to String in Arduino

This tutorial will discuss two methods to convert a char into a String. The first method is to use the String() function, and the second method is to use the Serial.readString() function.

Convert char to String Using the String() Function in Arduino

To convert char to String we can use the String() function. This function takes a variable as an input and returns a String object.

void loop() {
  char myChar = 'char';
  String myString = String(myChar);
}

In the above code, myChar is a variable of type char to store the given char and myString is a variable of type String to store the conversion result.

Convert char to String Using the Serial.readString() Function in Arduino

If you are reading data of type char from a serial port in Arduino and want to convert the data into String, you can do that using the Serial.readString() function. Using this function, you can convert the received data directly rather than converting it later with another function. The Serial.readString() function reads char data from the serial port and converts it into a String.

void loop() { String myString = Serial.readString(); }

In the above code, myString is a variable of type String to store the data from the serial port. Note that this function will be terminated if it times out. Check setTimeout() to set the time out of the serial.

Practical Considerations

While both methods achieve the conversion of char to String, it’s crucial to consider the context of your project. The String() function is useful for standalone conversions, while Serial.readString() streamlines conversions during serial communication.

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