RTC and battery issue

Hi,

If habe a little clock-project. Everything is working but I have the following issue:

When I detach the USB cable from my arduino MEGA board, and I remove the battery from the RTC module, The RTC module forget the time, that's normal, But haw can I check IF the RTC module has a time set?

When I look into my serial monitor (after removing all power supply - USB and battery) there is nothing..

This is my code in the LOOP:

if (RTC.read(tm)) {
Serial.print("Ok, Time = ");
print2digits(tm.Hour);
Serial.write(':');
print2digits(tm.Minute);
Serial.write(':');
print2digits(tm.Second);
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();
} else {
Serial.println("DS1307 read error! Please check the circuitry.");
Serial.println();
}

delay(9000);
}

If I understand your question correctly, then from the 1307 datasheet:

Bit 7 of Register 0 is the clock halt (CH) bit. When this bit is set to 1, the oscillator is disabled. When cleared to 0, the oscillator is enabled. On first application of power to the device the time and date registers are typically reset to 01/01/00 01 00:00:00 (MM/DD/YY DOW HH:MM:SS). The CH bit in the seconds register will be set to a 1.

So just check to see if the CH bit is 1 or 0? If you are using a library it is often a function called IsRunning(), or similar.

I just found this:

setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus()!= timeSet) {
Serial.println("Unable to sync with the RTC");
tm.Hour = 0;
tm.Minute= 0;
tm.Second = 0;
RTC.write(tm);
}

it seems to work as well, but is this the good way? I added this in the VOID SETUP

Different RTC library but similar idea (though I check the year) to what I use for testing my code until I have clock setting hardware in place.

 RTC.readClock();
  if(RTC.getYear() == 0){
    //Serial.println(F("Set Clock"));
    RTC.setHours(10);
    RTC.setMinutes(40);
    RTC.setSeconds(0);
    RTC.setDate(1);
    RTC.setMonth(7);
    RTC.setYear(14);
    RTC.setDayOfWeek(2);
    RTC.setClock();
    RTC.getFormatted2k(formatted);
  }

If you read the contents of the clock as raw bytes, there is a pair of bytes that determine that the "time is set". If I recall correctly, these have to be set to 0xaa and 0x55 to get the 1307 to run. If they are not set then the clock will not be running. I think these two bytes (again relying on memory) are located at address 54 and 55.

It may be worth checking these bytes to see if they still hold 0xaa55. Unfortunately I don't have the necessary hardware around to test. Something like the following could be worth trying as a test.

unsigned int value;
RTC.getRAM(54, (uint8_t* ) &value,(uint8_t) sizeof(int));
Serial.println(value,HEX);