I use a board with memory and a battery charger (DS3231). I have tested several modules with LIR2032 battery and CR2032 battery (after removing the diode and the resistance of the charger).
#include <RTClib.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x3f, 20, 4);
RTC_DS3231 rtc;
unsigned long timeForAction = millis();
int initialDay;
int utcOffset;
void setup() {
Serial.begin(9600);
Serial.flush();
Wire.begin();
rtc.begin();
lcd.init();
lcd.backlight();
lcd.clear();
// initClock();
DateTime nowTime = rtc.now();
initialDay = nowTime.day();
utcOffset = calcUtcOffset(nowTime);
showDate(nowTime);
}
void loop() {
int secondsInterval = 1;
if (millis() > timeForAction) {
timeForAction = millis() + (secondsInterval * 1000);
DateTime nowTime = rtc.now();
if (initialDay != nowTime.day()) {
initialDay = nowTime.day();
showDate(nowTime);
}
showHour(nowTime);
}
}
The power supply for the module, display and Arduino NANO is external with an additional 5V regulator.
Additional file:
String dayOfWeekName(int d) {
switch (d) {
case 0: return "DOMINGO";
case 1: return "LUNES";
case 2: return "MARTES";
case 3: return "MIERCOLES";
case 4: return "JUEVES";
case 5: return "VIERNES";
case 6: return "SABADO";
}
}
void initClock() {
int initDay = 17;
int initMonth = 9;
int initYear = 2019;
int initHour = 18;
int initMinute = 17;
rtc.adjust(DateTime(initYear, initMonth, initDay, initHour, initMinute, 0));
}
int calcUtcOffset(DateTime t) {
int offset;
if (t.month() >= 4 && t.month() <= 10) {
return 2;
} else {
return 1;
}
}
void showDate(DateTime t) {
char buf_date[11];
snprintf(buf_date, sizeof(buf_date), "%02d/%02d/%4d ",
t.day(), t.month(), t.year());
lcd.setCursor(0, 0);
lcd.print(buf_date);
lcd.setCursor(11, 0);
lcd.print(dayOfWeekName(t.dayOfTheWeek()).c_str());
}
int calcUtcHour(int h) {
if (h < utcOffset) {
return h - utcOffset + 24;
} else {
return h - utcOffset;
}
}
void showHour(DateTime t) {
int utcHour = calcUtcHour(t.hour());
char buf_hour_local[9];
snprintf(buf_hour_local, sizeof(buf_hour_local), "%02d:%02d:%02d",
t.hour(), t.minute(), t.second());
char buf_hour_utc[6];
snprintf(buf_hour_utc, sizeof(buf_hour_utc), "%02d:%02d",
utcHour, t.minute());
lcd.setCursor(0, 1);
lcd.print(buf_hour_local);
lcd.print(" ");
lcd.print(buf_hour_utc);
lcd.print(" (UTC)");
}
If I disconnect the external power, when I connect the RTC again it recovers the compilation time. In this situation, the voltage measured on pin 14 (Vbat) is always greater than 3V.
The library I use is RTClib.h.
I have reviewed the queries in several forums and although similar problems are described I have not found a way to solve them.
I would appreciate any help because I've been stuck for a while.