Issue with writing data on SD card after disconnecting the Arduino


I am using a DS3231, and an SD card to record the time. I want to record time on SD card while connecting and disconnecting power. But, each time after reconnecting the power all previous recorded data is erased and new data is recorded on SD card.

Can anyone please tell me how to solve the problem to be able to save the previously recorded data and continuing writting data at end of the file?

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);

///SD Card*******
#include <SPI.h>
#include <SD.h>

File myFile;

// change this to match your SD shield or module;
const int chipSelect = 10;

void setup()
// Setup Serial connection
// Uncomment the next line if you are using an Arduino Leonardo
//while (!Serial) {}

// Initialize the rtc object

// The following lines can be uncommented to set the date and time
//rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
//rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
//rtc.setDate(21, 7, 2021); // Set the date to January 1st, 2014

while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only

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

if (!SD.begin()) {
Serial.println("initialization failed!");
Serial.println("initialization done.");

// 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 ="test.txt", FILE_WRITE);

void loop()
// Send Day-of-Week
Serial.print(" ");

// Send date
Serial.print(" -- ");

// Send time

//SD Card *****************************************************************************
myFile ="test.txt", FILE_WRITE);
//Clock *********************
// Send Day-of-Week
myFile.print(" ");

// Send date
myFile.print(" -- ");

// Send time


// Wait one second before repeating :)
delay (1000);


Try opening the file for read / write, opening it for write as you have found creates a new file.

Note that if the power goes with the file open you are screwdriver.

And that is the size of it! :sunglasses:

Auto correct eh!

For screwdriver read screwed

I think the problem is the directory entry for the file has not been updated with the actual number of records in the file. So when the file is opened, only the original value, zero, is used. A flush or close will update the directory entry.