Writing header to data logger file in a SD card shield ??

Hi all,

I tried to write header once when the SD card (from Seeedstudio) initializes first time.

The dataset looks right, but the header does not show up in the beginning of the file.

Thanks for your guidance.

Here is my code:

#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;

void setup()
{
  Serial.begin(9600);
  while(!Serial);

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {        // see if the card is present and can be initialized:
  Serial.println("Card failed, or not present");
  return;     // don't do anything more:
  File logfile = SD.open("logger.csv", FILE_WRITE);
    if (logfile)
    {
    logfile.println(", , ,"); //Just a leading blank line, incase there was previous data
    logfile.println("DateTime,AT,RH,ST,VWC,LUX,CO2");   
    logfile.close();
    }
    else
    {
    Serial.println("Couldn't open log file");
    return;
    }  
  
  } 

void loop()
{

  //------ SD CARD ---------------------------
  delay(2000);
  File logfile = SD.open("logger.csv", FILE_WRITE);
  if(logfile)
  {
  clock.getTime();
  logfile.print(clock.month, DEC);
  logfile.print("/");
  logfile.print(clock.dayOfMonth, DEC);
  logfile.print("/");
  logfile.print(clock.year+2000, DEC);
  logfile.print("	");
  logfile.print(clock.hour, DEC);
  logfile.print(":");
  logfile.print(clock.minute, DEC);
  logfile.print(":");
  logfile.print(clock.second, DEC);
  logfile.print(", ");    
  logfile.print(at,1);
  logfile.print(", ");    
  logfile.print(rh,1);
  logfile.print(", ");    
  logfile.print(ST,1);
  logfile.print(", ");    
  logfile.print(VWC,1);  
  logfile.print(", ");    
  logfile.print(TSL2561.calculateLux(0,0,1));
  logfile.print(", ");    
  logfile.println(Vol);  
  logfile.close();
  }
  else
  {
    Serial.println("Couldn't access logfile");
  }
}

By default, when you open a file for writing, it will truncate the file and you start from the beginning.

Try changing

  File logfile = SD.open("logger.csv", FILE_WRITE);

to

  File logfile = SD.open("logger.csv", FILE_WRITE | O_APPEND);

and see if that helps.

If the file already existed then you will be inserting a new header each time the sketch started. Is that what you intended? If you wanted to only put one header into the file, it's possible to test whether the file previously existed and only write the header if it's a new file.