【问题标题】:SD card data parsing with esp8266用 esp8266 解析 SD 卡数据
【发布时间】:2016-11-04 04:01:21
【问题描述】:

我需要一些帮助来从 SD 卡中提取数据,我的代码来自 this 部分。

当我从 SD 卡读取数据并将其显示到串行端口时,代码可以工作,但是当我将数据传递到 char* 数组并调用将循环数组的函数时,数组显示垃圾(一些不可读的数据)。我正在尝试制作一个函数,可以用来调用以文本文件格式从 SD 卡存储的不同设置。

我有一个全局变量,名为:

char* tempStoreParam[10]; 

这将存储要处理的临时数据。文本文件中存储的数据就是这种格式

-n.command

其中:n = 要存储在tempStoreParam[10] 中的数据的int 编号和索引位置,命令是要存储在tempStoreParam[10] 中的char* 数组。

例子:

-1.readTempC

-2.readTempF

-3.setdelay:10

-4.getIpAddr

这里是sn-p的代码:

while (sdFiles.available()) {
  char sdData[datalen + 1];
  byte byteSize = sdFiles.read(sdData, datalen);
  sdData[byteSize] = 0;
  char* mList = strtok(sdData, "-");
  while (mList != 0)
  {
    // Split the command in 2 values
    char* lsParam = strchr(mList, '.');
    if (lsParam != 0)
    {
      *lsParam = 0;
      int index = atoi(mList);
      ++lsParam;
      tempStoreParam[index] = lsParam;
      Serial.println(index);
      Serial.println(tempStoreParam[index]);
    }
    mList = strtok(0, "-");
  }
} 

我正在尝试得到以下结果:

char* tempStoreParam[10] = {"readTempC","readTempF","setdelay:10","getIpAddr"};

【问题讨论】:

    标签: c++ c arduino arduino-esp8266


    【解决方案1】:

    您的代码有一些问题 - 按顺序:

    在这种情况下,read 的返回值是一个 32 位整数 - 您将其截断为一个字节值,这意味着如果文件内容超过 255 个字节,您将错误地终止您的字符串,并且无法读取内容正确:

    byte byteSize = sdFiles.read(sdData, datalen);
    

    其次,您将堆栈变量的地址存储到 tempStoreParam 数组中:

    tempStoreParam[index] = lsParam;
    

    现在,这将起作用,但仅限于 sdData 在范围内保留多长时间。之后,sdData 就不再有效使用,很可能导致你遇到垃圾。您最有可能尝试做的是将数据复制到tempStoreParam。为此,您应该使用以下内容:

    // The amount of memory we need is the length of the string, plus one 
    // for the null byte
    int length = strlen(lsParam)+1
    
    // Allocate storage space for the length of lsParam in tempStoreParam
    tempStoreParam[index] = new char[length];
    
    // Make sure the allocation succeeded 
    if (tempStoreParam[index] != nullptr) {
       // Copy the string into our new container
       strncpy(tempStoreParam[index], lsParam, length);
    }
    

    此时,您应该能够成功地在函数外部传递该字符串。请注意,您需要delete 完成后创建的数组 / 在再次读取文件之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多