Conversión de una int o Cadena a una matriz char en Arduino
Estoy obteniendo un valor int de uno de los pines analógicos de mi Arduino. ¿Cómo concateno esto a un String
y luego convertir el String
a un char[]
?
Se sugirió que lo intentara char msg[] = myString.getChars();
, pero estoy recibiendo un mensaje que getChars
no existe.
3 answers
-
Para convertir y anexar un entero, utilice operador += (o función miembro
concat
):String stringOne = "A long integer: "; stringOne += 123456789;
-
Para obtener la cadena como tipo
char[]
, use toCharArray():char charBuf[50]; stringOne.toCharArray(charBuf, 50)
En el ejemplo, solo hay espacio para 49 caracteres (suponiendo que esté terminado por null). Es posible que desee hacer que el tamaño dinámico.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-14 13:36:08
Solo como referencia, aquí hay un ejemplo de cómo convertir entre String
y char[]
con una longitud dinámica -
// Define
String str = "This is my string";
// Length (with one extra character for the null terminator)
int str_len = str.length() + 1;
// Prepare the character array (the buffer)
char char_array[str_len];
// Copy it over
str.toCharArray(char_array, str_len);
Sí, esto es dolorosamente obtuso para algo tan simple como una conversión de tipo, pero lamentablemente es la forma más fácil.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-27 02:15:55
Nada de eso funcionó. Aquí hay una manera mucho más simple .. la etiqueta str es el puntero a lo que ES un array...
String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string
str = str + '\r' + '\n'; // Add the required carriage return, optional line feed
byte str_len = str.length();
// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...
byte arrayPointer = 0;
while (str_len)
{
// I was outputting the digits to the TX buffer
if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
{
UDR0 = str[arrayPointer];
--str_len;
++arrayPointer;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-22 15:54:51