DS1302 not keeping time

I have an odd problem with a DS1302 module. I've used the code at Arduino Playground - DS1302 t initially set it up, and am using the library from Electronics - Henning Karlsen as well, now.

When I set the time on the module, it sets correctly and reports the time correctly while still attached to the USB cable. When I plug it back in, though, reading the time starts from where it was when I unplugged it. It doesn't default back to 00:00 etc, nor an I accidentally setting the time in the code I run. Like I say, the time just picks up from whenever it was that I unplugged it.

The first two errors I can understand, and if the battery were flat I'd think it'd go back to defaults (?)

The code I'm using to read the module is just the standard Easy Serial example

// DS1302_Serial_Easy (C)2010 Henning Karlsen
// web: http://www.henningkarlsen.com/electronics
//
// A quick demo of how to use my DS1302-library to 
// quickly send time and date information over a serial link
//
// I assume you know how to connect the DS1302.
// DS1302:  CE pin    -> Arduino Digital 2
//          I/O pin   -> Arduino Digital 3
//          SCLK pin  -> Arduino Digital 4

#include <DS1302.h>

// Init the DS1302
DS1302 rtc(2, 3, 4);

void setup()
{
  // Set the clock to run-mode, and disable the write protection
  rtc.halt(false);
  rtc.writeProtect(true);
  
  // Setup Serial connection
  Serial.begin(9600);

  // The following lines can be commented out to use the values already stored in the DS1302
  // rtc.setDOW(FRIDAY);        // Set Day-of-Week to FRIDAY
  // rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(6, 8, 2010);   // Set the date to August 6th, 2010
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");
  
  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());
  
  // Wait one second before repeating :)
  delay (1000);
}

The are a number of problems with the X-tal for RTCs.
Your battery could be empty or the X-tal could be bad.

The chip uses very little current. It is able to keep the data in memory with a low voltage. However, running the X-tal to get the clock running requires a little more voltage.

I have a DS1302 behaving in exactly the same way.
Except I am sending the data to the LCD display, using the sketch in the example folder.
The battery is fine (3.2V) Im using a small prebuilt module with crystal and backup battery from Hobbytronics.

You did turn on the oscillator?

Hello! I use a DS1302 in one of my projects and I had lots of troubles with it. It shouldn't keep the time whenever connected the usb. Even was losing sync every time I turned on/off the light ( ... yes , i know that sounds crazy , but thats what happened ...) After several hours researching the solution could not be simpler. It is a noise problem. You have to solder a capacitor between pins feeding the chip (pin four and eight) .... just that! 100 nF can do the job. Also try to keep wiring as short as possible . Goodbye problems!!! XD

1 Like

I have the exact same problem. When I unplug the power and wait any amount of time, when I plug it back in, it restarts at the same time it was unplugged. The battery is good though as is the oscillator (checked on a scope). HELP!

I'm having this same exact problem - the DS1302 is backup-powered by a CR2032 3.3V coin cell battery and the main power is 5V. I can set the time and it will maintain time faithfully after that point while 5V is connected to pin 1, however if i remove the main power the chip no longer counts. When i reconnect the 5V power, the clock remembers the last time it was at when the 5V was removed, but any time elapsed between disconnecting and reconnecting 5V is not accounted for.

The halt bit is not set, I make sure by calling:

RTC.haltRTC(false);

in the setup routine. The battery gives 3.3v and I've tried changing it. I'm just using the bare DS1302 module - I have tried 2 different ones with the same result.

Any clues would be most appreciated..

ke123:
Any clues would be most appreciated..

If you post the code you are using and if I can find a DS1302 (I think I have one) I'll try to reproduce the issue. If I can reproduce the issue, I'll try to help figure out the problem.

I'm just using the bare DS1302 module

Have you confirmed that Vbat is indeed present at Vcc1?

I have indeed checked that Vbat is present at Vcc1... If I remove the battery, the RTC loses the time completely. What's happening is it just isn't counting when 5V is not applied to Vcc2 but Vbat IS applied to Vcc1... funny.

Here's the sketch I'm using to set and read the clock.. I'm using the DS1302 library from Arduino Playground - DS1302RTC

/*----------------------------------------------------------------------*
 * Display the date and time from a DS1302 RTC every second.            *
 *                                                                      *
 * Set the date and time by entering the following on the Arduino       *
 * serial monitor:                                                      *
 *    year,month,day,hour,minute,second,                                *
 *                                                                      *
 * Where                                                                *
 *    year can be two or four digits,                                   *
 *    month is 1-12,                                                    *
 *    day is 1-31,                                                      *
 *    hour is 0-23, and                                                 *
 *    minute and second are 0-59.                                       *
 *                                                                      *
 * Entering the final comma delimiter (after "second") will avoid a     *
 * one-second timeout and will allow the RTC to be set more accurately. *
 *                                                                      *
 * No validity checking is done, invalid values or incomplete syntax    *
 * in the input will result in an incorrect RTC setting.                *
 *                                                                      *
 * Jack Christensen 08Aug2013                                           *
 *                                                                      *
 * Adopted for DS1302RTC library by Timur Maksimov 2014                 *
 *                                                                      *
 * This work is licensed under the Creative Commons Attribution-        *
 * ShareAlike 3.0 Unported License. To view a copy of this license,     *
 * visit http://creativecommons.org/licenses/by-sa/3.0/ or send a       *
 * letter to Creative Commons, 171 Second Street, Suite 300,            *
 * San Francisco, California, 94105, USA.                               *
 *----------------------------------------------------------------------*/ 
 
#include <DS1302RTC.h>
#include <Streaming.h>        //http://arduiniana.org/libraries/streaming/
#include <Time.h>             //http://playground.arduino.cc/Code/Time

// Set pins:  CE, IO,CLK
DS1302RTC RTC(10, 11, 12);

// Optional connection for RTC module
//#define DS1302_GND_PIN 33
//#define DS1302_VCC_PIN 35

void setup(void)
{
  Serial.begin(115200);
    
  // Activate RTC module
 /* digitalWrite(DS1302_GND_PIN, LOW);
  pinMode(DS1302_GND_PIN, OUTPUT);

  digitalWrite(DS1302_VCC_PIN, HIGH);
  pinMode(DS1302_VCC_PIN, OUTPUT);
  */
  Serial << F("RTC module activated");
  Serial << endl;
  delay(500);
  
  if (RTC.haltRTC()) {
    Serial << F("The DS1302 is stopped.  Please set time");
    Serial << F("to initialize the time and begin running.");
    Serial << endl;
  }
  if (!RTC.writeEN()) {
    Serial << F("The DS1302 is write protected. This normal.");
    Serial << endl;
  }
  
  delay(5000);
    
  //setSyncProvider() causes the Time library to synchronize with the
  //external RTC by calling RTC.get() every five minutes by default.
  setSyncProvider(RTC.get);

  Serial << F("RTC Sync");
  if (timeStatus() == timeSet)
    Serial << F(" Ok!");
  else
    Serial << F(" FAIL!");
  Serial << endl;
}

void loop(void)
{
    static time_t tLast;
    time_t t;
    tmElements_t tm;

    //check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
    if (Serial.available() >= 12) {
        //note that the tmElements_t Year member is an offset from 1970,
        //but the RTC wants the last two digits of the calendar year.
        //use the convenience macros from Time.h to do the conversions.
        int y = Serial.parseInt();
        if (y >= 100 && y < 1000)
            Serial << F("Error: Year must be two digits or four digits!") << endl;
        else {
            if (y >= 1000)
                tm.Year = CalendarYrToTm(y);
            else    //(y < 100)
                tm.Year = y2kYearToTm(y);
            tm.Month = Serial.parseInt();
            tm.Day = Serial.parseInt();
            tm.Hour = Serial.parseInt();
            tm.Minute = Serial.parseInt();
            tm.Second = Serial.parseInt();
            t = makeTime(tm);
	    //use the time_t value to ensure correct weekday is set
            if(RTC.set(t) == 0) { // Success
              setTime(t);
              Serial << F("RTC set to: ");
              printDateTime(t);
              Serial << endl;
	    }
	    else
	      Serial << F("RTC set failed!") << endl;
            //dump any extraneous input
            while (Serial.available() > 0) Serial.read();
        }
    }
    
    t = now();
    if (t != tLast) {
        tLast = t;
        printDateTime(t);
        Serial << endl;
    }
}

//print date and time to Serial
void printDateTime(time_t t)
{
    printDate(t);
    Serial << ' ';
    printTime(t);
}

//print time to Serial
void printTime(time_t t)
{
    printI00(hour(t), ':');
    printI00(minute(t), ':');
    printI00(second(t), ' ');
}

//print date to Serial
void printDate(time_t t)
{
    printI00(day(t), 0);
    Serial << monthShortStr(month(t)) << _DEC(year(t));
}

//Print an integer in "00" format (with leading zero),
//followed by a delimiter character to Serial.
//Input value assumed to be between 0 and 99.
void printI00(int val, char delim)
{
    if (val < 10) Serial << '0';
    Serial << _DEC(val);
    if (delim > 0) Serial << delim;
    return;
}

If I remove the battery, the RTC loses the time completely.

I believe that this is normal if you have also removed the 5v from Vcc2, The ram is not non volatile, but battery backed. 5v Vcc2 and no battery should be OK.

What's happening is it just isn't counting when 5V is not applied to Vcc2 but Vbat IS applied to Vcc1...

Yes, the chip is obviously not running under battery power.

Can you provide a schematic of how you have the chip wired? What are you using for a crystal? Where did you purchase the chip?

Here's a link to a thread where a DS1307 would not run under battery power. It turned out to be a defective counterfeit chip, but there were possible crystal issues as well. DS1307 Real Time Clock CH bit problem - Project Guidance - Arduino Forum

So while I was at the drugstore I bought a name brand CR2032 battery for the heck of it.. and now the clock holds time fine with that installed.

The ones I was using were bought from IKEA of all places (to run their little apple-lights or whatever) and it looks like they just weren't up to the job. They have all been reading 3.3V.. maybe there was voltage drop when the DS1302 was pulling current from the battery? Hard to imagine given this chip pulls so little.. but here we have it.. maybe damaged batteries? There are some tiny dents on the negative terminal of the last one installed.. hrm.

Thanks to all for the input...sorry the problem couldn't be more interesting :smiley:

just remove this after you update the time

// The following lines can be commented out to use the values already stored in the DS1302
// rtc.setDOW(FRIDAY); // Set Day-of-Week to FRIDAY
// rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
// rtc.setDate(6, 8, 2010); // Set the date to August 6th, 2010

i mean for the first time if the time is wrong then upload with this then after time has been updated then removed this and upload again . that it