DS3231 I2C Real-Time Clock
The DS3231 RTC module [1] is a low-cost, extremely accurate I2C real-time clock with an integrated temperature-compensated crystal oscillator. It also provides the date and two time of day alarms. It wil run from 2.3 V to 5.5 V.
Breakouts are available from Seeed Studio [2] and Adafruit [3].
The I2C address is 104 or #x68.
Setting the time
The following routine sets the time:
(defun ds3231-set (hr min) (with-i2c (str #x68) (write-byte 0 str) (write-byte 0 str) (write-byte min str) (write-byte hr str)))
The first call to write-byte sets the starting register to write to in the DS3234; in this case 0, the seconds register. We then set the seconds to 0, the minutes to min, and the hours to hr. The times are defined in binary-coded decimal, so to set the time to 12:34 you need to evaluate:
(ds3231-set #x12 #x34)
Once you have set the time the backup battery will keep the time correct in the DS3231.
Reading the time
Here's the routine ds3231-time to read the time:
(defun ds3231-time ()
(with-i2c (str #x68) (write-byte 0 str) (restart-i2c str 3) (list (read-byte str) (read-byte str) (read-byte str))))
It returns the time as a list of three binary-coded decimal numbers: (sec min hrs). For example 12:34:56 will be:
(86 52 18)
because 86 is #x56, 52 is #x34, and 18 is #x12. It's a simple extension to this to read the date and other registers; see the datasheet.
For an application to make a stand-alone digital clock programmed in Lisp see I2C clock.
- ^ DS3231 Datasheet on Maxim Integrated.
- ^ Mini RTC Module on Seeed Studio.
- ^ Adafruit DS3231 Precision RTC Breakout on Adafruit.