Arduino app to set DS1307 Real Time Clocks

I use a number of implementations of the DS1307 or DS3231 Real Time Clock chip, preferably the latter these days as they are considerably more accurate and compatible with DS1307 code.

In some applications, it is necessary or sometimes just better to preset the clock before connecting it into the application, and the need arises to set the clock ‘stand alone'. The method I have used for this has been clumsy and not as accurate as one might want for the DS3231, so this article describes a new solution.

IMG_1563

The solution uses an Arduino as the engine if you like. Above is an Arduino Pro, but a range of similar Arduinos would be equally suitable. ALso pictured are three RTCs, one connected to pins A2, A3, A4 and A5 providing GND, VCC, SDA and CLK respectively.

The firmware implements a basic command interpreter with commands to set the clock and read it back.


Above is the code, mostly derived from some various library examples.

Screenshot - 29_05_16 , 16_06_19

Above is a screen shot of the serial monitor in Arduino IDE being used to set and read back the time.

A better idea is a script of some kind that sets the time from the workstation clock. There are a number of ways to do this, the following is an Expect script.

#!/usr/bin/expect
#script to set KISS mode
package require Expect

encoding system iso8859-1

if {[lindex $argv 0] == ""} {
#  set port \\\\.\\COM12
  set port /dev/ttyUSB0
} else {
  set port [lindex $argv 0]
}

set baud 57600
send_tty "Open port $port\n";
set com [open $port r+]
fconfigure $com -mode $baud,n,8,1 -encoding binary -buffering none -translation binary
set spawned [spawn -open $com]
set timeout 2

after 1000
expect {
">>" {
  set newTime [clock seconds]
  set newTime [clock add $newTime 4 seconds]
  send "setrtc [clock format $newTime -format %Y%m%d%H%M%S]\n"}
  }

expect -re $ #clear buffer
expect {
">>" {
  send "getrtc\n"}
  }

after 2000
expect -re .$
#send_tty $expect_out(buffer)

exit

Above, the expect script runs on Windows (under ActiveTCL with Expect) and Linux.

Screenshot - 29_05_16 , 16_07_12

Above, a screen shot of the Expect script running in Windows 10.

A zip of the source and modified command interpreter files is downloadable from setrtc .