automatically saving file in SD card?

Hello, friend,

Really really…I’m sorry.
I’d like to know how to save files automatically in SD card with ‘if’ grammer or any other method.
So difficult to solve this problem because I’m a beginner.
Until now, I have to unplug the usb cable which connects arduino to computer, in order to save files and create new file.
My arduino system consists of Mega + RTC + SD reader.

I’d like to make this saving pattern to ‘1 csv file per 1 day’
automatically every day.

Please, let me know how to modify the below origin source code.
Thank you in advance.

------------------------------------------------- see below
RTC_DS1307 RTC;
const int chipSelect = 53;

File dataFile;

void setup()
{

Serial.begin(9600);
Serial.print(“Initializing SD card…”);

Wire.begin();
RTC.begin();
RTC.adjust(DateTime(“Aug 16 2015”,“09:53:00”));

pinMode(SS, OUTPUT);

// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println(“Card failed, or not present”);
while (1) ;
}
Serial.println(“card initialized.”);

// open a new file if it doesn’t exist and leave the loop:
char filename = “DATA_000.CSV”;
for (uint8_t i = 0; i < 1000; i++) {
filename[5] = i/100 + ‘0’;
filename[6] = (i%100)/10 + ‘0’;
filename[7] = i%10 + ‘0’;
if (! SD.exists(filename)) {
dataFile = SD.open(filename, FILE_WRITE);
break;
}
}

if (! dataFile) {
Serial.println(“could not create file”);
}
Serial.print("Logging to: ");
Serial.println(filename);

}

int i = 0;
void loop()
{
DateTime now = RTC.now();

// Sending date & time to UART every second
Serial.print(now.year(), DEC);
Serial.print(’/’);
Serial.print(now.month(), DEC);
Serial.print(’/’);
Serial.print(now.day(), DEC);
Serial.print(’ ‘);
Serial.print(now.hour(), DEC);
Serial.print(’:’);
Serial.print(now.minute(), DEC);
Serial.print(’:’);
Serial.print(now.second(), DEC);
Serial.print(" ");

String dataString = “”;

for (int analogPin = 0; analogPin < 3; analogPin++) {
int sensor = analogRead(analogPin);

dataString += String(sensor);
if (analogPin < 2) {
dataString += “,”;
}
}
Serial.println(dataString);

dataFile.print(now.year(), DEC);
dataFile.print(’/’);
dataFile.print(now.month(), DEC);
dataFile.print(’/’);
dataFile.print(now.day(), DEC);
dataFile.print(’ ‘);
dataFile.print(now.hour(), DEC);
dataFile.print(’:’);
dataFile.print(now.minute(), DEC);
dataFile.print(’:’);
dataFile.print(now.second(), DEC);
dataFile.print(",");

dataFile.println(dataString);

i++;
if (i>0){ //Call every times
dataFile.flush();
i = 0;
}

delay(1000);

}

Until now, I have to unplug the usb cable which connects arduino to computer, in order to save files and create new file.

That’s because you define the file name only in setup.

On every pass through loop(), see if it is time to close the open file and open a new one.

Quit pissing away resources on Strings. Write the data to the file as you collect it.

Thank you so much.. I'm now retrying it according to your advice.