(ESP32 + time.h + SD card) How to add leading a "0" to month and date and time?

now another challenge is setting the filename to the date

void getFileName() {
  File close();
  filename = date + ".txt";
  Serial.print("File name: ");
  Serial.println(filename);
}

filename is a string here above.

How to set the filename with sprintf..?

sprintf(filename1, PSTR("%d-%02d-%02d"), timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday);

here filename1 is char

%s is the format specifier I think you are looking for.

%d is the format specifier for signed decimal integers.

%s is the format specifier for a C string.

Yes.. correct..

I have replaced all the %d to %s but still I am getting the same error below.

"path" is a String.
"/" and "filename" are strings

Use sprintf or simple string manipulation functions, forget Strings.

Post code, not pictures.

1 Like

To run the appendFile command I need the path and the filename

appendFile(SD, "path", "dataMessage");

so I have written the following

  sprintf(path, PSTR("/%s"), filename );
  sprintf(filename, PSTR("%s-%02s-%02s.txt"), timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday);

But the compiler compiles and upload fine, but the terminal returns me an error.

...WiFi connected
IP address: 
192.168.1.169
Contacting Time Server
Initializing SD card...Initializing SD card...
Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.

Core  1 register dump:
PC      : 0x4008a0c5  PS      : 0x00060430  A0      : 0x8014a014  A1      : 0x3ffb2410  
A2      : 0x0000076c  A3      : 0x00000768  A4      : 0x000000ff  A5      : 0x0000ff00  
A6      : 0x00ff0000  A7      : 0xff000000  A8      : 0x00000000  A9      : 0x3ffb23e0  
A10     : 0x3ffb88d4  A11     : 0x3ffb8874  A12     : 0x00000001  A13     : 0x00000000  
A14     : 0x00000000  A15     : 0x00000000  SAR     : 0x00000004  EXCCAUSE: 0x0000001c  
EXCVADDR: 0x0000076c  LBEG    : 0x4008a0c5  LEND    : 0x4008a0d5  LCOUNT  : 0xffffffff  


Backtrace:0x4008a0c2:0x3ffb24100x4014a011:0x3ffb2420 0x40147dbd:0x3ffb2730 0x400d2bd4:0x3ffb27f0 0x400d7c21:0x3ffb2820 




ELF file SHA256: 0000000000000000

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1412
load:0x40078000,len:13416
load:0x40080400,len:3672
entry 0x400805f8

You have a string format specifier, but no string in the parameter list.

1 Like

:grimacing: missed that.

Now

  sprintf(filename, PSTR("%d-%02d-%02d.txt"), timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday);

filename above is a combination of integer + string*(.txt)*

then what should I use below..?

sprintf(path, PSTR("/%?"), filename );

If filename is a C string, simply %s

I have used %s, but ESP is unable to create the file and returns the following

Save data: xt
Appending to file: path
Failed to open file for appending

I don't understand why

xt

I'm going to write this down one more time:
I can't see your code.

1 Like

The reason for returning xt was I had set a shorter array for the path, where it couldn't fit in the file name. expanding it has solved the problem.

Now the file is getting created, but the appendFile is unable to run.
Seems I am making a mistake here

appendFile(SD, "path", "dataMessage");

here is the complete code below.

#include "FS.h"
#include "SD.h"
#include "SPI.h"
#include <time.h> 
#include <WiFi.h>

int second=0;
int date = 0;
struct tm timeinfo;
char buff[50];
char filename[40];

const char* ssid     = "SSID";
const char* password = "xxxx";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 19800;
const int   daylightOffset_sec = 0;

String dataMessage;
String date;
char path[40];

//=========================== WRITE FUNCTION ============================//
// Write to the SD card (DON'T MODIFY THIS FUNCTION)
void writeFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Writing file: %s\n", path);

  File file = fs.open(path, FILE_WRITE);
  if(!file) {
    Serial.println("Failed to open file for writing");
    return;
  }
  if(file.print(message)) {
    Serial.println("File written");
  } else {
    Serial.println("Write failed");
  }
  file.close();
}

//=========================== APPEND FUNCTION ============================//

// Append data to the SD card (DON'T MODIFY THIS FUNCTION)
void appendFile(fs::FS &fs, const char * path, const char * message) {
  Serial.printf("Appending to file: %s\n", path);

  File file = fs.open(path, FILE_APPEND);
  if(!file) {
    Serial.println("Failed to open file for appending");
    return;
  }
  if(file.print(message)) {
    Serial.println("Message appended");
  } else {
    Serial.println("Append failed");
  }
  file.close();
}

//============================= LOGGING FUNCTION ================================//
  void logSDCard() {
    dataMessage = (buff);
    Serial.print("Path: ");
    Serial.println(path);
    Serial.print("Save data: ");
    Serial.println(dataMessage);
//    appendFile(SD, path.c_str(), dataMessage.c_str());
    appendFile(SD, "path", "dataMessage");
  }


//================================ SETUP ================================//
void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(18, INPUT_PULLUP);
  pinMode(19, INPUT_PULLUP);
  pinMode(23, INPUT_PULLUP);

  
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Contacting Time Server");  


  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  

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

      // Initialize SD card
        SD.begin(5);  
        if(!SD.begin(5)) {
          Serial.println("Card Mount Failed");
          return;
        }
        uint8_t cardType = SD.cardType();
        if(cardType == CARD_NONE) {
          Serial.println("No SD card attached");
          return;
        }
        Serial.println("Initializing SD card...");
        if (!SD.begin(5)) {
          Serial.println("ERROR - SD card initialization failed!");
          return;    // init failed
        }



} //End of SETUP



//================================ LOOP ================================//
void loop() {

    if(!getLocalTime(&timeinfo)){
      Serial.println("Failed to obtain time");
      return;
    } 
  
  sprintf(buff, PSTR("%d-%02d-%02d,%02d:%02d:%02d \n"),timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec );


  if(date != timeinfo.tm_mday){

  sprintf(filename, PSTR("%d-%02d-%02d.txt"), timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday);
  sprintf(path, PSTR("/%s"), filename );

  
    date=timeinfo.tm_mday;
  }

  

  if(second != timeinfo.tm_sec){
    logSDCard();   
    second=timeinfo.tm_sec;
  }

} // End of LOOP

The return in the terminal

Appending to file: path
Failed to open file for appending
Path: /2021-06-16.txt
Save data: 2021-06-16,00:50:18

Aren't filenames 8.3?

Still got Strings?

:rofl: :rofl: why are you always so angry with String..?

I was making a mistake below. Was converting path and dataMessage to char
also the data message would be buff which has all the data to be written in it.

appendFile(SD, "path", "dataMessage");

Also I forgot to delete

String date;

I have to admit that you have superb way of pointing out faults.

Thank you once again for teaching me things.
Currently I have no String in the code. :blush:

No, I have a terrible way.

I know that I don't know all the answers - but I do know some really good questions.

1 Like

Very well said.. :heart:

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