ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
lis2dw12.cpp
Go to the documentation of this file.
1#include "lis2dw12.h"
3#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
6
8
9ESPHOME_LOG_TAG(TAG, "lis2dw12");
10
11static constexpr uint8_t LIS2DW12_WHO_AM_I_VALUE = 0x44;
12static constexpr float GRAVITY_EARTH = 9.80665f;
13static constexpr uint32_t EVENT_COOLDOWN_MS = 500;
14static constexpr uint32_t POLL_INTERVAL_MS = 50;
15static constexpr uint8_t SIXD_POSITION_MASK = 0x3F; // XL..ZH, leaving out D6D_IA
16
17// Indexed by PowerMode
18PROGMEM_STRING_TABLE(PowerModeStrings, "High Performance", "Low Power 1 (12-bit)", "Low Power 2", "Low Power 3",
19 "Low Power 4", "Unknown");
20
21// Indexed by Range
22PROGMEM_STRING_TABLE(RangeStrings, "±2g", "±4g", "±8g", "±16g", "Unknown");
23
24// Indexed by DataRate
25PROGMEM_STRING_TABLE(DataRateStrings, "Unknown", "1.6 Hz", "12.5 Hz", "25 Hz", "50 Hz", "100 Hz", "200 Hz", "400 Hz",
26 "800 Hz", "1600 Hz");
27
28// Indexed by FilterBandwidth
29PROGMEM_STRING_TABLE(FilterBandwidthStrings, "ODR/2", "ODR/4", "ODR/10", "ODR/20", "Unknown");
30
32 uint8_t who_am_i{0};
33 if (!this->setup_check(this->read_byte(static_cast<uint8_t>(RegisterMap::WHO_AM_I), &who_am_i)))
34 return;
35 if (who_am_i != LIS2DW12_WHO_AM_I_VALUE) {
36 ESP_LOGE(TAG, "WHO_AM_I check failed. Got 0x%02X, expected 0x%02X", who_am_i, LIS2DW12_WHO_AM_I_VALUE);
37 this->mark_failed(LOG_STR("Wrong chip ID"));
38 return;
39 }
40
41 // Soft reset
42 if (!this->setup_check(this->write_reg_(RegisterMap::CTRL2, 0x40), LOG_STR("Soft reset failed")))
43 return;
44 delay(1); // NOLINT - wait for reset to complete
45
46 uint8_t ctrl2{0};
47 if (!this->read_byte(static_cast<uint8_t>(RegisterMap::CTRL2), &ctrl2) || (ctrl2 & 0x40)) {
48 this->mark_failed(LOG_STR("Soft reset did not complete"));
49 return;
50 }
51
52 if (!this->setup_check(this->configure_registers_(), LOG_STR("Register configuration failed")))
53 return;
54
55 // 0.244 mg/LSB at ±2g (14-bit), doubling per range step; 12-bit LP1 is 4x coarser
56 const bool lp1 = this->power_mode_ == PowerMode::LOW_POWER_1;
57 const uint8_t range_idx = static_cast<uint8_t>(this->range_);
58 const float mg = 0.244f * (1u << range_idx) * (lp1 ? 4 : 1);
59 this->scale_ = mg * 0.001f * GRAVITY_EARTH;
60 this->shift_ = lp1 ? 4 : 2;
61
62 bool events_used = !this->tap_callback_.empty() || !this->double_tap_callback_.empty() ||
63 !this->freefall_callback_.empty() || !this->active_callback_.empty() ||
64 !this->orientation_callback_.empty();
65#ifdef USE_BINARY_SENSOR
66 for (auto *sensor : this->event_binary_sensors_) {
67 if (sensor != nullptr) {
68 sensor->publish_initial_state(false);
69 events_used = true;
70 }
71 }
72#endif
73#ifdef USE_TEXT_SENSOR
74 RegSixdSrc sixd;
75 if (this->orientation_text_sensor_ != nullptr &&
76 this->read_byte(static_cast<uint8_t>(RegisterMap::SIXD_SRC), &sixd.raw)) {
77 this->publish_orientation_(sixd);
78 events_used = true;
79 }
80#endif
81 if (!events_used) {
82 this->disable_loop(); // nothing consumes the events, so skip polling the chip
83 }
84}
85
87 // CTRL1: ODR[7:4], MODE[3:2] (00=low power, 01=high performance), LP_MODE[1:0] (LP1..LP4)
88 const uint8_t odr_bits = static_cast<uint8_t>(this->data_rate_) << 4;
89 uint8_t ctrl1;
90 if (this->power_mode_ == PowerMode::HIGH_PERF) {
91 ctrl1 = odr_bits | 0x04;
92 } else {
93 ctrl1 = odr_bits | ((static_cast<uint8_t>(this->power_mode_) - 1) & 0x03);
94 }
95
96 // CTRL6: BW_FILT[7:6], FS[5:4], LOW_NOISE[2]
97 uint8_t ctrl6 = (static_cast<uint8_t>(this->filter_bandwidth_) << 6) | (static_cast<uint8_t>(this->range_) << 4);
98 if (this->low_noise_) {
99 ctrl6 |= 0x04;
100 }
101
102 return this->write_reg_(RegisterMap::CTRL2, 0x0C) && // BDU, IF_ADD_INC
103 this->write_reg_(RegisterMap::CTRL1, ctrl1) && // ODR and power mode
104 this->write_reg_(RegisterMap::CTRL6, ctrl6) && // bandwidth, range, low noise
105 this->write_reg_(RegisterMap::TAP_THS_X, 0x29) && // 6D_THS=70 degrees, TAP_THSX=9
106 this->write_reg_(RegisterMap::TAP_THS_Y, 0x09) && // TAP_THSY=9
107 this->write_reg_(RegisterMap::TAP_THS_Z, 0xE9) && // TAP_THSZ=9, tap on X/Y/Z
108 this->write_reg_(RegisterMap::INT_DUR, 0x76) && // LATENCY=7, QUIET=1, SHOCK=2
109 this->write_reg_(RegisterMap::WAKE_UP_THS, 0x82) && // double tap enabled, WU_THS=2
110 this->write_reg_(RegisterMap::WAKE_UP_DUR, 0x00) && // no wake/sleep durations
111 this->write_reg_(RegisterMap::FREE_FALL, 0x33) && // FF_DUR=6, FF_THS=312 mg
112 this->write_reg_(RegisterMap::CTRL4_INT1, 0xF8) && // 6D, single tap, wake-up, free-fall, double tap to INT1
113 this->write_reg_(RegisterMap::CTRL3, 0x10) && // LIR: latched interrupts
114 this->write_reg_(RegisterMap::CTRL7, 0x20); // INTERRUPTS_ENABLE
115}
116
118 ESP_LOGCONFIG(TAG, "LIS2DW12:");
119 ESP_LOGCONFIG(TAG,
120 " Power Mode: %s\n"
121 " Data Rate: %s\n"
122 " Range: %s\n"
123 " Filter Bandwidth: %s\n"
124 " Low Noise: %s\n"
125 " Offsets: {%.3f m/s², %.3f m/s², %.3f m/s²}\n"
126 " Transform: {mirror_x=%s, mirror_y=%s, mirror_z=%s, swap_xy=%s}",
127 LOG_STR_ARG(PowerModeStrings::get_log_str(this->power_mode_)),
128 LOG_STR_ARG(DataRateStrings::get_log_str(this->data_rate_, 0)),
129 LOG_STR_ARG(RangeStrings::get_log_str(this->range_)),
130 LOG_STR_ARG(FilterBandwidthStrings::get_log_str(this->filter_bandwidth_)), YESNO(this->low_noise_),
131 this->offset_x_, this->offset_y_, this->offset_z_, YESNO(this->mirror_x_), YESNO(this->mirror_y_),
132 YESNO(this->mirror_z_), YESNO(this->swap_xy_));
133 LOG_UPDATE_INTERVAL(this);
134
135#ifdef USE_BINARY_SENSOR
136 LOG_BINARY_SENSOR(" ", "Tap", this->event_binary_sensors_[EVENT_TAP]);
137 LOG_BINARY_SENSOR(" ", "Double Tap", this->event_binary_sensors_[EVENT_DOUBLE_TAP]);
138 LOG_BINARY_SENSOR(" ", "Freefall", this->event_binary_sensors_[EVENT_FREEFALL]);
139 LOG_BINARY_SENSOR(" ", "Active", this->event_binary_sensors_[EVENT_ACTIVE]);
140#endif
141
142#ifdef USE_SENSOR
143 LOG_SENSOR(" ", "Acceleration X", this->acceleration_x_sensor_);
144 LOG_SENSOR(" ", "Acceleration Y", this->acceleration_y_sensor_);
145 LOG_SENSOR(" ", "Acceleration Z", this->acceleration_z_sensor_);
146#endif
147
148#ifdef USE_TEXT_SENSOR
149 LOG_TEXT_SENSOR(" ", "Orientation", this->orientation_text_sensor_);
150#endif
151}
152
153bool LIS2DW12Component::read_acceleration_data_(float &x, float &y, float &z) {
154 uint8_t accel_data[6];
155 if (!this->read_bytes(static_cast<uint8_t>(RegisterMap::OUT_X_L), accel_data, 6)) {
156 return false;
157 }
158
159 int16_t raw_x = encode_value_le<int16_t>(accel_data) >> this->shift_;
160 int16_t raw_y = encode_value_le<int16_t>(&accel_data[2]) >> this->shift_;
161 int16_t raw_z = encode_value_le<int16_t>(&accel_data[4]) >> this->shift_;
162
163 if (this->swap_xy_) {
164 std::swap(raw_x, raw_y);
165 }
166 x = (this->mirror_x_ ? -raw_x : raw_x) * this->scale_ + this->offset_x_;
167 y = (this->mirror_y_ ? -raw_y : raw_y) * this->scale_ + this->offset_y_;
168 z = (this->mirror_z_ ? -raw_z : raw_z) * this->scale_ + this->offset_z_;
169 return true;
170}
171
172#ifdef USE_TEXT_SENSOR
173static const char *orientation_to_string(RegSixdSrc sixd) {
174 if (sixd.xh)
175 return "X Up";
176 if (sixd.xl)
177 return "X Down";
178 if (sixd.yh)
179 return "Y Up";
180 if (sixd.yl)
181 return "Y Down";
182 if (sixd.zh)
183 return "Z Up";
184 if (sixd.zl)
185 return "Z Down";
186 return "Unknown";
187}
188
190 const uint8_t position = sixd.raw & SIXD_POSITION_MASK;
191 if (this->orientation_text_sensor_ == nullptr || position == this->sixd_last_) {
192 return;
193 }
194 this->sixd_last_ = position;
195 this->orientation_text_sensor_->publish_state(orientation_to_string(sixd));
196}
197#endif
198
199void LIS2DW12Component::handle_event_(Event event, bool active, uint32_t now, LazyCallbackManager<void()> &callback) {
200 const uint8_t bit = 1 << event;
201 bool state;
202 if (active) {
203 if (now - this->last_event_ms_[event] <= EVENT_COOLDOWN_MS) {
204 return;
205 }
206 this->last_event_ms_[event] = now;
207 callback.call();
208 if (this->events_on_ & bit) {
209 return;
210 }
211 this->events_on_ |= bit;
212 state = true;
213 } else {
214 if (!(this->events_on_ & bit) || now - this->last_event_ms_[event] <= EVENT_COOLDOWN_MS) {
215 return;
216 }
217 this->events_on_ &= ~bit;
218 state = false;
219 }
220#ifdef USE_BINARY_SENSOR
221 PUBLISH_STATE(this->event_binary_sensors_[event], state);
222#endif
223}
224
227 if (now - this->last_poll_ms_ < POLL_INTERVAL_MS) {
228 return;
229 }
230 this->last_poll_ms_ = now;
231
232 // SIXD_SRC and ALL_INT_SRC are adjacent, so one read captures both before any latch clears
233 uint8_t regs[2];
234 if (!this->status_comm_result(this->read_bytes(static_cast<uint8_t>(RegisterMap::SIXD_SRC), regs, sizeof(regs))))
235 return;
236 RegSixdSrc sixd;
237 sixd.raw = regs[0];
239 src.raw = regs[1];
240
241 this->handle_event_(EVENT_TAP, src.single_tap, now, this->tap_callback_);
242 this->handle_event_(EVENT_DOUBLE_TAP, src.double_tap, now, this->double_tap_callback_);
243 this->handle_event_(EVENT_FREEFALL, src.ff_ia, now, this->freefall_callback_);
244 this->handle_event_(EVENT_ACTIVE, src.wu_ia, now, this->active_callback_);
245
246 if (sixd.d6d_ia) {
247 this->orientation_callback_.call();
248#ifdef USE_TEXT_SENSOR
249 this->publish_orientation_(sixd);
250#endif
251 }
252}
253
255 float x{}, y{}, z{};
256 if (!this->status_comm_result(this->read_acceleration_data_(x, y, z)))
257 return;
258
259 ESP_LOGV(TAG, "Acceleration: {x = %+1.3f m/s², y = %+1.3f m/s², z = %+1.3f m/s²}", x, y, z);
260
261#ifdef USE_SENSOR
262 PUBLISH_STATE(this->acceleration_x_sensor_, x);
263 PUBLISH_STATE(this->acceleration_y_sensor_, y);
264 PUBLISH_STATE(this->acceleration_z_sensor_, z);
265#endif
266}
267
268void LIS2DW12Component::set_offset(float offset_x, float offset_y, float offset_z) {
269 this->offset_x_ = offset_x;
270 this->offset_y_ = offset_y;
271 this->offset_z_ = offset_z;
272}
273
274void LIS2DW12Component::set_transform(bool mirror_x, bool mirror_y, bool mirror_z, bool swap_xy) {
275 this->mirror_x_ = mirror_x;
276 this->mirror_y_ = mirror_y;
277 this->mirror_z_ = mirror_z;
278 this->swap_xy_ = swap_xy;
279}
280
281} // namespace esphome::lis2dw12
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
Definition component.h:236
void disable_loop()
Disable this component's loop.
bool read_byte(uint8_t a_register, uint8_t *data)
Definition lis2dw12.h:126
LazyCallbackManager< void()> orientation_callback_
Definition lis2dw12.h:183
uint32_t last_event_ms_[EVENT_COUNT]
Definition lis2dw12.h:174
void publish_orientation_(RegSixdSrc sixd)
Definition lis2dw12.cpp:189
LazyCallbackManager< void()> double_tap_callback_
Definition lis2dw12.h:180
binary_sensor::BinarySensor * event_binary_sensors_[EVENT_COUNT]
Definition lis2dw12.h:177
bool write_reg_(RegisterMap reg, uint8_t value)
Definition lis2dw12.h:164
virtual bool read_bytes(uint8_t a_register, uint8_t *data, size_t len)=0
void set_offset(float offset_x, float offset_y, float offset_z)
Definition lis2dw12.cpp:268
void handle_event_(Event event, bool active, uint32_t now, LazyCallbackManager< void()> &callback)
Definition lis2dw12.cpp:199
LazyCallbackManager< void()> tap_callback_
Definition lis2dw12.h:179
LazyCallbackManager< void()> freefall_callback_
Definition lis2dw12.h:181
LazyCallbackManager< void()> active_callback_
Definition lis2dw12.h:182
void set_transform(bool mirror_x, bool mirror_y, bool mirror_z, bool swap_xy)
Definition lis2dw12.cpp:274
bool read_acceleration_data_(float &x, float &y, float &z)
Definition lis2dw12.cpp:153
float position
Definition cover.h:0
bool state
Definition fan.h:2
bool z
Definition msa3xx.h:1
ESPHOME_LOG_TAG(TAG, "lis2dw12")
PROGMEM_STRING_TABLE(PowerModeStrings, "High Performance", "Low Power 1 (12-bit)", "Low Power 2", "Low Power 3", "Low Power 4", "Unknown")
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1268
const void * src
Definition hal.h:68
void HOT delay(uint32_t ms)
Definition hal.cpp:78
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6