I'm using ESP8266 to run my smart room over MQTT.
I'm struggling with converting a string to separated RGB integer values.
The string I get looks like this: #953f4f
I've already tried toInt()
, atoi()
, atol()
, casting, etc.
Here is the code:
mqtt.subscribe("light/rgb", [] (const String &payload) {
char msg[payload.length() + 1];
payload.toCharArray(msg, payload.length() + 1);
int r = msg[1];
Serial.println(r);
});
Now I need to find out how to convert ASCII to int.
Unless there's a better way to convert string to an int.
If Arduino has strtol
then you can do it like this:
mqtt.subscribe("light/rgb", [] (const String &payload) {
if (payload.length() != 7) {
Serial.printf("invalid payload: '%s'\n", payload.c_str());
return;
}
long rgb = strtol(payload.c_str() + 1, 0, 16); // parse as Hex, skipping the leading '#'
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
Serial.printf("r=%d, g=%d, b=%d\n", r, g, b);
});