Create variable text file name to be saved on SD Card

I want to create variable text file name, that creates a new text file to write data on it, after repeating the void loop for certain time. I will use a counter to calculate number of times the loop is repeated but I want to know how to create a variable file name.

Why did you start a topic in the Uncategorised category of the forum when its description is

:warning: DO NOT CREATE TOPICS IN THIS CATEGORY :warning:

Your topic has been moved to the Programming category

That is the wrong approach. Use the value of millis() or micros() to do the timing

What is the format of the filename and what will it be constructed from ?

An example:

int filenumber=100;
char filename[13]={0};  //8.3 format uses 12 bytes+zero terminator
sprintf(filename,"file%04d.dat",filenumber);  //file0100.dat
 File dataFile = SD.open (filename,FILE_WRITE);
1 Like

You could name the files something like 'data000.dat', 'data001.dat', etc. That way every time you want to create a new file you just increment the number in the filename. The number of files will be limited by the size of the SD card and the amount of data in each file.

Edit: LOL @jremington beat me to it!

1 Like

I get a filename in the YEARMODA format, every day at midnight

void getFilename()
{
  if ( getFilenameStatus == true )
  {
    getLocalTime(&timeinfo);
    sprintf( filename, "%04d%02d%02d", timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday);
    Serial.print( "filename: ");
    Serial.println( filename  );
    Serial.println();
    getFilenameStatus = false;
  }
}
...
this assumes you have a clock synced to NTP or GPS and include timelib.h or time.h

I'm new here, why shouting!!

I was not shouting

What I posted is the description of the Uncategorised topic which you ignored

1 Like
int filenumber=100;
char filename[13]={0};  //8.3 format uses 12 bytes+zero terminator
sprintf(filename,"file%04d.dat",filenumber);  //file0100.dat
 File dataFile = SD.open (filename,FILE_WRITE);

sprintf format data in the specified way
filename: array of char in that the characters of the string will be stored into
"file%04d.dat" formatting the string in this way

file: always start with fixed letters "file
%04: fill up leading zero to always have four digits
d: write in decimal (other options would be hexadecimal, or binary)
.dat: go on with fixed characters ".dat"
filenumber: variable to which the formatting %04d will be applied to

You haven't yet specified when a new filename shall be created

  • after a certain time?
  • after a certain number of times data has been written to the file?

If it is after a certain time you should learn how to write code the non-blocking way. (which is based on function millis().

best regards Stefan

ok, I did not notice that, Thanks!!

thanks, in my case I don't use RTC I may use a counter or Millis function instead of RTC.

Thanks Stefan, that's helpful, I use a delay function with 1 sec delay and usually the Arduino has memory fragmentation error after 6 hours on average which corresponds to 21600 iterations based on 1 second delay between each iteration and another so how to combine both counter and the above code to start new text file after 21600 iterations.

How did you determine that there is a memory fragmentation-error?

because I was using a buzzer to notify my if there is an error in opening file and writing data in it , this was continuously happening after certain time of writing data on SD card.

The buzzer buzzing shows that something went wrong with opening the file
but how did you conclude that the thing that is going wrong is a memory-fragmentation-error?

Why did you just start a new thread on the same topic?

Aha. So it is the file-size.
To be safe that the error does not occur you should close the file and begin to write to a new file at a filesize that is smaller than the absolut limit.
The length of one dataset (one line in the textfile) might vary on the measured data.

So my suggestion is to either start a new file after 20.000 entries
or
after 4 hours which equals to 14400 lines.
A simple counter will be sufficient.
each time you write a line to the file
increment the linecounter

myNumberOfLines++

and check if the numbers is equal or greater than 14440

if (myNumberOfLines >= 14440) {
  // close actual file
  // increment filenumber by on
  // open file and write to it

best regards Stefan

I still have a problem with intializing SD card, and I have a question about Sprintf, shall place in in void setup

#include <DHT.h>;

//////////////////////
#include <SD.h> //for the SD card module
#include <SPI.h> //for the SD card module
/////////////////


int filenumber=100;

char filename[13]={0};

//Constants
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

/////////////
int chipSelect = 4; //chipSelect pin for the SD card Reader
File mySensorData;

int d;

//////////////////////

//Variables

int dataCounter;

//////////////////////


float hum;  //Stores humidity value
float temp; //Stores temperature value

void setup()
{

Serial.begin(9600);
SD.begin(4); //Initialize the SD card reader 
pinMode(10, OUTPUT); //Must declare 10 an output and reserve it
dht.begin();
sprintf(filename,"file%04d.dat",filenumber);  //file0100.dat
File mySensorData = SD.open (filename,FILE_WRITE);
 
 if (!mySensorData)
 Serial.println("failed intialzing");

}



////////////////////////////////////////////////////////////////////////

void loop()
{
   
hum = dht.readHumidity();
temp= dht.readTemperature();


 if (mySensorData) {

dataCounter=dataCounter+1;

d= dataCounter%300; 

Serial.println(dataCounter);
mySensorData.print(hum);      
mySensorData.print("\t"); 

mySensorData.print(temp);      
mySensorData.println(""); 

 }

if (d==0)
{

mySensorData.close();

filenumber=filenumber+1;
sprintf(filename,"file%04d.dat",filenumber);  //file0100.dat
mySensorData = SD.open (filename,FILE_WRITE);



}

delay(2000);

}

first of all:

before you go on writing code. You should auto-format your code.
This is done by a two-finger key-press

press ctrl-t
then remove the too many empty lines. You are annoying the other users with such a worse formatted code

I removed spaces and reformatted it






#include <DHT.h>;
#include <SD.h>   //for the SD card module
#include <SPI.h>  //for the SD card module
int filenumber = 100;
char filename[13] = { 0 };
#define DHTPIN 2           // what pin we're connected to
#define DHTTYPE DHT22      // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);  //// Initialize DHT sensor for normal 16mhz Arduino
int chipSelect = 4;  //chipSelect pin for the SD card Reader
File mySensorData;
int dataCounter;
int d;
float hum;   //Stores humidity value
float temp;  //Stores temperature value

void setup() {

  Serial.begin(9600);
  SD.begin(4);          //Initialize the SD card reader
  pinMode(10, OUTPUT);  //Must declare 10 an output and reserve it
  dht.begin();
  sprintf(filename, "file%04d.dat", filenumber);  //file0100.dat
  File mySensorData = SD.open(filename, FILE_WRITE);
  if (!mySensorData)
  Serial.println("failed intialzing");
  
}
void loop() {
  hum = dht.readHumidity();
  temp = dht.readTemperature();

  if (mySensorData) {
    dataCounter = dataCounter + 1;
    d = dataCounter % 300;
    Serial.println(dataCounter);
    mySensorData.print(hum);
    mySensorData.print("\t");
    mySensorData.print(temp);
    mySensorData.println("");

  }
  if (d == 0) {
    mySensorData.close();
    filenumber = filenumber + 1;
    sprintf(filename, "file%04d.dat", filenumber);  //file0100.dat
    mySensorData = SD.open(filename, FILE_WRITE);
  }
  delay(2000);
}