kazar4
kazar4

Reputation: 77

Parsing RGB HexCode String for a ESP 8266

I'm working on a project where my ESP8266 receives color hexCodes from the internet and then I use that color for an LED strip.

An example text that I receive is "$3#FF00FF"

However my code currently crashes whenever the B value is non-zero, so "$3#FF00FF" and "$3#FF0012" would crash it but "$3#FF0000" would not. Here is a bare bones version of my code. Also when it crashes and the ESP8266 automatic WDT does not activate either, so I am guessing it's a memory leak.

int r1 = 0;
int g1 = 0;
int b1 = 0;

void setup() {
  // boilerplate
}

void loop() {

  String data = // getting string of data from server, format is like "$3#FF0000"
  
  if (data.charAt(0) == '$' && dataLen == 9) {
    char ledStrip = data.charAt(1);
    char buffer[10];
    data.toCharArray(buffer, sizeof(buffer));

    r1 = strtol(data.substring(3, 5).c_str(), NULL, 16); // Parse hex to int
    g1 = strtol(data.substring(5, 7).c_str(), NULL, 16);

    // Note it does crash after this line but indiscriminately after
    // If I remove this line the error does not ever happening
    // So I'm assuming is a memory issue
    b1 = strtol(data.substring(7, 9).c_str(), NULL, 16);

    Serial.print("Received RGB values for Strip 1 & 2: R=");
    Serial.print(r1);
    Serial.print(", G=");
    Serial.print(g1);
    Serial.print(", B=");
    Serial.println(b1);

  }

}

Upvotes: 0

Views: 59

Answers (1)

hello_user
hello_user

Reputation: 68

In your code, please comfirm:

  1. "dataLen": undefined
  2. "buffer[10]": unused

You can using sscanf+buffer instead of string type as bellow:

    char buffer[10] = // getting data from server, format is like "$3#FF0000"
    sscanf(buffer + 3, "%2hhx%2hhx%2hhx", &r1, &g1, &b1);
    Serial.print("Received RGB values for Strip 1 & 2: R=");
    Serial.print(r1);
    Serial.print(", G=");
    Serial.print(g1);
    Serial.print(", B=");
    Serial.println(b1);

Upvotes: 1

Related Questions