Arduino: how to once save date & time to RTC from __TIME__ and later get from RTC?

Status
Not open for further replies.

Tomasina

Member
Arduino: how to once save date & time to RTC from __TIME__ and later get from RTC?

Please help with code for Arduino. I have a module DS1307. I'm needed that after the firmware update MC will took the time and date from __ DATE__ and __ TIME__ constants and wrote them to RTC (may be need use some flag in EEPROM?), and the remaining time & date from RTC after other reboots.

In the examples that were libraries Time.h and DS1307RTC.h any excess amount parameters, I got confused.
 
Perhaps this example from the DS1307RTC library will help?

http://www.pjrc.com/teensy/td_libs_DS1307RTC.html

Code:
#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

tmElements_t tm;

void setup() {
  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}
 
Is this code takes time from __TIME__ only once after flashing?
I think he does it after every reboot, or am I wrong?
 
You can use RTC.get() to detect if the DS1307 is running, to avoid overwriting the time & date when you reboot after initially setting it up.
 
If you are using Teensy 3.0 or 3.1, which has a RTC build in (you only need to add the crystal and battery), this is done automatically by the startup code. Maybe a Teensy 3.1 would be simpler than a separate DS1307 chip?
 
Status
Not open for further replies.
Back
Top