Convert MQTT message into int values

I want to control an RGB ring light from my smartphone, I don't go into the details of how the system works but essentially I receive an MQTT message with hue, saturation and brightness values on my ESP8266.

To handle MQTT messages I use this function:

void callback(char* topic, byte* payload, unsigned int length)
{
  //Print message
  Serial.print("Message arrived: ");

  Serial.print(topic);
  Serial.print(", ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  if (strcmp(topic, "setHSV/LIGHT") == 0)
  {
      //Do something
  }
}

and when I change the color of the light from my smartphone I get a message like this on the ESP8266: setHSV/LIGHT = 0,0,59

My question is: how do I convert the 3 values I receive into 3 separate int values that I can use to control the LEDs?

Thanks for the help

Look at using strtok and atoi on the payload string.

It took me several hours last night but I managed to nearly solve my problem

void callback(char* topic, byte* payload, unsigned int length)
{
  //Print message
  Serial.print("Message arrived: ");
  Serial.print(topic);
  Serial.print(", ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }




  if (strcmp(topic, "setHSV/LIGHT") == 0)
  {
    char* str = (char* )payload; //conversion from a byte array to a character array
    str[length]= '\0'; 
    Serial.println("");
    Serial.print("Char array before: "); Serial.print(str);

    char* token = strtok(str, ",");

    while (token != NULL) {
      int n = atoi(token);
      Serial.println(n);
      token = strtok(NULL, ";");
    }

//    Serial.println("");
//    Serial.print("Char array after: "); Serial.print(str);


//    int n[10];
//    for (int a = 0; token != NULL; a++) {
//      n[a] = atoi(token);
//      Serial.println(n[a]);
//      token = strtok(NULL, ";");
//    }


  }

This is what I get in the serial console:

Message arrived: setHSV/LIGHT, 30,48,66
Char array before: 30,48,6630
48

Only the second value it's being printed and I can't figure why

Get the first one with atoi of the payload before you use strtok. Get the others with the while loop, but fix the typo where you are looking for a semi-colon rather than a comma.

I did the first conversion whit atoi outside the loop and the other two inside the loop and it worked, after fixing the typo of course.

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