0

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 <Wire.h>
#include <SPI.h>
#include <SD.h>
#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() ?

2

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.

-1

As far as I know you should use

text.write(getCurrentTime());

That because (if I'm not wrong) you need to send it as ASCII characters so the text editor will be able to read them in the right way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.