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("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++;

    }

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

  • what do you mean by last line? ... it is unclear what is the problem ... please provide a clear description of what happens – jsotola Aug 15 at 17:57
  • I'm new here :), what about now it's clear enough? – saja wahidee Aug 16 at 13:27
  • 1
    google esp32 sd file append – jsotola Aug 16 at 16:20
  • I will work on that, thanks for your note – saja wahidee Aug 18 at 6:14
  • Really weird, I would have done the same thing you did... Did you try to switch sd card? Or at least format? May be try starting over with arduino.cc/en/Tutorial/Datalogger , which seems to append to file some string. – YCN- Aug 21 at 10:04
1

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.