2016-11-04 948 views
1

我需要一些幫助來從SD卡中提取數據我基於我的代碼this部分。使用esp8266解析SD卡數據

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

我有一個名爲一個全局變量:

char* tempStoreParam[10]; 

將存儲臨時數據要處理。存儲在文本文件中的數據是在該格式

-n.command

其中:被存儲在tempStoreParam[10] N = INT數和數據的索引位置和命令是一個char *數組存儲在tempStoreParam[10]

實施例:

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

感謝您的糾正Aniket –

回答

0

您的代碼有幾個問題 - 爲了:

讀在這種情況下返回值是一個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 /再次讀取文件之前。