Error while saving data in text file I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ

#include &lt;Wire.h&gt;
#include &lt;SPI.h&gt;
#include &lt;SD.h&gt;
#include "RTClib.h"

RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
    char dateBuffer[40];
    DateTime now = rtc.now();
    sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
    return dateBuffer;
}

void saveLog()
{
  txt = SD.open("dados.txt", FILE_WRITE);
  txt.print(getCurrentTimestamp());
  txt.close();
}

void setup() {
  pinMode(53, OUTPUT);
  SD.begin(4); 
  Serial.begin(9600);
  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {
  Serial.println(getCurrentTimestamp());
  saveLog();
  delay(1000);
}


My code is very simple, do not understand where I went wrong. if I copy the following code snippet for saveData() function and save the dateBuffer variable, everything works normally.

char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());


how to save the timestamp correctly in the file through the function getCurrentTimestamp() ?
Your function, getCurrentTimestamp() saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either Serial.println() or savelog() is overwriting it.

The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in loop() and pass it to both functions.