-->
Page 1 of 1

RTC and wrong date on NodeMCU

PostPosted: Wed Aug 07, 2019 4:37 am
by array81
I use a NodeMCU connect with DS1307RTC module. On my device can work online and offline. If it works online use NTP to update datetime but if it works offline the user can update the datetime by html interface (webserver).

I have problem with offline mode because when I read date from RTC after a "manual update" this is wrong, the time is correct but date is wrong about 52 years.

This is an extract of my code:

Code: Select all// convert string to time_t (input as "07/08/2019 06:00")
time_t createTimeFromString(const char *str) {
  TimeElements te;
 
  te.Year = CalendarYrToTm((str[6] - '0') * 1000 + (str[7] - '0') * 100 + (str[8] - '0') * 10 + (str[9] - '0'));
  te.Month = (str[3] - '0') * 10 + (str[2] - '0');
  te.Day = (str[0] - '0') * 10 + (str[1] - '0');
  te.Hour = (str[11] - '0') * 10 + (str[12] - '0');
  te.Minute = (str[14] - '0') * 10 + (str[15] - '0');
  te.Second = 0;

  return makeTime(te);
}

// convert string to char
char* string2char(String command) {
  if (command.length() != 0) {
    char *p = const_cast<char*>(command.c_str());
    return p;
  }
}

void setup() {
  tmElements_t tm;

  if (RTC.read(tm)) {
    setSyncProvider(RTC.get);
    Log(LOG_LEVEL_VERBOSE, "Datetime from RTC: " + digits2string(day()) + "/" + digits2string(month()) + "/" + year() + " " + digits2string(hour()) + ":" + digits2string(minute()) + ":" + digits2string(second()));
  } else {
    Log(LOG_LEVEL_ERROR, "RTC not found");
  }
}


This code update manually the datetime:

Code: Select all// example NEW_date = "07/08/2019" and NEW_time = "06:00" from HTML form
RTC.set(createTimeFromString(string2char(NEW_date + " " + NEW_time)));
setSyncProvider(RTC.get);


After this if I try to print the datetime I get right time but wrong date (days, months and years are wrong of about +52 years):

Code: Select allLog(LOG_LEVEL_VERBOSE, "Datetime from RTC: " + digits2string(day()) + "/" + digits2string(month()) + "/" + year() + " " + digits2string(hour()) + ":" + digits2string(minute()) + ":" + digits2string(second()));


I have control data sent from HTML form, and result of createTimeFromString function.
RTC have a new battery.

I used these libraries:
https://github.com/PaulStoffregen/DS1307RTC
https://github.com/PaulStoffregen/Time

Some idea?

Re: RTC and wrong date on NodeMCU

PostPosted: Wed Aug 07, 2019 9:47 am
by rudy
How are you powering the DS1307RTC? It is specified as a 5 volt operating part. Maybe the date does not report properly at 3.3 volts?

I use the DS3231 for a number of reasons, one being 3 volt operation.