ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
vl6180x.cpp
Go to the documentation of this file.
1#include "vl6180x.h"
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
4
5namespace esphome::vl6180x {
6
7ESPHOME_LOG_TAG(TAG, "vl6180x");
8
9static constexpr uint32_t MEASUREMENT_ID = 0;
10
11static constexpr uint8_t DEFAULT_ADDRESS = 0x29;
12static constexpr uint8_t MODEL_ID = 0xB4;
13
14static constexpr uint16_t REG_IDENTIFICATION_MODEL_ID = 0x000;
15static constexpr uint16_t REG_SYSTEM_INTERRUPT_CLEAR = 0x015;
16static constexpr uint16_t REG_SYSTEM_FRESH_OUT_OF_RESET = 0x016;
17static constexpr uint16_t REG_SYSRANGE_START = 0x018;
18static constexpr uint16_t REG_SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x021;
19static constexpr uint16_t REG_SYSRANGE_PART_TO_PART_OFFSET = 0x024;
20static constexpr uint16_t REG_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D;
21static constexpr uint16_t REG_SYSALS_START = 0x038;
22static constexpr uint16_t REG_SYSALS_ANALOGUE_GAIN = 0x03F;
23static constexpr uint16_t REG_SYSALS_INTEGRATION_PERIOD = 0x040;
24static constexpr uint16_t REG_RESULT_RANGE_STATUS = 0x04D;
25static constexpr uint16_t REG_RESULT_ALS_STATUS = 0x04E;
26static constexpr uint16_t REG_RESULT_RANGE_VAL = 0x062;
27static constexpr uint16_t REG_RANGE_SCALING = 0x096;
28static constexpr uint16_t REG_I2C_DEVICE_ADDRESS = 0x212;
29
30// RESULT_INTERRUPT_STATUS_GPIO: a new range sample in bits 2:0, a new ALS sample in bits 5:3
31static constexpr uint8_t RANGE_SAMPLE_READY = 0x04;
32static constexpr uint8_t ALS_SAMPLE_READY = 0x04 << 3;
33
34// Range conversion is at most the 50 ms convergence time set below plus readout
35static constexpr uint32_t RANGE_TIME_MS = 70;
36static constexpr uint32_t ALS_READOUT_MARGIN_MS = 400;
37
38// Indexed by the range scaler, 1x to 3x (AN4545)
39static constexpr uint16_t RANGE_SCALING_VALUES[] PROGMEM = {0, 253, 127, 84};
40
41struct RegValue {
42 uint16_t reg;
43 uint8_t value;
44};
45
46// Private settings written once after a power-on reset (AN4545 table 7)
47static constexpr RegValue MANDATORY_SETTINGS[] PROGMEM = {
48 {0x0207, 0x01},
49 {0x0208, 0x01},
50 {0x0096, 0x00},
51 {0x0097, 0xFD},
52 {0x00E3, 0x00},
53 {0x00E4, 0x04},
54 {0x00E5, 0x02},
55 {0x00E6, 0x01},
56 {0x00E7, 0x03},
57 {0x00F5, 0x02},
58 {0x00D9, 0x05},
59 {0x00DB, 0xCE},
60 {0x00DC, 0x03},
61 {0x00DD, 0xF8},
62 {0x009F, 0x00},
63 {0x00A3, 0x3C},
64 {0x00B7, 0x00},
65 {0x00BB, 0x3C},
66 {0x00B2, 0x09},
67 {0x00CA, 0x09},
68 {0x0198, 0x01},
69 {0x01B0, 0x17},
70 {0x01AD, 0x00},
71 {0x00FF, 0x05},
72 {0x0100, 0x05},
73 {0x0199, 0x05},
74 {0x01A6, 0x1B},
75 {0x01AC, 0x3E},
76 {0x01A7, 0x1F},
77 {0x0030, 0x00},
78 {REG_SYSTEM_FRESH_OUT_OF_RESET, 0x00},
79};
80
81// Recommended settings (AN4545 section 9), with GPIO1 left floating and new-sample interrupts flagged
82static constexpr RegValue DEFAULT_SETTINGS[] PROGMEM = {
83 {0x010A, 0x30}, // averaging sample period
84 {0x0031, 0xFF}, // repeat temperature calibration every 255 range measurements
85 {0x002E, 0x01}, // run the first temperature calibration now
86 {0x001C, 0x32}, // 50 ms maximum convergence time
87 {0x0011, 0x20}, // GPIO1 off
88 {0x0014, RANGE_SAMPLE_READY | ALS_SAMPLE_READY},
89 {REG_SYSTEM_INTERRUPT_CLEAR, 0x07},
90};
91
92template<size_t N> static bool write_settings(i2c::I2CDevice *device, const RegValue (&table)[N]) {
93 for (const auto &entry : table) {
94 RegValue setting;
95 progmem_memcpy(&setting, &entry, sizeof(setting));
96 if (!device->write_byte_reg16(setting.reg, setting.value))
97 return false;
98 }
99 return true;
100}
101
102#ifdef VL6180X_ENABLE_PIN_COUNT
104#endif
105
107#ifdef VL6180X_ENABLE_PIN_COUNT
108 // Every sensor boots at 0x29, so all are held in reset and then released one at a time
109 for (auto *pin : enable_pins) {
110 setup_output_pin(pin, false);
111 }
112 enable_pins.clear();
113 if (this->enable_pin_ != nullptr) {
114 this->enable_pin_->digital_write(true);
115 delay(10);
116 }
117#endif
118 const uint8_t address = this->address_;
119 this->set_i2c_address(DEFAULT_ADDRESS);
120 uint8_t model_id = 0;
121 const bool read_ok = this->read_byte_reg16(REG_IDENTIFICATION_MODEL_ID, &model_id);
122 const bool ok = read_ok && model_id == MODEL_ID && this->init_() &&
123 (address == DEFAULT_ADDRESS || this->write_byte_reg16(REG_I2C_DEVICE_ADDRESS, address));
124 this->set_i2c_address(address);
125 if (ok)
126 return;
127#ifdef VL6180X_ENABLE_PIN_COUNT
128 // A sensor left at 0x29 would answer for the next one released
129 if (this->enable_pin_ != nullptr)
130 this->enable_pin_->digital_write(false);
131#endif
132 if (read_ok && model_id != MODEL_ID) {
133 ESP_LOGE(TAG, "Wrong model ID 0x%02X", model_id);
134 this->mark_failed(LOG_STR("Wrong model ID"));
135 return;
136 }
137 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
138}
139
141 uint8_t fresh;
142 uint8_t offset;
143 if (!this->read_byte_reg16(REG_SYSTEM_FRESH_OUT_OF_RESET, &fresh) ||
144 !this->read_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, &offset))
145 return false;
146 // The factory offset is for 1x; a sensor that kept power through an MCU reboot already holds it divided by the
147 // scaler from the last setup
148 int16_t part_offset = static_cast<int8_t>(offset);
149 if (fresh & 0x01) {
150 if (!write_settings(this, MANDATORY_SETTINGS))
151 return false;
152 } else {
153 uint8_t scaling[2];
154 if (this->read_register16(REG_RANGE_SCALING, scaling, 2) != i2c::ERROR_OK)
155 return false;
156 const uint16_t value = encode_uint16(scaling[0], scaling[1]);
157 for (uint8_t scaler = 2; scaler <= 3; scaler++) {
158 if (value == progmem_read_uint16(&RANGE_SCALING_VALUES[scaler]))
159 part_offset *= scaler;
160 }
161 }
162
163 uint8_t period[2];
164 put_be16(period, this->als_integration_time_ms_ - 1);
165 uint8_t scaling[2];
166 put_be16(scaling, progmem_read_uint16(&RANGE_SCALING_VALUES[this->scaler_]));
167 return write_settings(this, DEFAULT_SETTINGS) &&
168 this->write_byte_reg16(REG_SYSALS_ANALOGUE_GAIN, 0x40 | this->als_gain_code_) &&
169 this->write_register16(REG_SYSALS_INTEGRATION_PERIOD, period, 2) == i2c::ERROR_OK &&
170 this->write_register16(REG_RANGE_SCALING, scaling, 2) == i2c::ERROR_OK &&
171 this->write_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, static_cast<uint8_t>(part_offset / this->scaler_)) &&
172 this->write_byte_reg16(REG_SYSRANGE_CROSSTALK_VALID_HEIGHT, 20 / this->scaler_) &&
173 // SNR check, plus the early convergence estimate only at 1x, as in ST's API
174 this->write_byte_reg16(REG_SYSRANGE_RANGE_CHECK_ENABLES, 0x10 | (this->scaler_ == 1 ? 0x01 : 0x00));
175}
176
177void VL6180XComponent::update() {
178 // A measurement still running means the update interval is shorter than one cycle
179 if (this->measuring_)
180 return;
181 this->measuring_ = true;
182 if (this->distance_sensor_ != nullptr) {
183 this->start_range_();
184 } else {
185 this->start_als_();
186 }
187}
188
190 if (!this->status_comm_check(this->write_byte_reg16(REG_SYSRANGE_START, 0x01))) {
191 this->measuring_ = false;
192 return;
193 }
194 this->set_timeout(MEASUREMENT_ID, RANGE_TIME_MS, [this]() { this->read_range_(); });
195}
196
198 uint8_t status[3]; // range status, ALS status, interrupt status
199 uint8_t raw;
200 if (!this->status_comm_check(this->read_register16(REG_RESULT_RANGE_STATUS, status, 3) == i2c::ERROR_OK) ||
201 !this->status_comm_check((status[2] & 0x07) == RANGE_SAMPLE_READY) ||
202 !this->status_comm_check(this->read_byte_reg16(REG_RESULT_RANGE_VAL, &raw) &&
203 this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07))) {
204 this->measuring_ = false;
205 return;
206 }
207 const uint8_t error = status[0] >> 4;
208 // Codes 1 to 5 are self-test faults (VCSEL or PLL); a fault keeps the warning until a whole cycle works
209 if (error >= 1 && error <= 5) {
210 ESP_LOGW(TAG, "Range self-test fault %u", error);
211 PUBLISH_STATE(this->distance_sensor_, NAN);
212 this->status_set_warning();
213 this->measuring_ = false;
214 return;
215 }
216 // Other codes mean no target or out of range
217 if (error != 0) {
218 ESP_LOGV(TAG, "Range error code %u", error);
219 PUBLISH_STATE(this->distance_sensor_, NAN);
220 } else {
221 PUBLISH_STATE(this->distance_sensor_, static_cast<float>(raw * this->scaler_));
222 }
223 // With illuminance configured, read_als_() clears the warning once the whole cycle has worked
224 if (this->illuminance_sensor_ != nullptr) {
225 this->start_als_();
226 } else {
227 this->measuring_ = false;
228 this->status_clear_warning();
229 }
230}
231
233 if (!this->status_comm_check(this->write_byte_reg16(REG_SYSALS_START, 0x01))) {
234 this->measuring_ = false;
235 return;
236 }
237 this->set_timeout(MEASUREMENT_ID, this->als_integration_time_ms_ + ALS_READOUT_MARGIN_MS,
238 [this]() { this->read_als_(); });
239}
240
242 this->measuring_ = false;
243 uint8_t result[4]; // ALS status, interrupt status, ALS value
244 if (!this->status_comm_check(this->read_register16(REG_RESULT_ALS_STATUS, result, 4) == i2c::ERROR_OK) ||
245 !this->status_comm_check((result[1] & 0x38) == ALS_SAMPLE_READY) ||
246 !this->status_comm_result(this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07)))
247 return;
248 // An overflow in bright light is a reading, not a fault
249 if (result[0] >> 4) {
250 ESP_LOGV(TAG, "ALS error code %u", result[0] >> 4);
251 PUBLISH_STATE(this->illuminance_sensor_, NAN);
252 return;
253 }
254 PUBLISH_STATE(this->illuminance_sensor_, encode_uint16(result[2], result[3]) * this->lux_per_count_);
255}
256
257void VL6180XComponent::dump_config() {
258 ESP_LOGCONFIG(TAG, "VL6180X:");
259 LOG_I2C_DEVICE(this);
260 LOG_PIN(" Enable Pin: ", this->enable_pin_);
261 LOG_UPDATE_INTERVAL(this);
262 LOG_SENSOR(" ", "Distance", this->distance_sensor_);
263 LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_);
264}
265
266} // namespace esphome::vl6180x
uint8_t raw[35]
Definition bl0939.h:0
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
bool status_comm_check(bool ok)
Sets the warning ("Communication failed") when not ok but never clears it; returns ok.
Definition component.h:309
void status_clear_warning()
Definition component.h:318
void set_timeout(const char *name, uint32_t timeout, SchedulerCallback &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
virtual void digital_write(bool value)=0
ErrorCode write_register16(uint16_t a_register, const uint8_t *data, size_t len) const
write an array of bytes to a specific register in the I²C device
Definition i2c.cpp:83
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
uint8_t address_
store the address of the device on the bus
Definition i2c.h:340
bool read_byte_reg16(uint16_t a_register, uint8_t *data)
Read one byte from a register with a 16-bit register address.
Definition i2c.h:325
ErrorCode read_register16(uint16_t a_register, uint8_t *data, size_t len)
reads an array of bytes from a specific register in the I²C device
Definition i2c.cpp:62
void set_i2c_address(uint8_t address)
We store the address of the device on the bus.
Definition i2c.h:151
static SlotList< GPIOPin *, VL6180X_ENABLE_PIN_COUNT > enable_pins
Definition vl6180x.h:44
const uint8_t STORE_YAML_DATA[] PROGMEM
The zstd YAML envelope generated by store_yaml, STORE_YAML_DATA_SIZE bytes in flash.
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
ESPHOME_LOG_TAG(TAG, "vl6180x")
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
uint32_t value
Definition hal.cpp:59
std::conditional_t< N==0, EmptyList< T >, StaticVector< T, N > > SlotList
StaticVector<T, N>, or EmptyList<T> when N is 0.
Definition helpers.h:444
uint16_t progmem_read_uint16(const uint16_t *addr)
Definition hal.h:53
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
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1227
void HOT delay(uint32_t ms)
Definition hal.cpp:78
static void uint32_t
esp_err_t result