Atof, atoi, and MQTT, convert byte* to char[]

Hello,
I've been playing with MQTT (using what Kitard provided). Last night, I figured out how to turn topics into integers, but I'm struggling with turning the payload into an int or a float. Here's what I know.

client.publish("1111", "76.5"); //assume this was published

I believe this is the result, if you could magically look at the data:

void callback(char* topic, byte* payload, unsigned int length)
topic=1111
payload=76.51111
length=4

The payload starts with the message that was published, but has the topic name appended. In order to convert the payload into a float, you need to separate the trailing 1111 from the payload somehow. On Arduino, this is done like this:

int mytopic = atoi (topic);
payload[length] = '\0';
float mymsg = atof( (const char *) payload);

So it looks like:
payload=76.5\n111

The atoi() works like it should, and I get integer topic numbers like I expect.

The atof() function scans payload until it hits the end of line character '\n', and converts "76.5" to a float. That works on the Arduino, but not on the Spark. On the Spark, the atof always returns 0.

If anyone has any ideas for me to try tonight, I'd appreciate any advice. If there's a different way of forming the character array manually? Last night, I tried filling a char with the first four bytes of payload, then doing atof. But that didn't work, still getting 0.0's.

Maybe '\n' isn't the right end of line character for Spark's version of atof?

It’s working for me… give this a try in Spark Dev

#include "application.h"

char myChar[24] = "76.911";
double myDouble = 0.0;
int myInt = 0;

int f(String);

void setup() {
    pinMode(D7,OUTPUT);
    digitalWrite(D7,HIGH);
    Spark.variable("myDouble", &myDouble, DOUBLE);
    Spark.variable("myInt", &myInt, INT);
    Spark.function("f", f);
    myDouble = atof(myChar);
    myInt = atoi("34");
}

void loop() {

}

int f(String s) {
  myDouble = atof(s.c_str());
  digitalWrite(D7,!digitalRead(D7));
  return 200;
}

1 Like