View Single Post
Old 01-03-16, 03:25 PM   #22
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 218
Thanks: 2
Thanked 75 Times in 44 Posts
Default

8. DS1307.ino
#include <Time.h>
#include <DS1307RTC.h>

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

uint64_t makeTimeMilli(tmElements_t tm) {
return ((uint64_t)makeTime(tm) * 1000);
}

void writeTime(tmElements_t tmw) {

// Configure the RTC
RTC.write(tmw);
}

void readTime() {

if (RTC.read(tm)) {
//Serial.print("Ok, Time = ");
//print2digits(tm.Hour);
//Serial.write(':');
//print2digits(tm.Minute);
//Serial.write(':');
//print2digits(tm.Second);
//Serial.print(", Date (D/M/Y) = ");
//Serial.print(tm.Day);
//Serial.write('/');
//Serial.print(tm.Month);
//Serial.write('/');
//Serial.print(tmYearToCalendar(tm.Year));
//Serial.println();
}
else {
if (RTC.chipPresent()) {
Serial.println("The DS1307 is stopped. Please run the SetTime");
Serial.println("example to initialize the time and begin running.");
Serial.println();
// get the date and time the compiler was run
if (getDate(__DATE__) && getTime(__TIME__)) {
// and configure the RTC with this info
RTC.write(tm);
}
}
else {
Serial.println("DS1307 read error! Please check the circuitry.");
Serial.println();
}
}
}


void print2digits(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
}

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;
}
Acuario is offline   Reply With Quote