Title data while saving on SD card

Hi, I'm working on my sensor, and I'm trying to save data to the sd card. I need the header/title data only in the first row of the stored data, how can I write the code, and where should it be placed? because if it is placed in a loop then it will appear continuously.

this is the code I made to read my sensor.

#include <SD.h>
#include <SPI.h>
#include <DS3231.h>
#define MQ2pin (A0)

float sensorValue;  //variable to store sensor value


File myFile;
DS3231  rtc(SDA, SCL);

int pinCS = 10; // Pin 10 on Arduino Uno

void setup() {
    
  Serial.begin(9600);
  pinMode(pinCS, OUTPUT);
  
  // SD Card Initialization
  if (SD.begin())
  {
    Serial.println("Gas sensor warming up!");
    delay(2000); // allow the MQ-6 to warm up
    Serial.println("SD card is ready to use.");
    Serial.println("Time, sensor Value");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  
  }
  rtc.begin();    
}
void loop() {
  sensorValue = analogRead(MQ2pin); // read analog input pin 0
  Serial.print(rtc.getDateStr()); //prosedur pembacaan tanggal
  Serial.print(",");
  Serial.print(rtc.getTimeStr()); //prosedur pembacaan waktu
  Serial.print(",");
  Serial.print(sensorValue);
  Serial.println(" ");

myFile = SD.open("File1.txt", FILE_WRITE);
  if (myFile) {  
    myFile.print(rtc.getDateStr());
    myFile.print(",");
    myFile.print(rtc.getTimeStr());
    myFile.print(",");
    myFile.print(sensorValue);  
    myFile.println(" ");
    
    
    myFile.close(); // close the file
  }
  // if the file didn't open, print an error:
  else {
    Serial.println("error opening test.txt");
  }

and this is the output


result that i want
image

write the header in setup().

Better yet use a text editor make your text file headers, save it to the SD card, and use file.append() to add to the data text.

Check if file exists, if not, create and add header line, else open in append mode, like @Idahowalker suggested.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.