Category: ARDUINO
Hits: 12854

Hi, It has been so long I am not talking about arduino. I have a project with arduino and I will expose it yet. But, one part of the project (programmes) is to have a log file in SD card named by date. Something like YYYYMMDD.CSV file.

Basically, I used RTClib.h library because date/time syncronisiation is very simple. To create file name based on date, we need to put every digit in file name charactor from integer values. So, we need to know about % (modulo) and / (divider) algorithm. Some of us maybe not very familiar with modulo. You can read about module in here.

And also, we must understand SD.h is only allow 12 characters, something like 8 characters for file name, . , and 3 characters for the extention file name. (YYYYMMDD.CVS) Total 12. More than that is not acceptable.

 

 

I found a site how to create file name based on date, but the idea is not complete. Below, you can see and study how I make it clearl and complete for each character in file name.

 

 

#include <SD.h>

#include "RTClib.h"

#include <Wire.h>

#include <string.h>


RTC_DS1307 RTC;

char filename[] = "00000000.CSV";

File myFile;


void setup()

{

Serial.begin(9600);

Wire.begin(); //Important for RTClib.h

RTC.begin();

if (! RTC.isrunning()) {

Serial.println("RTC is NOT running!");

// following line sets the RTC to the date & time this sketch was compiled

// RTC.adjust(DateTime(__DATE__, __TIME__));

return;

}

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

// On the Ethernet Shield, CS is pin 4. It's set as an output by default.

// Note that even if it's not used as the CS pin, the hardware SS pin

// (10 on most Arduino boards, 53 on the Mega) must be left as an output

// or the SD library functions will not work.

pinMode(10, OUTPUT);


if (!SD.begin(4)) {

Serial.println("initialization failed!");

return;

}

Serial.println("initialization done.");


}


void loop()

{

getFileName();

createFileName();

delay(3000);

}


void getFileName(){

DateTime now = RTC.now();

filename[0] = (now.year()/1000)%10 + '0'; //To get 1st digit from year()

filename[1] = (now.year()/100)%10 + '0'; //To get 2nd digit from year()

filename[2] = (now.year()/10)%10 + '0'; //To get 3rd digit from year()

filename[3] = now.year()%10 + '0'; //To get 4th digit from year()

filename[4] = now.month()/10 + '0'; //To get 1st digit from month()

filename[5] = now.month()%10 + '0'; //To get 2nd digit from month()

filename[6] = now.day()/10 + '0'; //To get 1st digit from day()

filename[7] = now.day()%10 + '0'; //To get 2nd digit from day()

Serial.println(filename);

}


void createFileName(){

//Check file name exist?

if (SD.exists(filename)) {

Serial.println("exists.");

}

else {

Serial.println("doesn't exist.");

Serial.println("Creating new file");

Serial.println(filename);

myFile = SD.open(filename, FILE_WRITE);

myFile.close();

}

}