Publishing float to particle.variable

Hi,

I have a temp/humidity sensor, I am reading the values using
float humidity = dht.getHumidity();
float temperature = dht.getTempCelcius();

I have tried pretty much all I can think of to publish these variables using particle.variable but I am either getting no value or garbage. Can someone assist on what needs to be done to achieve this starting with the definition of the variable in the particle.variable function please? I’d like to be able to see the humidity/temperature in 2 decimal format.

Thanks.

Andre

You need something like this:

char eventData[10];
sprintf(eventData, "%.2f", temperature);
Particle.publish("temperature", eventData, 60, PRIVATE);

As variable it would be:

Spark.variable("temperature", &temperature, DOUBLE);
Spark.variable("temperature", &temperature, DOUBLE);

this is the old notation. Nowadays you’d write

double temperature;
Particle.variable("temperature", temperature);

float is not supported as native type Particle.variable().

2 Likes

Thanks, worked like a charm, after using the sprintf conversion you suggested I used Particle.variable(“temperature”, eventData); and displayed as a string. Thanks.

To access with Particle.variable(), you should be able to declare it as a double instead of as a float, and not need to do any conversion at all! :wink: It’s Particle.publish() that needs it to be a String. Particle.variable() supports int, double and String data types.

Thanks, I do a lot of work with meters and always use double. but the tutorial:
https://docs.particle.io/tutorials/projects/maker-kit/#tutorial-4-temperature-logger
uses float for fahrenheit and celsius

so that threw me off. I’d like to update the example and change those to double as I did in my version of the example. kinda silly but at least it would be something I could contribute to particle.
Dave Carlson

2 Likes