ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
vl53l4cx.cpp
Go to the documentation of this file.
1#include "vl53l4cx.h"
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
7
8#include <algorithm>
9#include <new>
10
12
13ESPHOME_LOG_TAG(TAG, "vl53l4cx");
14
15static constexpr uint8_t DEFAULT_ADDRESS = 0x29;
16static constexpr uint16_t SENSOR_ID = 0xEBAA;
17// ST's first frames after a start are unreliable
18static constexpr uint8_t SETTLE_FRAMES = 5;
19static constexpr uint32_t RESET_INTERVAL_ID = 0;
20static constexpr uint32_t RESET_INTERVAL_MS = 5000;
21// Write 0, wait, write 1: reboots the sensor like a power-up
22static constexpr uint16_t SOFT_RESET_REGISTER = 0x0000;
23static constexpr uint32_t SOFT_RESET_US = 100;
24
25PROGMEM_STRING_TABLE(TargetStrings, "nearest", "farthest", "strongest");
26PROGMEM_STRING_TABLE(DistanceModeStrings, "medium", "long");
27
28#ifdef USE_VL53L4CX_ENABLE_PIN
29VL53L4CXSensor *VL53L4CXSensor::first_sensor = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
30
33 VL53L4CXSensor::first_sensor = this;
34}
35#endif
36
37static constexpr size_t REGISTER_ADDRESS_SIZE = 2;
38// Arduino Wire buffers 128 bytes on ESP8266 and 64 on LibreTiny, including the register address; the driver
39// writes up to 135, so longer transfers are split (the register address auto-increments)
40#if defined(USE_ESP8266)
41static constexpr uint16_t MAX_TRANSFER = 128 - REGISTER_ADDRESS_SIZE;
42#elif defined(USE_LIBRETINY)
43static constexpr uint16_t MAX_TRANSFER = 64 - REGISTER_ADDRESS_SIZE;
44#else
45static constexpr uint16_t MAX_TRANSFER = UINT16_MAX;
46#endif
47
49template<typename F> static bool transfer_in_parts(uint16_t reg, uint16_t len, F &&transfer) {
50 uint16_t done = 0;
51 do {
52 const uint16_t part = std::min<uint16_t>(len - done, MAX_TRANSFER);
53 uint8_t prefix[REGISTER_ADDRESS_SIZE];
54 put_be16(prefix, reg + done);
55 if (!transfer(prefix, done, part))
56 return false;
57 done += part;
58 } while (done < len);
59 return true;
60}
61
62bool VL53L4CXSensor::write_registers(uint8_t address, uint16_t reg, const uint8_t *data, uint16_t len) {
63 return transfer_in_parts(reg, len, [&](const uint8_t *prefix, uint16_t offset, uint16_t part) {
64 return this->bus_->write_prefixed(address, prefix, REGISTER_ADDRESS_SIZE, data + offset, part) == i2c::ERROR_OK;
65 });
66}
67
68bool VL53L4CXSensor::read_registers(uint8_t address, uint16_t reg, uint8_t *data, uint16_t len) {
69 return transfer_in_parts(reg, len, [&](const uint8_t *prefix, uint16_t offset, uint16_t part) {
70 return this->bus_->write_readv(address, prefix, REGISTER_ADDRESS_SIZE, data + offset, part) == i2c::ERROR_OK;
71 });
72}
73
77
79#ifdef USE_VL53L4CX_ENABLE_PIN
80 if (this->enable_pin_ != nullptr)
81 this->enable_pin_->digital_write(false);
82#endif
83}
84
85void VL53L4CXSensor::reset_failed_(const LogString *reason) {
86 ESP_LOGV(TAG, "Reset failed: %s", LOG_STR_ARG(reason));
87 if (this->failures_ == MAX_FAILURES) {
88 this->failures_++;
90 this->status_set_warning(reason);
91 }
92 this->hold_in_reset_();
93}
94
96#ifdef USE_VL53L4CX_ENABLE_PIN
97 // Hold every sensor in reset so each comes up at 0x29 only in its own setup()
98 for (auto *other = VL53L4CXSensor::first_sensor; other != nullptr; other = other->next_) {
99 setup_output_pin(other->enable_pin_, false);
100 }
102 if (this->enable_pin_ != nullptr) {
103 this->enable_pin_->digital_write(true);
104 }
105#endif
106#ifdef USE_VL53L4CX_INTERRUPT_PIN
107 if (this->interrupt_pin_ != nullptr) {
108 this->interrupt_pin_->setup();
110 }
111#endif
112
113 if (const LogString *error = this->init_and_start_(true)) {
114 this->hold_in_reset_();
115 this->mark_failed(error);
116 }
117}
118
119const LogString *VL53L4CXSensor::init_and_start_(bool at_boot) {
120 if (this->driver_.VL53L4CX_WaitDeviceBooted() != VL53L4CX_ERROR_NONE)
121 return LOG_STR("Boot timeout");
122 uint16_t sensor_id;
123 if (this->driver_.VL53L4CX_GetSensorId(&sensor_id) != VL53L4CX_ERROR_NONE)
124 return LOG_STR(ESP_LOG_MSG_COMM_FAIL);
125 if (sensor_id != SENSOR_ID) {
126 if (at_boot) {
127 ESP_LOGE(TAG, "Wrong sensor ID 0x%04X", sensor_id);
128 } else {
129 ESP_LOGV(TAG, "Wrong sensor ID 0x%04X", sensor_id);
130 }
131 return LOG_STR("Wrong sensor ID");
132 }
133 // The driver takes the 8-bit form of the address
134 if (this->address_ != DEFAULT_ADDRESS &&
135 this->driver_.VL53L4CX_SetDeviceAddress(this->address_ << 1) != VL53L4CX_ERROR_NONE)
136 return LOG_STR("Setting address failed");
137 if (this->driver_.VL53L4CX_DataInit() != VL53L4CX_ERROR_NONE)
138 return LOG_STR("Initialization failed");
139 if (this->driver_.VL53L4CX_SetDistanceMode(this->distance_mode_) != VL53L4CX_ERROR_NONE ||
140 this->driver_.VL53L4CX_SetMeasurementTimingBudgetMicroSeconds(this->budget_ms_ * 1000UL) != VL53L4CX_ERROR_NONE)
141 return LOG_STR("Configuration failed");
142#ifdef USE_VL53L4CX_INTERRUPT_PIN
143 this->ready_edge_ = false;
144#endif
145 if (this->driver_.VL53L4CX_StartMeasurement() != VL53L4CX_ERROR_NONE)
146 return LOG_STR("Starting measurements failed");
148 this->measuring_ = true;
149 this->settle_frames_ = SETTLE_FRAMES;
150 return nullptr;
151}
152
154 // Both resets leave the sensor unconfigured at 0x29, so start over with a fresh driver
155#ifdef USE_VL53L4CX_ENABLE_PIN
156 if (this->enable_pin_ != nullptr) {
157 pulse_reset(this->enable_pin_, {.low_ms = 2});
158 } else
159#endif
160 {
161 // Always release; a sensor that was not reset must not run DataInit again
162 const bool held = this->write_byte_reg16(SOFT_RESET_REGISTER, 0);
163 delayMicroseconds(SOFT_RESET_US);
164 if (!this->write_byte_reg16(SOFT_RESET_REGISTER, 1) || !held) {
165 this->reset_failed_(LOG_STR("Software reset not written"));
166 return;
167 }
168 }
169 this->driver_.~VL53L4CX();
170 new (&this->driver_) VL53L4CX(this);
171 if (const LogString *error = this->init_and_start_(false)) {
172 this->reset_failed_(error);
173 return;
174 }
175 this->cancel_interval(RESET_INTERVAL_ID);
176 this->failures_ = 0;
177 this->enable_loop();
178}
179
182 // The driver ranges again only once the interrupt is cleared
183#ifdef USE_VL53L4CX_INTERRUPT_PIN
184 this->ready_edge_ = false;
185#endif
186 const VL53L4CX_Error error = this->driver_.VL53L4CX_ClearInterruptAndStartMeasurement();
187 this->measuring_ = error == VL53L4CX_ERROR_NONE;
188 if (!this->measuring_)
189 this->measurement_failed_(LOG_STR("Starting a measurement failed"), error);
190 return this->measuring_;
191}
192
193void VL53L4CXSensor::measurement_failed_(const LogString *message, VL53L4CX_Error error) {
194 ESP_LOGV(TAG, "%s: error %d", LOG_STR_ARG(message), error);
195 this->status_set_warning(message);
196 if (++this->failures_ == MAX_FAILURES) {
197 this->publish_state(NAN);
198 this->set_interval(RESET_INTERVAL_ID, RESET_INTERVAL_MS, [this]() { this->reset_sensor_(); });
199 }
200}
201
203 if (this->resetting_())
204 return;
205 if (this->measuring_) {
206 ESP_LOGV(TAG, "Measurement still running");
207 return;
208 }
209 if (this->start_measurement_())
210 this->enable_loop();
211}
212
215 if (!this->measuring_) {
216 if (this->get_update_interval() != SCHEDULER_DONT_RUN || this->resetting_()) {
217 this->disable_loop();
218 } else if (elapsed > this->timeout_ms_()) {
219 this->start_measurement_();
220 }
221 return;
222 }
223 const bool settling = this->settle_frames_ > 0;
224 uint8_t ready = 0;
225 VL53L4CX_Error error = VL53L4CX_ERROR_NONE;
226#ifdef USE_VL53L4CX_INTERRUPT_PIN
227 // Edge and low level: a stuck-low pin makes no edge, and a stale edge leaves the pin high after the start
228 if (this->interrupt_pin_ != nullptr) {
229 ready = this->ready_edge_ && !this->interrupt_pin_->digital_read();
230 } else
231#endif
232 {
233 if (elapsed < this->budget_ms_)
234 return;
235 error = this->driver_.VL53L4CX_GetMeasurementDataReady(&ready);
236 }
237 // On a failed poll the driver can report ready from an unread byte
238 if (error == VL53L4CX_ERROR_NONE && !ready && elapsed <= this->timeout_ms_())
239 return;
240 this->measuring_ = false;
241 if (error != VL53L4CX_ERROR_NONE) {
242 this->measurement_failed_(LOG_STR("Polling data ready failed"), error);
243 } else if (ready) {
244 this->publish_result_();
245 } else {
246 this->measurement_failed_(LOG_STR("Measurement timed out"), VL53L4CX_ERROR_TIME_OUT);
247 }
248 // An on_value automation may have called update() already
249 if (this->measuring_)
250 return;
251 if ((this->get_update_interval() != SCHEDULER_DONT_RUN && !settling) || this->resetting_()) {
252 this->disable_loop();
253 return;
254 }
255 this->start_measurement_();
256}
257
258static bool is_valid_range(uint8_t status) {
259 return status == VL53L4CX_RANGESTATUS_RANGE_VALID || status == VL53L4CX_RANGESTATUS_RANGE_VALID_MIN_RANGE_CLIPPED ||
260 status == VL53L4CX_RANGESTATUS_RANGE_VALID_NO_WRAP_CHECK_FAIL ||
261 status == VL53L4CX_RANGESTATUS_RANGE_VALID_MERGED_PULSE;
262}
263
264int32_t select_distance_mm(const VL53L4CX_MultiRangingData_t &data, Target target, uint16_t min_distance_mm,
265 int16_t offset_mm) {
266 int32_t best_mm = -1;
267 FixPoint1616_t best_signal = 0;
268 for (uint8_t i = 0; i < data.NumberOfObjectsFound && i < VL53L4CX_MAX_RANGE_RESULTS; i++) {
269 const VL53L4CX_TargetRangeData_t &range = data.RangeData[i];
270 if (!is_valid_range(range.RangeStatus))
271 continue;
272 const int32_t mm = range.RangeMilliMeter + offset_mm;
273 if (mm < min_distance_mm)
274 continue;
275 const bool better = best_mm < 0 || (target == TARGET_NEAREST && mm < best_mm) ||
276 (target == TARGET_FARTHEST && mm > best_mm) ||
277 (target == TARGET_STRONGEST && range.SignalRateRtnMegaCps > best_signal);
278 if (better) {
279 best_mm = mm;
280 best_signal = range.SignalRateRtnMegaCps;
281 }
282 }
283 return best_mm;
284}
285
287 VL53L4CX_MultiRangingData_t data;
288 const VL53L4CX_Error error = this->driver_.VL53L4CX_GetMultiRangingData(&data);
289 if (error != VL53L4CX_ERROR_NONE) {
290 this->measurement_failed_(LOG_STR("Reading the measurement failed"), error);
291 return;
292 }
293 this->failures_ = 0;
294 this->status_clear_warning();
295 if (this->settle_frames_ > 0) {
296 this->settle_frames_--;
297 return;
298 }
299 const int32_t best_mm = select_distance_mm(data, this->target_, this->min_distance_mm_, this->offset_mm_);
300 ESP_LOGV(TAG, "%u targets, reporting %" PRId32 " mm", data.NumberOfObjectsFound, best_mm);
301 this->publish_state(best_mm < 0 ? NAN : best_mm / 1000.0f);
302}
303
305 LOG_SENSOR("", "VL53L4CX", this);
306 LOG_UPDATE_INTERVAL(this);
307 LOG_I2C_DEVICE(this);
308#ifdef USE_VL53L4CX_ENABLE_PIN
309 LOG_PIN(" Enable Pin: ", this->enable_pin_);
310#endif
311#ifdef USE_VL53L4CX_INTERRUPT_PIN
312 LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
313#endif
314 ESP_LOGCONFIG(TAG,
315 " Distance Mode: %s\n"
316 " Timing Budget: %u ms\n"
317 " Target: %s\n"
318 " Minimum Distance: %u mm\n"
319 " Offset: %d mm",
320 LOG_STR_ARG(DistanceModeStrings::get_log_str(this->distance_mode_ - VL53L4CX_DISTANCEMODE_MEDIUM)),
321 this->budget_ms_, LOG_STR_ARG(TargetStrings::get_log_str(this->target_)), this->min_distance_mm_,
322 this->offset_mm_);
323}
324
325} // namespace esphome::vl53l4cx
uint8_t status
Definition bl0942.h:8
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 cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
void enable_loop()
Enable this component's loop.
Definition component.h:262
void disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:318
void set_interval(const char *name, uint32_t interval, SchedulerCallback &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
virtual void digital_write(bool value)=0
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
void attach_interrupt(void(*func)(T *), T *arg, gpio::InterruptType type) const
Definition gpio.h:32
virtual ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer, size_t read_count)=0
This virtual method writes bytes to an I2CBus from an array, then reads bytes into an array of ReadBu...
virtual ErrorCode write_prefixed(uint8_t address, const uint8_t *prefix, size_t prefix_len, const uint8_t *data, size_t len)
Writes prefix then data in one transaction, as for a register address followed by its data.
Definition i2c.cpp:67
bool write_byte_reg16(uint16_t a_register, uint8_t data) const
Write one byte to a register with a 16-bit register address.
Definition i2c.h:330
I2CBus * bus_
pointer to I2CBus instance
Definition i2c.h:338
uint8_t address_
store the address of the device on the bus
Definition i2c.h:340
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:164
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
VL53L4CX multi-target time-of-flight sensor, driven by ST's driver (esphome-libs/VL53L4CX).
Definition vl53l4cx.h:24
void hold_in_reset_()
Holds the sensor in reset when it has an enable pin.
Definition vl53l4cx.cpp:78
bool write_registers(uint8_t address, uint16_t reg, const uint8_t *data, uint16_t len) override
Definition vl53l4cx.cpp:62
static VL53L4CXSensor * first_sensor
Definition vl53l4cx.h:77
static constexpr uint8_t MAX_FAILURES
Definition vl53l4cx.h:54
InternalGPIOPin * interrupt_pin_
Definition vl53l4cx.h:86
const LogString * init_and_start_(bool at_boot)
Boots, addresses and starts the sensor; returns the failure reason or nullptr.
Definition vl53l4cx.cpp:119
static void IRAM_ATTR ready_isr(VL53L4CXSensor *sensor)
Definition vl53l4cx.h:58
void measurement_failed_(const LogString *message, VL53L4CX_Error error)
Definition vl53l4cx.cpp:193
bool read_registers(uint8_t address, uint16_t reg, uint8_t *data, uint16_t len) override
Definition vl53l4cx.cpp:68
void delay_ms(uint32_t ms) override
Definition vl53l4cx.cpp:75
void reset_failed_(const LogString *reason)
Definition vl53l4cx.cpp:85
void delay_us(uint32_t us) override
Definition vl53l4cx.cpp:76
const LogString * message
Definition component.cpp:35
Range range
Definition msa3xx.h:0
@ INTERRUPT_FALLING_EDGE
Definition gpio_pin.h:53
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
PROGMEM_STRING_TABLE(TargetStrings, "nearest", "farthest", "strongest")
ESPHOME_LOG_TAG(TAG, "vl53l4cx")
int32_t select_distance_mm(const VL53L4CX_MultiRangingData_t &data, Target target, uint16_t min_distance_mm, int16_t offset_mm)
Distance in mm of the chosen valid target at or beyond min_distance_mm, or -1.
Definition vl53l4cx.cpp:264
const void size_t len
Definition hal.h:68
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1296
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
void HOT delay(uint32_t ms)
Definition hal.cpp:78
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
ESPHOME_ALWAYS_INLINE void pulse_reset(GPIOPin *pin, ResetPulse pulse)
Set up an active-low reset pin and drive it through pulse.
Definition gpio_pin.h:214
constexpr uint32_t SCHEDULER_DONT_RUN
Definition component.h:64
static void uint32_t
SemaphoreHandle_t done