Particle Function returning a String

How can I use a Particle Function to return a String (instead of an integer)?

When using String as the return type, I am getting the following compile errors:

no matching function for call to 'CloudClass::_function(const char [8], String (*&)(String))
invalid conversion from 'String (*)(String)' to 'int (*)(String)' [-fpermissive]

You can't, that's not how Particle.function works. What is your reason for wanting a string instead of an int?

The reason is because I need to find the value of multiple variables (separated by a comma) but do not want to find each value using a separate Particle variable.

There are several possibilities to solve your problem. The return from a function is a 32 bit integer, so you could combine values into a single int if they’re small enough or there aren’t too many of them. If that doesn’t work, you could certainly have a single variable (string) that’s a concatenation of your other variables, so you can get them all with a single Particle.variable. You could also publish a string that combines all the data. What works for you might depend on how you can pull apart the combined data on the receiving end.

6 Likes

Thanks @Ric.

"If that doesn’t work, you could certainly have a single variable (string) that’s a concatenation of your other variables, so you can get them all with a single Particle.variable. "

How does one do that?

I'm sure there are several ways to do this. If you want to have named variables, you could create them, and a "master" string that would contain all the variable values. For instance, here's an example with four variables,

char master[400];
char varA[100];
char varB[100];
char varC[100];
char varD[100];

Master would be your Particle.variable. Any place in your code where any of the four variables is set to a new value, you would need to call a function that updates the value of master,

void createParticleVariableString() {
    snprintf(master, sizeof(master), "%s,%s,%s,%s", varA, varB, varC, varD);
}

This would give you a comma separated c-string of all your values.
2 Likes

Thank you very much @Ric. I appreciate this clear code. This should work.

If I may trouble you with one small thing. Not being much of a C programmer, since my variables are int and long, how does one convert to char?

You can use snprintf() for that too.

snprintf(varA, sizeof(varA), "%d", someIntVariable);

You use %d for ints, %f for floats or doubles, %s for c-strings, etc. See here for snprintf() reference, and here for an explanation of the format specifiers.

2 Likes