DS1307 RTC With Arduino

Instead of being sheepish and using an RTC shield, I decided I’d knock up an RTC module myself, its incredibly simple anyway – just a 32.768KHz crystal, a DS1307 chip and a 3v coin cell battery. It talks I2C so only two wires to connect to the Arduino (plus two for power):

If you’re using another I2C device, you should put a 10k pullup resistor on SDA and SCL, and a 0.1uF capacitor on the Vcc if you’re anal about power smoothing.

I used RTClib (not the Adafruit fork) as although the Teensy library works, it also required using their Time library. I haven’t tried the ds1307new library as it seems a bit dead with only a one-line fix since 2011.

The bit that took me the time (pun intended!) was figuring out that if you use a battery backup, once you set the time from the PC, you then have to re-upload the script with the RTC.adjust() line commented out, otherwise as soon as you disconnect and reconnect the Arduino, the DS1307 returns the offset from the previous compile time rather than unplug time or re-upload time or something odd….

Here’s the sourcecode with the offending line highlighted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// include libs
#include <Wire.h>
#include <RTClib.h>
 
// constructor
RTC_DS1307 RTC;
 
void setup()
{
    Serial.begin(9600);
    Wire.begin();
    RTC.begin();
 
    // RTC.adjust(DateTime(__DATE__, __TIME__));}
 
void loop()
{
    // get time
    DateTime now = RTC.now();
 
    if (now.day() < 10) { Serial.print("0"); }
    Serial.print(now.day(), DEC);
    Serial.print("/");
 
    if (now.month() < 10) { Serial.print("0"); }
    Serial.print(now.month(), DEC);
    Serial.print("/");
 
    Serial.println(now.year(), DEC);
 
    if (now.hour() < 10) { Serial.print("0"); }
    Serial.print(now.hour(), DEC);  
    Serial.print(":");
 
    if (now.minute() < 10) { Serial.print("0"); }
    Serial.print(now.minute(), DEC);  
    Serial.print(":");
 
    if (now.second() < 10) { Serial.print("0"); }
    Serial.println(now.second(), DEC);
    Serial.println();
 
    // pause
    delay(1000);
}

Also the Makefile:

ARDUINO_DIR        = /usr/share/arduino
ARDMK_DIR          = /usr
AVR_TOOLS_DIR      = /usr
BOARD_TAG          = mega2560
ARDUINO_PORT       = /dev/ttyACM0
ARDUINO_LIBS       = Wire RTClib
ARDUINO_SKETCHBOOK = /home/user/programming/c++/arduino
 
include /usr/share/arduino/Arduino.mk

Comments are closed.