2013-03-11 214 views
1

我目前正在嘗試編寫一個函數來將數據存儲到我的Arduino上的EEPROM中。到目前爲止,我只寫了一個指定的字符串,然後在程序第一次運行時再讀回它。我試圖將字符串的長度存儲爲第一個字節,我的代碼如下所示;將數據寫入Arduino的板載EEPROM

#include <EEPROM.h> 
#include <LiquidCrystal.h> 

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7); 
char string[] = "Test"; 

void setup() { 
    lcd.begin(16, 2); 
    for (int i = 1; i <= EEPROM.read(0); i++){ // Here is my error 
     lcd.write(EEPROM.read(i)); 
    } 
    delay(5000); 
    EEPROM_write(string); 
} 

void loop() { 
} 

void EEPROM_write(char data[]) 
{ 
    lcd.clear(); 
    int length = sizeof(data); // I think my problem originates here! 
    for (int i = 0; i <= length + 2; i++){ 
     if (i == 0){ 
      EEPROM.write(i, length); // Am I storing the length correctly? 
      lcd.write(length); 
     } 
     else{ 
      byte character = data[i - 1]; 
      EEPROM.write(i, character); 
      lcd.write(character); 
     } 
    } 
} 

我遇到的問題是當我讀取EEPROM的第一個字節時,我得到了應有的長度值。但是,循環只運行三次。我在我的代碼中評論了一些興趣點,但錯誤在哪裏?

回答

2

我認爲你的確是正確的,在許多方面。試試這個寫作:

// Function takes a void pointer to data, and how much to write (no other way to know) 
// Could also take a starting address, and return the size of the reach chunk, to be more generic 
void EEPROM_write(void * data, byte datasize) { 
    int addr = 0; 
    EEPROM.write(addr++, datasize); 
    for (int i=0; i<datasize; i++) { 
     EEPROM.write(addr++, data[i]); 
    } 
} 

你會這樣稱呼它:

char[] stringToWrite = "Test"; 
EEPROM_write(stringToWrite, strlen(stringToWrite)); 

要讀那麼:

int addr = 0; 
byte datasize = EEPROM.read(addr++); 
char stringToRead[0x20];   // allocate enough space for the string here! 
char * readLoc = stringToRead; 
for (int i=0;i<datasize; i++) { 
    readLoc = EEPROM.read(addr++); 
    readLoc++; 
} 

請注意,這是不使用的Arduino開發的String類:閱讀和寫作會有所不同。但上述應該適用於char數組字符串。

不過請注意,雖然EEPROM_write()看起來通用現在,它是不是真的,因爲addr是harcoded。它只能將數據寫入EEPROM的開始處。

+0

非常感謝,我正在構建一個簡單的系統,它將存儲一組數值。這是一個很好的開始:)再次,謝謝 – 2013-03-12 19:20:40