簡體   English   中英

使用esp8266解析SD卡數據

[英]SD card data parsing with esp8266

我需要一些幫助來從 SD 卡中提取數據,我基於節中的代碼。

當我從 SD 卡讀取數據並將其顯示到串行端口時,代碼有效,但是當我將數據傳遞到 char* 數組並調用將循環數組的函數時,該數組顯示垃圾(一些不可讀的數據) . 我正在嘗試創建一個函數,我可以使用該函數調用以文本文件格式從 SD 卡存儲的不同設置。

我有一個名為的全局變量:

char* tempStoreParam[10]; 

它將存儲要處理的臨時數據。 文本文件中存儲的數據就是這種格式

-n.command

其中: n = 要存儲在tempStoreParam[10]中的數據的 int 編號和索引位置,並且 command 是要存儲在tempStoreParam[10]的 char* 數組。

示例:

-1.readTempC

-2.readTempF

-3.setdelay:10

-4.getIpAddr

這是代碼片段:

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"};

您的代碼有一些問題 - 按順序:

在此實例中 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創建的數組/在再次讀取文件之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM