Unable to synch time from RTC

Hello Guys

here is my code for setting alarams

#include <Time.h>
#include <TimeAlarms.h>
#include <Wire.h> //added jim ************************
#include <DS1307RTC.h> //added jim ***************************

void setup()
{
  Serial.begin(9600);
  Serial.println("In setup...."); //added jim *****************
  /*
  using rtc, sync system time to rtc
   setTime(8,29,0,1,1,11); // set time to Saturday 8:29:00am Jan 1 2011 //old way *****************
   */

  // following lines added to set time from rtc, took from timeRtcSet example, added jim *****************
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if (timeStatus() != timeSet) 
    Serial.println("Unable to sync with the RTC");
  else
    Serial.println("RTC has set the system time");
  // end of setting the time ******************************



  // create the alarms 
   Alarm.alarmRepeat(11, 30, 30,led13OFF);
  Alarm.alarmRepeat(11, 30, 00,led13ON);
 
  //Alarm.alarmRepeat(11,16,0, MorningAlarm); 
 /* 
  Alarm.alarmRepeat(10, 35,45, MorningAlarm);  
  Alarm.alarmRepeat(10,36,0, MorningAlarm); 
 
  Alarm.alarmRepeat(10, 36,30, MorningAlarm);
  
  Alarm.alarmRepeat(10,37,0, MorningAlarm);  
  
  Alarm.alarmRepeat(10, 15,30, MorningAlarm);
  Alarm.alarmRepeat(10,16,0, MorningAlarm);  
  Alarm.alarmRepeat(10,16,30, MorningAlarm);  
  Alarm.alarmRepeat(10,17,0, MorningAlarm);  
  Alarm.alarmRepeat(10, 17,30, MorningAlarm);
  Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day 
  Alarm.alarmRepeat(dowSaturday,8,30,30,WeeklyAlarm);  // 8:30:30 every Saturday 
  */


  //Alarm.timerRepeat(15, Repeats);            // timer for every 15 seconds    
  //Alarm.timerOnce(10, OnceOnly);             // called once after 10 seconds 


  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Serial.print("Turning pin 13 LED off at ");
  digitalClockDisplay();
  Serial.println("Ending setup...."); //added jim *****************
}

void  loop(){  
  digitalClockDisplay();
  Alarm.delay(1000);
}

// functions to be called when an alarm triggers:

void led13ON(){
 //Serial.print("Turning pin 13 LED on at ");
 //digitalClockDisplay();
 digitalWrite(13, HIGH);   
 }
 
 void led13OFF(){
 //Serial.print("Turning pin 13 LED off at ");
 //digitalClockDisplay();
 digitalWrite(13, LOW);   
 }
 

void MorningAlarm(){
  digitalClockDisplay();
  Serial.println("Alarm: - turn lights off Jimbo");    
}

void EveningAlarm(){
  Serial.println("Alarm: - turn lights on");           
}

void WeeklyAlarm(){
  Serial.println("Alarm: - its Monday Morning");      
}

void ExplicitAlarm(){
  Serial.println("Alarm: - this triggers only at the given date and time");       
}

void Repeats(){
  Serial.println("15 second timer");         
}

void OnceOnly(){
  Serial.println("This timer only triggers once");  
}

void digitalClockDisplay()
{
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(); 
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

This is my code for setting time from ds1307 lib

#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.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;
}

at first i am able to sync time from RTC but after the power goes down my time get reset to 00


image sharing

Check the voltage on the DS1307's backup battery. If the battery has gone dead the DS1307 will not be able to keep the time without power.

johnwasser:
Check the voltage on the DS1307's backup battery. If the battery has gone dead the DS1307 will not be able to keep the time without power.

i just checked it by changing battery

Updated:Now incrementer in clock even stopped working ? my time is not even incrementing

You will have to run the settime sketch again to reset the clock halt bit in the RTC.

cattledog:
You will have to run the settime sketch again to reset the clock halt bit in the RTC.

i did at first it synch the time but after power goes down timer starts counting from 0

but after power goes down timer starts counting from 0

Even after you used the new battery?

It appears that your module is not running under battery power.

You will then need to confirm that approximately 3 v is getting to the Vbat lead of the chip.

If the voltage is present but the rtc is not running, then you may have a defective chip or oscillator on the module. See this thread for a case of a counterfeit ds1307 chip which would not run under batter power DS1307 Real Time Clock CH bit problem - Project Guidance - Arduino Forum

cattledog:
Even after you used the new battery?

It appears that your module is not running under battery power.

You will then need to confirm that approximately 3 v is getting to the Vbat lead of the chip.

If the voltage is present but the rtc is not running, then you may have a defective chip or oscillator on the module. See this thread for a case of a counterfeit ds1307 chip which would not run under batter power DS1307 Real Time Clock CH bit problem - Project Guidance - Arduino Forum

Ok my old battery is running fine its incrementing the timer but in my new battery its not incrementing the timer. some time my arduino is able to synch the power in my old battery but most of time its not

Here it is after synching at first time after set time

upload img

But after power failure it doesent synch most of time

When the rtc fails to resync, can you run the following sketch and see what is in the leftmost bit of register 0x00. Did you confirm correct batter power to the chip when the external power is disconnected? It still looks like the module is not running under battery power.

// DS1307 I2C Read and Write Timekeeper Registers 0x00-0X07

#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68
#define startRegister 0x00
#define endRegister 0x07
//data storage registers 0X08-0X3F



void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.print("Register");
  Serial.print("\t");
  Serial.println("Bit Values");
  Serial.println();

 // writeNVRAM(0x00, B00000000);//enable oscillator and set seconds to 0
 //writeNVRAM(0x00, B10000000);//disable oscillator set CH bit

  for (int a = startRegister; a <= endRegister; a++)
  {
    byte b = readNVRAM(a);
    Serial.print("0X");
    if (a < 16)
      Serial.print("0");
    Serial.print(a, HEX);
    Serial.print("\t");
    Serial.print("\t");


    for (int i = 7; i >= 0; i-- )
    {
      Serial.print((b >> i) & 0X01);//shift and select first bit, no speed advantage
    }
    Serial.println();
  }
}

void writeNVRAM(byte location, byte data)
// writes data to DS1307 NVRAM location
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.write(location);
  Wire.write(data);
  Wire.endTransmission();
}

byte readNVRAM(byte location)//// reads data from DS1307 NVRAM location
{
  Wire.beginTransmission(DS1307_I2C_ADDRESS);
  Wire.write(location);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_I2C_ADDRESS, 1);
  Wire.read();
}

void loop() {
}


online photo storage

This is what i got after putting your code after getting unable to synch

How can i confirm that battery power ?

The module is not running under battery power, and the clock halt bit is being set to 1. If the battery itself if OK, then you have some trouble shooting to do to determine why the voltage is not getting to the Vbat pin of the chip. It may relate to the connections to the battery holder or traces on the module. If the voltage is indeed getting to the pin, then its likely to be a defective chip or oscillator.
Here's the data sheet for the chip to help you find the Vbat pin on the chip.
http://datasheets.maximintegrated.com/en/ds/DS1307.pdf

most of the ds1307 RTC modules for sale out there on ebay have issues with their circuit design.
They can be easily fixed by removing some components from the board.
The two biggest problems are using a resistor on the crystal and an improper battery circuit that is a hack attempt to make it work with a rechargeable battery. Both of these bad designs should be removed for reliable operation.

I have attached a zip file with more information about the issues.

--- bill

I2CRTC-ds1307.zip (112 KB)

is coin cell battery recharge automaticallly ? dunno but my module is working perfect now

saifkazi:
is coin cell battery recharge automaticallly ? dunno but my module is working perfect now

I'd recommend figuring out what happened or why it is suddenly working.
Things just don't magically start working.
And just as suddenly as it starting working, it could fail again.

I'd go look carefully at the board to see if it is one of the many boards that has h/w issues that need to be corrected.
Many of the units out there include a poorly designed charging circuit for use on a rechargeable battery but the battery shipped is not a rechargeable battery.
This charging circuity can create battery backup issues for the DS1307 even when used with a rechargeable battery.
But when used with a non rechargeable battery, it has the potential to damage the battery over time.

It won't take long to look at the PCB and figure out if it needs some surgery.

--- bill

bperrybap:
I'd recommend figuring out what happened or why it is suddenly working.
Things just don't magically start working.
And just as suddenly as it starting working, it could fail again.

I'd go look carefully at the board to see if it is one of the many boards that has h/w issues that need to be corrected.
Many of the units out there include a poorly designed charging circuit for use on a rechargeable battery but the battery shipped is not a rechargeable battery.
This charging circuity can create battery backup issues for the DS1307 even when used with a rechargeable battery.
But when used with a non rechargeable battery, it has the potential to damage the battery over time.

It won't take long to look at the PCB and figure out if it needs some surgery.

--- bill

actually the one i am using is home made RTC module

saifkazi:
actually the one i am using is home made RTC module

Ah... ok.
hm....

The DS1307 does not attempt to charge the battery.
If it is suddenly "working" then something must have changed. Perhaps some kind of intermittent/loose connection?

There are two ways the time can fail to initialize in the Time library when using a synchronization routine; both are from the RTC synchronization routine returning a "failed" gettime status.

This happens from either:

  • The RTC is halted.
  • there was a i2c error when trying to talk to the RTC chip

We did see earlier that the RTC was halted, which happens when the power fails and battery backup is not working properly and power is reapplied, but perhaps there is also a i2c communications issue as well.

Are you using "Typical operating circuit" from the datasheet including the required i2c pullups on your I2C signal lines?

bperrybap:
Ah... ok.
hm....

The DS1307 does not attempt to charge the battery.
If it is suddenly "working" then something must have changed. Perhaps some kind of intermittent/loose connection?

There are two ways the time can fail to initialize in the Time library when using a synchronization routine; both are from the RTC synchronization routine returning a "failed" gettime status.

This happens from either:

  • The RTC is halted.
  • there was a i2c error when trying to talk to the RTC chip

We did see earlier that the RTC was halted, which happens when the power fails and battery backup is not working properly and power is reapplied, but perhaps there is also a i2c communications issue as well.

Are you using "Typical operating circuit" from the datasheet including the required i2c pullups on your I2C signal lines?

the timer is working when the battery is removed.ok the timer freezes when i put the good battery

Here is my serial monitor when i put new battery.it freezes when i put new battery


upload gambar

Here is my serial monitor when i put old battery.

img host

That output doesn't match the output produced by the code you previously posted for us to see.

You never didn't tell us how you hooked up the 1307 and if you have the external pullups on the i2c bus signals.

Yes removing power, then removing the battery, re-inserting the battery, and replying power, will leave the RTC halted until you set it which clears the bit to allow it run again.

actually i was trying this code now

#include <Wire.h>
#include <RealTimeClockDS1307.h>

//RealTimeClock RTC;//=new RealTimeClock();

#define Display_Clock_Every_N_Seconds 1
#define Display_ShortHelp_Every_N_Seconds 25
//#define TEST_Squarewave
//#define TEST_StopStart
//#define TEST_1224Switch

int count=0;
char formatted[] = "00-00-00 00:00:00x";

void setup() {
//  Wire.begin();
  Serial.begin(9600);
}
 
void loop() {
  if(Serial.available())
  {
    processCommand();
  }
  delay(1000);
  RTC.readClock();
  count++;
  if(count % Display_Clock_Every_N_Seconds == 0){
    Serial.print(count);
    Serial.print(": ");
    RTC.getFormatted(formatted);
    Serial.print(formatted);
    Serial.println();
  }
  
  if(count % Display_ShortHelp_Every_N_Seconds == 0) {
    Serial.println("Send ? for a list of commands.");
  }
#ifdef TEST_Squarewave
if(count%10 == 0)
{
  switch(count/10 % 6)
  {
    case 0:
    Serial.print("Squarewave disabled (low impedance): ");
    RTC.sqwDisable(0);
    Serial.println((int) RTC.readData(7));
    break;
    case 1:
    Serial.print("Squarewave disabled (high impedance): ");
    RTC.sqwDisable(1);
    Serial.println((int) RTC.readData(7));
    break;
    case 2:
    Serial.println("Squarewave enabled at 1 Hz");
    RTC.sqwEnable(RTC.SQW_1Hz);
    break;
    case 3:
    Serial.println("Squarewave enabled at 4.096 kHz");
    RTC.sqwEnable(RTC.SQW_4kHz);
    break;
    case 4:
    Serial.println("Squarewave enabled at 8.192 kHz");
    RTC.sqwEnable(RTC.SQW_8kHz);
    break;
    case 5:
    Serial.println("Squarewave enabled at 32.768 kHz");
    RTC.sqwEnable(RTC.SQW_32kHz);
    break;
    default:
    Serial.println("Squarewave test not defined");
  }//switch
}
#endif

#ifdef TEST_StopStart
if(count%10 == 0)
{
  if(!RTC.isStopped()) 
  {
    if(RTC.getSeconds() < 45) 
    {
      Serial.println("Stopping clock for 10 seconds");
      RTC.stop();
    }//if we have enough time
  } else {
    RTC.setSeconds(RTC.getSeconds()+11);
    RTC.start();
    Serial.println("Adding 11 seconds and restarting clock");
  }
}//if on a multiple of 10 counts
#endif

#ifdef TEST_1224Switch  
  if(count%10 == 0)
  {
    if(count %20 == 0)
    {
      Serial.println("switching to 12-hour time");
      RTC.switchTo12h();
      RTC.setClock();
    }
    else
    {
      Serial.println("switching to 24-hour time");
      RTC.switchTo24h();
      RTC.setClock();
    }
  }
#endif
}

void processCommand() {
  if(!Serial.available()) { return; }
  char command = Serial.read();
  int in,in2;
  switch(command)
  {
    case 'H':
    case 'h':
    in=SerialReadPosInt();
    RTC.setHours(in);
    RTC.setClock();
    Serial.print("Setting hours to ");
    Serial.println(in);
    break;
    case 'I':
    case 'i':
    in=SerialReadPosInt();
    RTC.setMinutes(in);
    RTC.setClock();
    Serial.print("Setting minutes to ");
    Serial.println(in);
    break;
    case 'S':
    case 's':
    in=SerialReadPosInt();
    RTC.setSeconds(in);
    RTC.setClock();
    Serial.print("Setting seconds to ");
    Serial.println(in);
    break;
    case 'Y':
    case 'y':
    in=SerialReadPosInt();
    RTC.setYear(in);
    RTC.setClock();
    Serial.print("Setting year to ");
    Serial.println(in);
    break;
    case 'M':
    case 'm':
    in=SerialReadPosInt();
    RTC.setMonth(in);
    RTC.setClock();
    Serial.print("Setting month to ");
    Serial.println(in);
    break;
    case 'D':
    case 'd':
    in=SerialReadPosInt();
    RTC.setDate(in);
    RTC.setClock();
    Serial.print("Setting date to ");
    Serial.println(in);
    break;
    case 'W':
    Serial.print("Day of week is ");
    Serial.println((int) RTC.getDayOfWeek());
    break;
    case 'w':
    in=SerialReadPosInt();
    RTC.setDayOfWeek(in);
    RTC.setClock();
    Serial.print("Setting day of week to ");
    Serial.println(in);
    break;
    
    case 't':
    case 'T':
    if(RTC.is12hour()) {
      RTC.switchTo24h();
      Serial.println("Switching to 24-hour clock.");
    } else {
      RTC.switchTo12h();
      Serial.println("Switching to 12-hour clock.");
    }
    RTC.setClock();
    break;
    
    case 'A':
    case 'a':
    if(RTC.is12hour()) {
      RTC.setAM();
      RTC.setClock();
      Serial.println("Set AM.");
    } else {
      Serial.println("(Set hours only in 24-hour mode.)");
    }
    break;
    
    case 'P':
    case 'p':
    if(RTC.is12hour()) {
      RTC.setPM();
      RTC.setClock();
      Serial.println("Set PM.");
    } else {
      Serial.println("(Set hours only in 24-hour mode.)");
    }
    break;

    case 'q':
    RTC.sqwEnable(RTC.SQW_1Hz);
    Serial.println("Square wave output set to 1Hz");
    break;
    case 'Q':
    RTC.sqwDisable(0);
    Serial.println("Square wave output disabled (low)");
    break;
    
    case 'z':
    RTC.start();
    Serial.println("Clock oscillator started.");
    break;
    case 'Z':
    RTC.stop();
    Serial.println("Clock oscillator stopped.");
    break;
    
    case '>':
    in=SerialReadPosInt();
    in2=SerialReadPosInt();
    RTC.writeData(in, in2);
    Serial.print("Write to register ");
    Serial.print(in);
    Serial.print(" the value ");
    Serial.println(in2);
    break;    
    case '<':
    in=SerialReadPosInt();
    in2=RTC.readData(in);
    Serial.print("Read from register ");
    Serial.print(in);
    Serial.print(" the value ");
    Serial.println(in2);
    break;

    default:
    Serial.println("Unknown command. Try these:");
    Serial.println(" h## - set Hours       d## - set Date");
    Serial.println(" i## - set mInutes     m## - set Month");
    Serial.println(" s## - set Seconds     y## - set Year");
    Serial.println(" w## - set arbitrary day of Week");
    Serial.println(" t   - toggle 24-hour mode");
    Serial.println(" a   - set AM          p   - set PM");
    Serial.println();
    Serial.println(" z   - start clock     Z   - stop clock");
    Serial.println(" q   - SQW/OUT = 1Hz   Q   - stop SQW/OUT");
    Serial.println();
    Serial.println(" >##,###  - write to register ## the value ###");
    Serial.println(" <##      - read the value in register ##");
    
  }//switch on command
  
}

//read in numeric characters until something else
//or no more data is available on serial.
int SerialReadPosInt() {
  int i = 0;
  boolean done=false;
  while(Serial.available() && !done)
  {
    char c = Serial.read();
    if (c >= '0' && c <='9')
    {
      i = i * 10 + (c-'0');
    }
    else 
    {
      done = true;
    }
  }
  return i;
}