2

我目前正在尝试编写一个函数来将数据存储到我的 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 的第一个字节时,我得到了假定的长度值。但是,循环只运行了 3 次。我已经评论了我的代码中的一些兴趣点,但错误在哪里?

4

1 回答 1

3

我认为,在很多方面,你确实是正确的。试试这个写:

// 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++;
}

请注意,这不是使用String为 Arduino 开发的类:读写会有所不同。但上面应该适用于char数组字符串。

Note however, that while EEPROM_write() looks generic now, it isn't really, since addr is harcoded. It can only write data to the beginning of EEPROM.

于 2013-03-11T23:44:17.913 回答