如何在SD卡内存中保存多于一行

物联网 ESP32
2021-06-01 09:29:29

我正在尝试将某些文本存储在 SC 卡内存中,但 SD 卡保存了最后一行或根本不起作用我正在使用 ESP32 微控制器,这是我的代码

    #include <SPI.h>
    #include <SD.h>

    File myFile;
    int i=0;
    void setup() {
        // Open serial communications and wait for port to open:
        Serial.begin(9600);
        while (!Serial) {
             ; // wait for serial port to connect. Needed for native USB port only
        }


        Serial.print("Initializing SD card...");

        if (!SD.begin(5)) {
           Serial.println("initialization failed!");
           while (1);
       }
       Serial.println("initialization done.");

    }

   void loop() {
      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
     myFile = SD.open("test.txt", FILE_WRITE);

     // if the file opened okay, write to it:
     if (myFile) {
       Serial.print("Writing to test.txt...");
       myFile.println("testing"+i);
       // close the file:
       myFile.close();
       Serial.println("done.");
     } else {
         // if the file didn't open, print an error:
         Serial.println("error opening test.txt");
       }
     
      i++;

    }

它必须打印

{testing 0
 testing 1
 testing 2
.....
 testing n
}

其中 n={0-infinity} 但它只保存最后一行 {testing n } 最后一行

在此处输入图片说明

在此处输入图片说明

1个回答

更改FILE_WRITEFILE_APPEND

myFile = SD.open("test.txt", FILE_WRITE);成为myFile = SD.open("test.txt", FILE_APPEND);

事实上,你的loop()函数会被重复调用,每次它都会创建一个名为“test.txt”的新文件,覆盖前一个文件。