Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int or String to a char array on Arduino

I am getting an int value from one of the analog pins on my Arduino. How do I concatenate this to a String and then convert the String to a char[]?

It was suggested that I try char msg[] = myString.getChars();, but I am receiving a message that getChars does not exist.

like image 280
Chris Avatar asked Sep 12 '11 05:09

Chris


People also ask

How do I convert a string to a char in Arduino?

You can convert it to char* if you don't need a modifiable string by using: (char*) yourString. c_str();

How do I convert a string to an array in Arduino?

Basically String type variable in arduino is character array, Conversion of string to character array can be done using simple toCharArray() function. Getting string value in character array is useful when you want to break single string into parts or get part of string.

How do I convert an int to a char array?

One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );


1 Answers

  1. To convert and append an integer, use operator += (or member function concat):

     String stringOne = "A long integer: ";  stringOne += 123456789; 
  2. To get the string as type char[], use toCharArray():

     char charBuf[50];  stringOne.toCharArray(charBuf, 50) 

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

###Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes of program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

like image 91
Peter Mortensen Avatar answered Sep 27 '22 17:09

Peter Mortensen