ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
ds3231.cpp
Go to the documentation of this file.
1#include "ds3231.h"
2#include "esphome/core/log.h"
3
4// Datasheet:
5// - https://www.analog.com/media/en/technical-documentation/data-sheets/DS3231.pdf
6
7namespace esphome::ds3231 {
8
9ESPHOME_LOG_TAG(TAG, "ds3231");
10
11static constexpr uint8_t DS3231_REG_CONTROL = 0x0E;
12static constexpr uint8_t DS3231_REG_TEMPERATURE = 0x11;
13
15 if (!this->read_control_status_()) {
16 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
17 return;
18 }
19
20 this->control_reg_ &= ~CONTROL_EOSC; // keep the oscillator running on battery
21 // INT/SQW is the (unused) interrupt line rather than a square-wave output.
23 if (!this->write_control_()) {
24 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
25 return;
26 }
27}
28
30 ESP_LOGCONFIG(TAG, "DS3231:");
31 LOG_I2C_DEVICE(this);
32}
33
35 uint8_t raw[2];
36 if (this->is_failed() || !this->read_bytes(DS3231_REG_TEMPERATURE, raw, sizeof(raw))) {
37 return false;
38 }
39 // 10-bit two's complement, 0.25 degC per LSB.
40 int16_t value = static_cast<int16_t>((raw[0] << 8) | raw[1]) >> 6;
41 out = value * 0.25f;
42 return true;
43}
44
46 // Just kick off the conversion - the chip clears CONV and updates the temperature
47 // register on its own within ~200 ms, and the next temperature poll picks it up.
48 // Blocking here to wait for it would stall the main loop.
49 if (this->is_failed() || !this->read_control_status_())
50 return;
51 if ((this->status_reg_ & STATUS_BSY) != 0) {
52 ESP_LOGW(TAG, "A temperature conversion is already in progress.");
53 return;
54 }
56 this->write_control_();
57}
58
60 uint8_t raw[2];
61 if (!this->read_bytes(DS3231_REG_CONTROL, raw, sizeof(raw))) {
62 ESP_LOGW(TAG, "Can't read control/status registers.");
63 return false;
64 }
65 this->control_reg_ = raw[0];
66 this->status_reg_ = raw[1];
67 return true;
68}
69
71 if (!this->write_byte(DS3231_REG_CONTROL, this->control_reg_)) {
72 ESP_LOGW(TAG, "Can't write control register.");
73 return false;
74 }
75 return true;
76}
77
78} // namespace esphome::ds3231
uint8_t raw[35]
Definition bl0939.h:0
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:274
static constexpr uint8_t CONTROL_INTCN
Definition ds3231.h:19
bool read_temperature(float &out)
Definition ds3231.cpp:34
static constexpr uint8_t STATUS_BSY
Definition ds3231.h:23
static constexpr uint8_t CONTROL_CONV
Definition ds3231.h:20
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:265
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Compat APIs All methods below have been added for compatibility reasons.
Definition i2c.h:217
std::vector< uint8_t > & out
Definition gif.cpp:49
ESPHOME_LOG_TAG(TAG, "ds3231")