MQTT data- I can serial print, but can't then use data!

Hello everyone, I'm new to programming and learning a bit by trial and error / cut and paste but I'm stuck with an issue I can't solve.

I'm sending data to an esp8266 via mqtt (from a pi using node red). at this stage it's a fixed number (23) I can serial print the number but I need to use a line similar to:
temp = ((char)payload[i]);
temp will be used later in the program as data from a sensor and logged / graphed.
if I serial print ''temp'' I just get a strange number in this case it is ''51'' not the ''23'' Im expecting??
extract of code below:
Help me on this hot afternoon...

float temp;

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]);
   temp = ((char)payload[i]);     
  
  }
 Serial.print("temp=");
 Serial.print (temp);

51 is the ASCII code for'3'. You will need to convert the text of the payload to a number. You can use atoi or atof for this purpose but you will likely need to copy the payload into a buffer first so you can zero terminate it.

Thanks wildbill, but what you just said goes straight over my head....any chance of some example code I can work with?

float temp;
char buffer[16];

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]);  
   }
 memcpy(buffer, payload,length);
 buffer[length]=0;
temp=atof(buffer);
 Serial.print("temp=");
 Serial.print (temp);

Not compiled, not tested.
Note too that there is no check that the payload is small enough to fit in the buffer.

Wildbill, I'll give it a whirl right now and let you know...thanks so much...it's people like you that help people like me out and stops me from giving up...Thanks

Wildbill- perfect, worked like a charm....i can't thank you enough.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.