解析 ESP 8266 的 RGB HexCode 字符串

问题描述 投票:0回答:1

我正在开发一个项目,我的 ESP8266 从互联网接收颜色十六进制代码,然后我将该颜色用于 LED 灯条。

我收到的示例文本是“$3#FF00FF”

但是,当前只要 B 值非零,我的代码就会崩溃,因此“$3#FF00FF”和“$3#FF0012”会使它崩溃,但“$3#FF0000”不会。这是我的代码的简单版本。另外,当它崩溃并且 ESP8266 自动 WDT 也没有激活时,所以我猜测这是内存泄漏。

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

  }

}
c memory-leaks arduino esp8266 arduino-esp8266
1个回答
0
投票

在您的代码中,请确认:

  1. “dataLen”:未定义
  2. “缓冲区[10]”:未使用

您可以使用 sscanf+buffer 代替字符串类型,如下所示:

    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);
© www.soinside.com 2019 - 2024. All rights reserved.