3

I am trying to store certain text in SC Card memory, but the SD Card save the last line or it does not work at all I'm working with ESP32 microcontroller this is my code

    #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(&quot;Initializing SD card...&quot;);

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

}

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(&quot;Writing to test.txt...&quot;);
   myFile.println(&quot;testing&quot;+i);
   // close the file:
   myFile.close();
   Serial.println(&quot;done.&quot;);
 } else {
     // if the file didn't open, print an error:
     Serial.println(&quot;error opening test.txt&quot;);
   }

  i++;

}

it must print

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

where n={0-infinity} but it just saves the last line which {testing n } the last line

enter image description here

enter image description here

Bence Kaulics
  • 7,783
  • 8
  • 41
  • 90

1 Answers1

2

Change FILE_WRITE to FILE_APPEND.

I.e myFile = SD.open("test.txt", FILE_WRITE); becomes myFile = SD.open("test.txt", FILE_APPEND);.

As it is, your loop() function is called repeatedly, and each time it creates a new file called "test.txt", overwriting the previous one.