RTC doesn't update the date and time

Hi everyone! I'm playing with Arduino Mega and DS1307 RTC module. The sketch I use is very simple:

#include <RTClib.h>
RTC_DS1307 rtc;

void setup() {
  Serial.begin(9600);
  rtc.begin();
  if (!rtc.isrunning()){
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
}

void loop() {
  DateTime now = rtc.now();

  String line =
     String(now.year())+"-"+
     String(now.month())+"-"+
     String(now.day())+" "+
     String(now.hour())+":"+
     String(now.minute())+":"+
     String(now.second());

    Serial.println(line);
    delay(2000);
}

I upload the sketch on the board and let it run for a while, if I disconnect the board from the pc at time (for example) 16:50:10, wait 5 minutes and then reconnect it to the pc, the time that I see on the serial monitor is not 16:55:12, but it's 16:50:12.
So I suppose that the RTC module only keeps date and time, but it doesn't continues to update them even if it has a battery to function when Arduino doesn't have supply.
Is my rtc faulty or (more probably) I'm not properly using it?

if you are powered by USB and you disconnect, then the Arduino stops.

Once you plug it back in, setup() is executed again and depending on how well the rtc.isrunning() flag is managed by your RTC (it checks the Clock Halt bit in register 0) you are at risk of overwriting the time with the compile time

can you add a Serial.println() when you do the adjust() to see if you go through this?

You have to enable the module to get it to run. Also your time set will reset to compile time and lag real time.
Both issues are why there is a sync, so the time can be set and at the synchronization time, counting begins.
Lemme rummage for similar start code.

//
 // Fire up RTC
 //
 rtc.writeProtect(false); //Gotta unlock before letting it run
 rtc.halt(false); //Let clock run
 // 

Do you have a battery installed? Is it fresh and installed with the correct polarity?

mmm writeProtect and halt are not recognized in the class RTC_DS1307 that I use

Yes I have a battery and it's correctly installed

Yah, but there is a similar function with a different name.

Okay, I've seen that they are used for ds3102 but I can't find something similar for ds1307

Great. Next thing to confirm is that the battery voltage is to use a multimeter and confirm the voltage is actually present at the VBat pin of the chip.

You will need to look at the chip documentation to identify the pin.
https://datasheets.maximintegrated.com/en/ds/DS1307.pdf

If the rtc is running under usb power, the issue is not with the clock halt bit. Disconnecting the usb will not affect that bit.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.