Converting String from Particle Subscribe to integer

I want to collect the temperature from one photon, convert it to a string and publish it to the cloud. Then subscribe to it with my Argon and print it on an LCD. Maybe a string isn’t the best choice, but I was hoping you guys could point me in the right direction.

I am practicing for when I start putting this on a mesh network.

Here is what I have going on in my program:

//Publishing from Photon:
Particle.publish("DataShare", String(fahrenheit,2), PRIVATE);

//Subscribed from Argon:
// void setup():
Particle.subscribe("DataShare", TemperatureHandler);

//Handler Function:
void TemperatureHandler(const char *event, const char *data){
    Temp = printf( "%d\n", data);

//void loop():
1 Like

Could you share your complete code?

Also, you’re probably going to want to use snprintf() in this situation. With complete code to provide context you’ll see why.

1 Like

When you subscribe to a PRIVATE event your Particle.subscribe() scope needs to be MY_DEVICES - with device OS v1.0.0 (already since 0.8.0-rc.4 on Gen1&2, for Gen3 this will be true soon) you won’t be allowed to subscribe unscoped.

printf() is not a function you can use on these devices because you have no stdout channel to print to. As @nrobinson2000 already said, you can only use sprintf() or better/safer snprintf() to store formatted strings into a buffer for further action, but that’s also not what you want, since the return value of printf(), sprintf() and snprintf() would only tell you the number of characters that were “printed” but not the value of the integer you injected into the string.

You want to convert a string into an int and for that you’d use atoi().
For multiple integers you could also use sscanf() (unfortunately not for floating point types - although there are workarounds too).


@ScruffR, thanks for the help. I am still struggling with it. the atoi() didn’t work. I have seen where other people have made it work. I feel like it may be due to how I am sending throught the Particle.publish().

I will work on it some more tonight.

1 Like

If your incoming data represents a float then you’d use atof() instead.
But since you used %d in your printf() statement I assumed you’d get an integer.

However, in order to advise we’d need to know exactly what data you are receiving.

Also have you considered this advice?

1 Like