0

I have 3 variables declared as character arrays in arduino: id, temp, humidity.

How could I append them and write them as a string separated by commas.

For example: id:12,temp:23,humidity:50

This is my code so far.

Kind regards

char id[2];
char humidity;
char temp[2];
string example;

void setup()
{
//setup stuff
 }

void loop(void)
{
// Receive message

e = sx1272.receivePacketTimeout(10000);
e = sx1272.getRSSIpacket();

Serial.println(e, DEC);

if( sx1272.packet_received.length < 14 )
{
Serial.println("Missing data");
}
else
{

id[0] = sx1272.packet_received.data[0]; 
id[1] = sx1272.packet_received.data[1];  
humidity = sx1272.packet_received.data[4]; 
temp[0] = sx1272.packet_received.data[9]; 
temp[1] = sx1272.packet_received.data[10]; 
}

example = String.format("id:%c,crc:%c,humidity:%c)", id, crc, humidity);

1 Answers1

1

You can also use string format in order to be more precise.

 String example = String.format("id:%s,temp:%s,humidity:%s", id, temp, humidity)
loshkin
  • 1,600
  • 2
  • 21
  • 38
  • Hi @toshkinl, Does it matter that the variables are char arrays? They are not strings - can I use .format on them? I'm getting the error `expected primary-expression before '.' token` thanks –  Jun 24 '15 at 10:56
  • It doesn't matter where you declare the String, you can declare it when you have the values of your fields. And char arrays and strings are almost the same. String is immutable. Char array is not. string is implemented with a char array underneath but every time you try to modify it (like with concatenation, replace etc.) it gives you a new String object. I thought that arduino is written in java. Fortunately it is c++. You can see this [link](http://stackoverflow.com/questions/10410023/string-format-alternative-in-c) to see the c++ string formatting alternative. – loshkin Jun 24 '15 at 11:11
  • Thank you for explaining. Do you know why it is giving the `expected primary-expression before '.' token` error? I've amended the code in my original post. kind regards –  Jun 24 '15 at 11:14
  • Because I've given you the java code for string format. You need the c++ one [from here](http://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf) – loshkin Jun 24 '15 at 11:21