Insert a fixed data with a char in a the Spark.publish's optional data field

Hey guys
Is there any way to insert a fixed data with a char in a the Spark.publish’s optional data field? I mean something like this:

Spark.publish("Spark1", "The person number" string1 "produced a data", PRIVATE);

When I tried this, I received the following error:

error: expected ')' before 'string1'

@BDub @mdma

Thanks in advance.

This should work:

    Spark.publish("Spark1", "The person number" + string1 + "produced a data", PRIVATE);
1 Like

Thanks for your reply, but unfortunate when I tried this I got this error:

error: invalid operands of types 'const char [18]' and 'char [50]' to binary 'operator+'

Any other suggestion?

How did you define string1?

I tried with this code and it compiled fine

void setup() {
 String string1 = "";
 Spark.publish("Spark1", "The person number" + string1 + "produced a data", PRIVATE);
}
2 Likes

Dear @kennethlimcp

I was defining string1 at the beginning before the setup () like this:

int counter= 0;
char string1[18] = "";
extern char* itoa(int a, char* buffer, unsigned char radix);

then in the loop () I did that:

counter++;
itoa(counter, string1, 10);
Spark.publish("Spark1", "The person number" + string1 + "produced a data", PRIVATE);

So I converted the integer storage, counter, to a character string, string1, to publish it on the cloud.
Is this a correct way to do it?

even after I defined the string1 as you suggested, I got the following error:
no matching function for call to 'itoa(int&, String [1], int) invalid operands of types 'const char [18]' and 'String [1]' to binary 'operator+

Thanks.

Any other suggestions @bko?

Hi @Ahmedsa1983

If you want to stay with char array (C strings) and not use Arduino String objects, then I would switch to sprintf() like this:

int counter = 0;
char string1[65];
...
sprintf(string1, "The person number %d produced a data", counter++);
Particle.publish("Spark1",string1,PRIVATE);
2 Likes

Thanks a lot @bko. I’ll try that and see what I get.

Your suggestion worked for me, but I required to change the initial value for the counter to be equals 1 instead of 0 because I got this as the first person:

The person number 0 produced a data

Thanks a lot @bko :wink:

1 Like