Convert a char to a String

I want to turn the result of Serial.read(), which returns a char, into a String. I've looked elsewhere to no avail. I've tested String test= String (NameOfChar) as suggested. Thanks!

You can try this:

String phrase;
char c;
c=Serial1.read();
phrase = String(phrase + c);

You can try this:

Calling the constructor to create a temporary object, then calling the copy constructor to copy the object to the existing instance is a huge waste of resources. Two constructor calls and two destructor calls, when the String class has a += operator overload that can append a char to a String with no constructor calls and no destructor calls, is a real waste.

DBids35 - what are you trying to do? The Serial.read() function returns ONE character. That will NEVER equal a String or a string.

Urgh.... String ... shudder

Don't get me started...

If your using Serial.read(), you can store the incoming chars in a char array, and send a terminating char like a period or something to let the code know it has reach the end of the string.

example:

char My_Array[20];
int count = 0;

//inside loop()

if(Serial.available() > 0) //something is there to be read
{
  char C = Serial.read();

   if(C == '.') 
   {
     int i = 0;
     while (i != count) 
      {
         Serial.print(My_Array[i++]);
      }
   }
   else  My_Array[count++] = C; 
}

Serial.read() returns an int not a byte the returned value can be -1 (no data available).

Mark

I am attempting to read an RFID tag, then print it to a OLED display. I've already successfully printed to the serial monitor, but the display command for the OLED I'm using needs a string to print.

Try sprintf().

Could you give me more information on sprintf()? I've looked into it and can't seem to find an example that will fit my purpose.
Thanks!

char buffer [40]; //whatever
int len = sprintf (buffer, "%08x", rfidTagVal);

will print the unsigned long variable "rfidTagVal" as an eight digit hex value, with leading zeroes.

can't seem to find an example that will fit my purpose.

You didn't say what your purposes was, exactly.

What sort of "string" does your OLED display allegedly require ?

michinyon:
What sort of "string" does your OLED display allegedly require ?

Some code and links to librarys would be useful here...

DBids35:
I want to turn the result of Serial.read(), which returns a char, into a String. I've looked elsewhere to no avail. I've tested String test= String (NameOfChar) as suggested. Thanks!

Capturing characters into a String.

// zoomkat 7-30-11 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later

String readString;

void setup() {
  Serial.begin(9600);
  Serial.println("serial test 0021"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    delay(2);  //delay to allow byte to arrive in input buffer
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);

    readString="";
  } 
}

DBids35:
I want to turn the result of Serial.read(), which returns a char, into a String. I've looked elsewhere to no avail.

Its curious that you haven't found anything on this, because it's a requirement that crops up very often.

I recommend you stick to plain old char arrays rather than using the Arduino String class. Firstly because the String class doesn't make the solution any simpler. Secondly because the String class uses dynamic memory which introduces the risk of heap fragmentation. Most importantly, because it currently exposes a bug in the Arduino runtime library which can cause memory corruption.

Essentially you just need to use a char array to hold the sequence of chars, and an integer to record how many chars you currently have stored in the array. You will need to have some scheme to work out when the string is complete. If your input line is terminated by a carriage return or newline then you could just keep reading until you receive that:

const int buflen = 32; 
char buf[buflen];
int len = 0;

if(Serial.available())
{
    char c = Serial.read();
    if((c == '\n') || (c == '\r'))
    {
        if(len > 0)
        {
            handleCommand(buf);
            len = 0;
        }
    }
    else
    {
        if(len < buflen)
        {
            buf[len++] = c; 
            buf[len] = 0; // append null terminator
        }
    }
}

I actually just figured out how to do this. Instead of getting a bunch of chars and making them into a string, you can simply get a string from serial. Try this:

void setup(){
  Serial.begin(9600);
}
String Message;
void loop(){
  while(Serial.available() > 0){
    Message = Serial.readString();
  }
  Serial.println(Message);
}

Hope I helped!

fourth-decent:
Hope I helped!

Perhaps, if the OP is still alive...

DBids35:
I want to turn the result of Serial.read(), which returns a char, into a String. I've looked elsewhere to no avail. I've tested String test= String (NameOfChar) as suggested. Thanks!

Hope I helped!

No, not helping. Don't use String™, which you would have known if you read the last post. It provided a good solution with the char arrays. See also the "Serial Input Basics" examples in the Useful Links page at the top.

And don't resurrect ancient 4 year-old threads. Didn't you see the warning before you posted?

BulldogLowell:
Perhaps, if the OP is still alive...

I need to leave my long laugh when I read this! Very spontaneous. :slight_smile:

to converting any datatype into string just concat the variable to an empty string

char chr='a';
String str=""+chr;

@logans, you should read the WHOLE thread before posting. You did not add anything except a bad example to an ancient thread. Please read Reply #16 and this.