【问题标题】:Writing data to the Arduino's onboard EEPROM将数据写入 Arduino 的板载 EEPROM
【发布时间】:2021-02-06 01:10:30
【问题描述】:

我目前正在尝试编写一个函数来将数据存储到我的 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 次。我在我的代码中注释了一些感兴趣的点,但错误在哪里?

【问题讨论】:

    标签: arduino eeprom


    【解决方案1】:

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

    // 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 是硬编码的。它只能将数据写入EEPROM的开头。

    【讨论】:

    • 非常感谢,我正在构建一个简单的系统来存储一定数量的值。这是一个很好的开始 :) 再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多