knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

Payload to value (mqtt_basic.ino) #995

Closed HaViGit closed 1 year ago

HaViGit commented 1 year ago

Can someone help me to convert the payload in the code below to a value (int or float)?


void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}
knolleary commented 1 year ago

Hi @HaViGit - this issue list isn't intended as a general support forum. Please consider using something like StackOverflow for general questions like this.

In this instance, if the payload contains just the string representation of the number you want, you can use the atoi function:

void callback(char* topic, byte* payload, unsigned int length) {
   int value;
   // Ensure the payload is a null terminated string for the atoi function to use
   payload[length] = '\0'
   value = atoi(payload)
}

If you want it as a float, you can use atof:

void callback(char* topic, byte* payload, unsigned int length) {
   double value;
   // Ensure the payload is a null terminated string for the atoi function to use
   payload[length] = '\0'
   value = atof(payload)
}
HaViGit commented 1 year ago

Sorry if I'm using this list wrong, I'll take note. But anyway thanks for your quick response and solution.