0

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);

  }

}
1
  • Does this bare bones version crash? Commented May 11, 2024 at 1:28

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

what does the hh part of hhx do?
hh: 1byte scanf, so 'hhx' means: read from buffer in 1-byte hexadecimal format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.