DS3231

Driver for the DS3231 high precision RTC and the DS1337 RTC.

Features

The DS3231 keeps a 32.768 kHz crystal inside a temperature compensated oscillator, so it stays within ±2 ppm (about a minute per year) between 0 and +40 °C and within ±3.5 ppm over the full −40…+85 °C range. The DS1337 is the same register map and the same two-wire interface without the compensated oscillator and without the temperature sensor.

The address of both chips is fixed: 0x68. The DS3231 runs from 2.3 to 5.5 V, its I²C pins are open drain, 400 kHz is the maximum bus speed and the descriptor is created with it. The backup cell goes to VBAT (2.3…3.5 V, CR2032 is the usual choice) and keeps the oscillator and the 32 kHz output running when VCC is gone. Most breakout boards carry the chip, the cell, the pull-ups and sometimes an AT24C32 EEPROM on the same module; the EEPROM is a separate device at 0x57 and this driver does not touch it.

The time

The chip stores seven BCD bytes: seconds, minutes, hours, day of week, date, month and year. ds3231_get_time() fills a struct tm:

i2c_dev_t dev = { 0 };
ESP_ERROR_CHECK(ds3231_init_desc(&dev, 0, GPIO_NUM_18, GPIO_NUM_19));

struct tm now;
ESP_ERROR_CHECK(ds3231_get_time(&dev, &now));

printf("%04d-%02d-%02d %02d:%02d:%02d\n", now.tm_year + 1900,
       now.tm_mon + 1, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec);

tm_hour is always 0…23. The chip can also hold the hour in 12-hour format with the AM/PM flag in bit 5, and the driver converts it on the way out; the conversion is the only reason that branch exists. ds3231_set_time() always writes 24-hour format and also fills the day of week, so tm_wday must be set (0 is Sunday) and the other fields must be a real date: seconds and minutes 0…59, hours 0…23, day 1…31, month 0…11, year 100…199.

The year field of the chip is two digits. The driver maps tm_year 100…199 to 2000…2099 and does not touch the century bit in the month register, so dates outside that window are not representable.

The chip keeps whatever the application writes: it is not a UTC clock and has no idea about time zones or daylight saving time. tm_isdst comes back as −1, meaning “unknown”, and tm_yday is calculated by the driver.

Bad time detection

The oscillator stop flag (ds3231_get_oscillator_stop_flag()) is set by the chip when the oscillator has stopped, which happens when both supplies were lost. In that case the time registers hold garbage, and the usual sequence is to read the flag, set the time with ds3231_set_time() and clear the flag with ds3231_clear_oscillator_stop_flag().

A cell that has been removed for a while leaves the registers at 0xFF. ds3231_get_time() checks every byte for valid BCD digits and every field for a valid range, and returns ESP_ERR_INVALID_RESPONSE instead of handing out values such as month 164. The same error comes back when the hour in 12-hour mode is outside 1…12.

Alarms

The DS3231 has two alarms: alarm 1 has a seconds resolution and can fire every second, on a second, on a second and a minute, on seconds, minutes and hours, and on top of that on a day of week or a date; alarm 2 has a minutes resolution and the same choices without seconds.

ds3231_set_alarm() takes the alarm selection (DS3231_ALARM_1, DS3231_ALARM_2, DS3231_ALARM_BOTH), one struct tm and one rate constant per alarm. Only the fields the chosen rate uses have to be filled:

struct tm alarm = { .tm_hour = 7, .tm_min = 30 };

ESP_ERROR_CHECK(ds3231_set_alarm(&dev, DS3231_ALARM_1, &alarm,
        DS3231_ALARM1_MATCH_SECMINHOUR, NULL, DS3231_ALARM2_EVERY_MIN));

The day of week and date variants use the DY/DT bit of the alarm register; the driver sets it according to the rate constant, and the day of week is written as 1…7 with 1 for Sunday, following tm_wday + 1.

Whether an alarm has fired is visible in the status register: ds3231_get_alarm_flags() returns DS3231_ALARM_1, DS3231_ALARM_2, DS3231_ALARM_BOTH or DS3231_ALARM_NONE, and ds3231_clear_alarm_flags() clears them.

The A1IE/A2IE interrupt enable bits of the control register are not exposed by this driver: the flags are readable, but the pin is not driven by the alarms. The INT/SQW pin is configured only through the square wave functions below.

Square wave output

With INTCN cleared the INT/SQW pin outputs a square wave. ds3231_enable_squarewave() clears it and ds3231_disable_squarewave() sets it back, which returns the pin to the interrupt function.

ds3231_set_squarewave_freq() picks the frequency from DS3231_SQWAVE_1HZ, DS3231_SQWAVE_1024HZ, DS3231_SQWAVE_4096HZ and DS3231_SQWAVE_8192HZ; ds3231_get_squarewave_freq() reads it back. The call changes only the RS2/RS1 bits and leaves the rest of the control register alone. Remember that the frequency has no effect while INTCN is set, that is until ds3231_enable_squarewave() is called.

32 kHz output

ds3231_enable_32khz() and ds3231_disable_32khz() control the EN32kHz bit in the status register. The output runs from the backup cell as well, so it stays available with VCC off, and it is disabled after a power-on reset until the application enables it.

Temperature

The chip measures its own die temperature every 64 seconds and stores it as a 10-bit signed value with a 0.25 °C resolution. ds3231_get_temp_float() returns degrees Celsius, ds3231_get_temp_integer() returns whole degrees (truncated towards minus infinity), and ds3231_get_raw_temp() returns the raw value in quarters of a degree.

The die is warmed by the chip itself, so the reading is a few degrees above the ambient temperature. It is meant for the oscillator compensation, not as a room thermometer.

Aging offset

ds3231_set_aging_offset() writes the signed aging register; each LSB moves the oscillator by about 0.1 ppm at 25 °C. The call also sets the CONV bit, which starts a temperature conversion, so the effect on the 32 kHz output can be measured immediately. ds3231_get_aging_offset() reads the value back as a signed byte. A positive value slows the oscillator down. The register is only useful for trimming a particular board against a reference; the factory value is zero and it survives a power loss.

Limitations

  • one descriptor per device; the driver serialises the transactions of that descriptor with its own mutex, but two descriptors pointing to the same chip are not coordinated;

  • the century bit is not used, so years are limited to 2000…2099;

  • the alarm interrupt enable bits are not exposed, only the alarm flags;

  • the temperature is the die temperature and is updated once per 64 seconds unless a conversion is requested through the aging register;

  • the DS1337 has no temperature sensor and no aging register: those calls fail or return meaningless values on that chip.

Configuration

The component itself has nothing to configure. The pins live in the example: CONFIG_EXAMPLE_I2C_MASTER_SDA and CONFIG_EXAMPLE_I2C_MASTER_SCL are set in menuconfig under the example’s own options, the defaults are 18 and 19.

Example

examples/default sets the time once (2016-10-09 13:50:10), then prints the time and the temperature every 250 ms:

2016-10-09 13:50:10, 24.25 deg Cel
2016-10-09 13:50:11, 24.25 deg Cel

API Reference

Defines

DS3231_ADDR

I2C address.

Enums

enum ds3231_alarm_t

Alarms.

Values:

enumerator DS3231_ALARM_NONE

No alarms.

enumerator DS3231_ALARM_1

First alarm.

enumerator DS3231_ALARM_2

Second alarm.

enumerator DS3231_ALARM_BOTH

Both alarms.

enum ds3231_alarm1_rate_t

First alarm rate.

Values:

enumerator DS3231_ALARM1_EVERY_SECOND
enumerator DS3231_ALARM1_MATCH_SEC
enumerator DS3231_ALARM1_MATCH_SECMIN
enumerator DS3231_ALARM1_MATCH_SECMINHOUR
enumerator DS3231_ALARM1_MATCH_SECMINHOURDAY
enumerator DS3231_ALARM1_MATCH_SECMINHOURDATE
enum ds3231_alarm2_rate_t

Second alarm rate.

Values:

enumerator DS3231_ALARM2_EVERY_MIN
enumerator DS3231_ALARM2_MATCH_MIN
enumerator DS3231_ALARM2_MATCH_MINHOUR
enumerator DS3231_ALARM2_MATCH_MINHOURDAY
enumerator DS3231_ALARM2_MATCH_MINHOURDATE
enum ds3231_sqwave_freq_t

Squarewave frequency.

Values:

enumerator DS3231_SQWAVE_1HZ
enumerator DS3231_SQWAVE_1024HZ
enumerator DS3231_SQWAVE_4096HZ
enumerator DS3231_SQWAVE_8192HZ

Functions

esp_err_t ds3231_init_desc(i2c_dev_t *dev, i2c_port_t port, gpio_num_t sda_gpio, gpio_num_t scl_gpio)

Initialize device descriptor.

Parameters:
  • dev – I2C device descriptor

  • port – I2C port

  • sda_gpio – SDA GPIO

  • scl_gpio – SCL GPIO

Returns:

ESP_OK to indicate success

esp_err_t ds3231_free_desc(i2c_dev_t *dev)

Free device descriptor.

Parameters:

dev – I2C device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_set_time(i2c_dev_t *dev, const struct tm *time)

Set the time on the RTC.

Timezone agnostic, pass whatever you like. I suggest using GMT and applying timezone and DST when read back.

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_time(i2c_dev_t *dev, struct tm *time)

Get the time from the RTC, populates a supplied tm struct.

Parameters:
  • dev – Device descriptor

  • time – [out] RTC time

Returns:

ESP_OK to indicate success

esp_err_t ds3231_set_alarm(i2c_dev_t *dev, ds3231_alarm_t alarms, const struct tm *time1, ds3231_alarm1_rate_t option1, const struct tm *time2, ds3231_alarm2_rate_t option2)

Set alarms.

alarm1 works with seconds, minutes, hours and day of week/month, or fires every second. alarm2 works with minutes, hours and day of week/month, or fires every minute.

Not all combinations are supported, see DS3231_ALARM1_* and DS3231_ALARM2_* defines for valid options you only need to populate the fields you are using in the tm struct, and you can set both alarms at the same time (pass DS3231_ALARM_1/DS3231_ALARM_2/DS3231_ALARM_BOTH).

If only setting one alarm just pass 0 for tm struct and option field for the other alarm. If using DS3231_ALARM1_EVERY_SECOND/DS3231_ALARM2_EVERY_MIN you can pass 0 for tm struct.

If you want to enable interrupts for the alarms you need to do that separately.

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_oscillator_stop_flag(i2c_dev_t *dev, bool *flag)

Check if oscillator has previously stopped.

E.g. no power/battery or disabled sets flag to true if there has been a stop

Parameters:
  • dev – Device descriptor

  • flag – [out] Stop flag

Returns:

ESP_OK to indicate success

esp_err_t ds3231_clear_oscillator_stop_flag(i2c_dev_t *dev)

Clear the oscillator stopped flag.

Parameters:

dev – Device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_alarm_flags(i2c_dev_t *dev, ds3231_alarm_t *alarms)

Check which alarm(s) have past.

Sets alarms to DS3231_ALARM_NONE/DS3231_ALARM_1/DS3231_ALARM_2/DS3231_ALARM_BOTH

Parameters:
  • dev – Device descriptor

  • alarms – [out] Alarms

Returns:

ESP_OK to indicate success

esp_err_t ds3231_clear_alarm_flags(i2c_dev_t *dev, ds3231_alarm_t alarms)

Clear alarm past flag(s)

Pass DS3231_ALARM_1/DS3231_ALARM_2/DS3231_ALARM_BOTH

Parameters:
  • dev – Device descriptor

  • alarms – Alarms

Returns:

ESP_OK to indicate success

esp_err_t ds3231_enable_alarm_ints(i2c_dev_t *dev, ds3231_alarm_t alarms)

enable alarm interrupts (and disables squarewave)

Pass DS3231_ALARM_1/DS3231_ALARM_2/DS3231_ALARM_BOTH.

If you set only one alarm the status of the other is not changed you must also clear any alarm past flag(s) for alarms with interrupt enabled, else it will trigger immediately.

Parameters:
  • dev – Device descriptor

  • alarms – Alarms

Returns:

ESP_OK to indicate success

esp_err_t ds3231_disable_alarm_ints(i2c_dev_t *dev, ds3231_alarm_t alarms)

Disable alarm interrupts.

Does not (re-)enable squarewave

Parameters:
  • dev – Device descriptor

  • alarms – Alarm

Returns:

ESP_OK to indicate success

esp_err_t ds3231_enable_32khz(i2c_dev_t *dev)

Enable the output of 32khz signal.

Supported only by DS3231

Parameters:

dev – Device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_disable_32khz(i2c_dev_t *dev)

Disable the output of 32khz signal.

Supported only by DS3231

Parameters:

dev – Device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_enable_squarewave(i2c_dev_t *dev)

Enable the squarewave output.

Disables alarm interrupt functionality.

Parameters:

dev – Device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_disable_squarewave(i2c_dev_t *dev)

Disable the squarewave output.

Which re-enables alarm interrupts, but individual alarm interrupts also need to be enabled, if not already, before they will trigger.

Parameters:

dev – Device descriptor

Returns:

ESP_OK to indicate success

esp_err_t ds3231_set_squarewave_freq(i2c_dev_t *dev, ds3231_sqwave_freq_t freq)

Set the frequency of the squarewave output.

Does not enable squarewave output.

Parameters:
  • dev – Device descriptor

  • freq – Squarewave frequency

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_squarewave_freq(i2c_dev_t *dev, ds3231_sqwave_freq_t *freq)

Get the frequency of the squarewave output.

Does not enable squarewave output.

Parameters:
  • dev – Device descriptor

  • freq – Squarewave frequency to store the output

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_raw_temp(i2c_dev_t *dev, int16_t *temp)

Get the raw temperature value.

Supported only by DS3231

Parameters:
  • dev – Device descriptor

  • temp – [out] Raw temperature value

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_temp_integer(i2c_dev_t *dev, int8_t *temp)

Get the temperature as an integer.

Supported only by DS3231

Parameters:
  • dev – Device descriptor

  • temp – [out] Temperature, degrees Celsius

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_temp_float(i2c_dev_t *dev, float *temp)

Get the temperature as a float.

Supported only by DS3231

Parameters:
  • dev – Device descriptor

  • temp – [out] Temperature, degrees Celsius

Returns:

ESP_OK to indicate success

esp_err_t ds3231_set_aging_offset(i2c_dev_t *dev, int8_t age)

Set the aging offset register to a new value.

Positive aging values add capacitance to the array, slowing the oscillator frequency. Negative values remove capacitance from the array, increasing the oscillator frequency.

Supported only by DS3231

Parameters:
  • dev – Device descriptor

  • age – Aging offset (in range [-128, 127]) to be set

Returns:

ESP_OK to indicate success

esp_err_t ds3231_get_aging_offset(i2c_dev_t *dev, int8_t *age)

Get the aging offset register.

Supported only by DS3231

Parameters:
  • dev – Device descriptor

  • age – [out] Aging offset in range [-128, 127]

Returns:

ESP_OK to indicate success