system
March 29, 2012, 8:25pm
1
Each time the program runs, I'd like a new file to be created on the SD card with the Month, Day, Year, and then two additional numbers, so "MMDDYY00.txt" for example. However, the time library returns integers and the file name needs to be an array of characters. How can I put the time integers into a single character array?
In case I'm not clear:
month = 03
day = 29
year = 12
file name = 03291200.txt
system
March 29, 2012, 9:17pm
2
However, the time library returns integers
Which are easily converted to strings in a number of ways. sprintf() is probably the easiest.
Here is an example for SdFat.
bool openByDate(SdFile* file, uint8_t y, uint8_t m, uint8_t d);
creates a new file with a name of the form "YYMMDDNN.TXT". NN is 0-99 and makes the name unique for a given date.
#include <SdFat.h>
SdFat sd;
SdFile file;
uint8_t const chipSelect = 10;
void fmt2d(char* str, uint8_t v) {
if (v > 99) return;
uint8_t n1 = v / 10;
uint8_t n0 = v - 10 * n1;
*str++ = '0' + n1;
*str = '0' + n0;
}
bool openByDate(SdFile* file, uint8_t y, uint8_t m, uint8_t d) {
char name[] = "YYMMDD00.TXT";
fmt2d(name, y);
fmt2d(name + 2, m);
fmt2d(name + 4, d);
for (uint8_t n = 0; n < 100; n++) {
fmt2d(name + 6, n);
if (file->open(name, O_CREAT | O_EXCL |O_WRITE)) return true;
}
return false;
}
void setup() {
Serial.begin(9600);
Serial.println("type any character");
while (Serial.available() == 0) {}
if (!sd.begin(chipSelect)) {
Serial.println("sd.begin failed");
}
if (openByDate(&file, 12, 3, 30)) {
Serial.print("opened: ");
file.printName();
Serial.println();
} else {
Serial.println("open failed");
}
}
void loop() {}
Here is a list of files created today 2012-03-30:
12033000.TXT
12033001.TXT
12033002.TXT
12033003.TXT
12033004.TXT
12033005.TXT
12033006.TXT
12033007.TXT
12033008.TXT
12033009.TXT
godo
September 9, 2015, 2:27pm
4
Hello fat16lib,
thanks for the code, that is exactly what I need.
Unfortunately, it does not compile. I get:
SdFile was not declared in this scope
which refers to that portion:
bool openByDate(SdFile* file, uint8_t y, uint8_t m, uint8_t d) {
char name[] = "YYMMDD00.TXT";
fmt2d(name, y);
fmt2d(name + 2, m);
fmt2d(name + 4, d);
for (uint8_t n = 0; n < 100; n++) {
fmt2d(name + 6, n);
if (file->open(name, O_CREAT | O_EXCL |O_WRITE)) return true;
}
return false;
}
What is missing? I use the IDE 1.6.4., and the SdFat lib works in general.
Thank for any hint.