ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
ltr501.cpp
Go to the documentation of this file.
1#include "ltr501.h"
4#include "esphome/core/log.h"
5#include <limits>
6
8
9namespace esphome::ltr501 {
10
11ESPHOME_LOG_TAG(TAG, "ltr501");
12
13static const uint8_t MAX_TRIES = 5;
14static const uint8_t MAX_SENSITIVITY_ADJUSTMENTS = 10;
15
16struct GainTimePair {
17 AlsGain501 gain;
19};
20
21bool operator==(const GainTimePair &lhs, const GainTimePair &rhs) {
22 return lhs.gain == rhs.gain && lhs.time == rhs.time;
23}
24
25bool operator!=(const GainTimePair &lhs, const GainTimePair &rhs) {
26 return lhs.gain != rhs.gain || lhs.time != rhs.time;
27}
28
29template<typename T, size_t size> T get_next(const T (&array)[size], const T val) {
30 size_t i = 0;
31 size_t idx = std::numeric_limits<size_t>::max();
32 while (idx == std::numeric_limits<size_t>::max() && i < size) {
33 if (array[i] == val) {
34 idx = i;
35 break;
36 }
37 i++;
38 }
39 if (idx == std::numeric_limits<size_t>::max() || i + 1 >= size)
40 return val;
41 return array[i + 1];
42}
43
44template<typename T, size_t size> T get_prev(const T (&array)[size], const T val) {
45 size_t i = size - 1;
46 size_t idx = std::numeric_limits<size_t>::max();
47 while (idx == std::numeric_limits<size_t>::max() && i > 0) {
48 if (array[i] == val) {
49 idx = i;
50 break;
51 }
52 i--;
53 }
54 if (idx == std::numeric_limits<size_t>::max() || i == 0)
55 return val;
56 return array[i - 1];
57}
58
59static uint16_t get_itime_ms(IntegrationTime501 time) {
60 static const uint16_t ALS_INT_TIME[4] = {100, 50, 200, 400};
61 return ALS_INT_TIME[time & 0b11];
62}
63
64static uint16_t get_meas_time_ms(MeasurementRepeatRate rate) {
65 static const uint16_t ALS_MEAS_RATE[8] = {50, 100, 200, 500, 1000, 2000, 2000, 2000};
66 return ALS_MEAS_RATE[rate & 0b111];
67}
68
69static float get_gain_coeff(AlsGain501 gain) { return gain == AlsGain501::GAIN_1 ? 1.0f : 150.0f; }
70
71static float get_ps_gain_coeff(PsGain501 gain) {
72 static const float PS_GAIN[4] = {1, 4, 8, 16};
73 return PS_GAIN[gain & 0b11];
74}
75
77 // As per datasheet we need to wait at least 100ms after power on to get ALS chip responsive
78 this->set_timeout(100, [this]() { this->state_ = State::DELAYED_SETUP; });
79}
80
82 auto get_device_type = [](LtrType typ) {
83 switch (typ) {
85 return "ALS only";
87 return "PS only";
89 return "Als + PS";
90 default:
91 return "Unknown";
92 }
93 };
94
95 LOG_I2C_DEVICE(this);
96 ESP_LOGCONFIG(TAG,
97 " Device type: %s\n"
98 " Automatic mode: %s\n"
99 " Gain: %.0fx\n"
100 " Integration time: %d ms\n"
101 " Measurement repeat rate: %d ms\n"
102 " Glass attenuation factor: %f\n"
103 " Proximity gain: %.0fx\n"
104 " Proximity cooldown time: %d s\n"
105 " Proximity high threshold: %d\n"
106 " Proximity low threshold: %d",
107 get_device_type(this->ltr_type_), ONOFF(this->automatic_mode_enabled_), get_gain_coeff(this->gain_),
108 get_itime_ms(this->integration_time_), get_meas_time_ms(this->repeat_rate_),
109 this->glass_attenuation_factor_, get_ps_gain_coeff(this->ps_gain_), this->ps_cooldown_time_s_,
111
112 LOG_UPDATE_INTERVAL(this);
113
114 LOG_SENSOR(" ", "ALS calculated lux", this->ambient_light_sensor_);
115 LOG_SENSOR(" ", "CH1 Infrared counts", this->infrared_counts_sensor_);
116 LOG_SENSOR(" ", "CH0 Visible+IR counts", this->full_spectrum_counts_sensor_);
117 LOG_SENSOR(" ", "Actual gain", this->actual_gain_sensor_);
118}
119
121 if (!this->is_als_()) {
122 ESP_LOGW(TAG, "Update. ALS data not available. Change configuration to ALS or ALS_PS.");
123 return;
124 }
125 if (this->is_ready() && this->is_als_() && this->state_ == State::IDLE) {
126 ESP_LOGV(TAG, "Update. Initiating new ALS data collection.");
127
129
130 this->als_readings_.ch0 = 0;
131 this->als_readings_.ch1 = 0;
132 this->als_readings_.gain = this->gain_;
134 this->als_readings_.lux = 0;
136
137 } else {
138 ESP_LOGV(TAG, "Update. Component not ready yet.");
139 }
140}
141
144
145 switch (this->state_) {
147 err = this->write(nullptr, 0);
148 if (err != i2c::ERROR_OK) {
149 ESP_LOGW(TAG, "i2c connection failed");
150 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
151 }
152 this->configure_reset_();
153 if (this->is_als_()) {
154 this->configure_als_();
156 }
157 if (this->is_ps_()) {
158 this->configure_ps_();
159 }
160
161 this->state_ = State::IDLE;
162 break;
163
164 case State::IDLE:
165 if (this->is_ps_()) {
166 this->check_and_trigger_ps_();
167 }
168 break;
169
172 this->tries_ = 0;
173 ESP_LOGV(TAG, "Reading sensor data assuming gain = %.0fx, time = %d ms",
174 get_gain_coeff(this->als_readings_.gain), get_itime_ms(this->als_readings_.integration_time));
175 this->read_sensor_data_(this->als_readings_);
177 this->state_ = State::DATA_COLLECTED;
178 } else if (this->tries_ >= MAX_TRIES) {
179 ESP_LOGW(TAG, "Can't get data after several tries. Aborting.");
180 this->tries_ = 0;
181 this->status_set_warning();
182 this->state_ = State::IDLE;
183 return;
184 } else {
185 this->tries_++;
186 }
187 break;
188
191 // first measurement in auto mode (COLLECTING_DATA_AUTO state) require device reconfiguration
192 if (this->state_ == State::COLLECTING_DATA_AUTO || this->are_adjustments_required_(this->als_readings_)) {
193 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
194 ESP_LOGD(TAG, "Reconfiguring sensitivity: gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
195 get_itime_ms(this->als_readings_.integration_time));
198 // if sensitivity adjustment needed - need to wait for first data samples after setting new parameters
199 this->set_timeout(2 * get_meas_time_ms(this->repeat_rate_),
200 [this]() { this->state_ = State::WAITING_FOR_DATA; });
201 } else {
202 this->state_ = State::READY_TO_PUBLISH;
203 }
204 break;
205
207 // nothing to be done, just waiting for the timeout
208 break;
209
212 this->state_ = State::KEEP_PUBLISHING;
213 break;
214
217 this->status_clear_warning();
218 this->state_ = State::IDLE;
219 break;
220
221 default:
222 break;
223 }
224}
225
227 uint16_t ps_data = this->read_ps_data_();
228 uint32_t now = millis();
229
230 if (ps_data != this->ps_readings_) {
231 this->ps_readings_ = ps_data;
232 // Higher values - object is closer to sensor
233 if (ps_data > this->ps_threshold_high_ &&
234 now - this->last_ps_high_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
235 this->last_ps_high_trigger_time_ = now;
236 ESP_LOGD(TAG, "Proximity high threshold triggered. Value = %d, Trigger level = %d", ps_data,
237 this->ps_threshold_high_);
238 this->on_ps_high_trigger_callback_.call();
239 } else if (ps_data < this->ps_threshold_low_ &&
240 now - this->last_ps_low_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
241 this->last_ps_low_trigger_time_ = now;
242 ESP_LOGD(TAG, "Proximity low threshold triggered. Value = %d, Trigger level = %d", ps_data,
243 this->ps_threshold_low_);
244 this->on_ps_low_trigger_callback_.call();
245 }
246 }
247}
248
250 uint8_t manuf_id = this->reg((uint8_t) CommandRegisters::MANUFAC_ID).get();
251 if (manuf_id != 0x05) { // 0x05 is Lite-On Semiconductor Corp. ID
252 ESP_LOGW(TAG, "Unknown manufacturer ID: 0x%02X", manuf_id);
253 this->mark_failed();
254 return false;
255 }
256
257 // Things getting not really funny here, we can't identify device type by part number ID
258 // ======================== ========= ===== =================
259 // Device Part ID Rev Capabilities
260 // ======================== ========= ===== =================
261 // ltr-558als 0x08 0 als + ps
262 // ltr-501als 0x08 0 als + ps
263 // ltr-301als - 0x08 0 als only
264
265 PartIdRegister part_id{0};
266 part_id.raw = this->reg((uint8_t) CommandRegisters::PART_ID).get();
267 if (part_id.part_number_id != 0x08) {
268 ESP_LOGW(TAG, "Unknown part number ID: 0x%02X. LTR-501/301 shall have 0x08. It might not work properly.",
269 part_id.part_number_id);
270 this->status_set_warning();
271 return true;
272 }
273 return true;
274}
275
277 ESP_LOGV(TAG, "Resetting");
278
279 AlsControlRegister501 als_ctrl{0};
280 als_ctrl.sw_reset = true;
281 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
282 delay(2);
283
284 uint8_t tries = MAX_TRIES;
285 do {
286 ESP_LOGV(TAG, "Waiting chip to reset");
287 delay(2);
288 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
289 } while (als_ctrl.sw_reset && tries--); // while sw reset bit is on - keep waiting
290
291 if (als_ctrl.sw_reset) {
292 ESP_LOGW(TAG, "Reset failed");
293 }
294}
295
297 AlsControlRegister501 als_ctrl{0};
298 als_ctrl.sw_reset = false;
299 als_ctrl.als_mode_active = true;
300 als_ctrl.gain = this->gain_;
301
302 ESP_LOGV(TAG, "Setting active mode and gain reg 0x%02X", als_ctrl.raw);
303 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
304 delay(5);
305
306 uint8_t tries = MAX_TRIES;
307 do {
308 ESP_LOGV(TAG, "Waiting for ALS device to become active");
309 delay(2);
310 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
311 } while (!als_ctrl.als_mode_active && tries--); // while active mode is not set - keep waiting
312
313 if (!als_ctrl.als_mode_active) {
314 ESP_LOGW(TAG, "Failed to activate ALS device");
315 }
316}
317
319 PsMeasurementRateRegister ps_meas{0};
321 this->reg((uint8_t) CommandRegisters::PS_MEAS_RATE) = ps_meas.raw;
322
323 PsControlRegister501 ps_ctrl{0};
324 ps_ctrl.ps_mode_active = true;
325 ps_ctrl.ps_mode_xxx = true;
326 this->reg((uint8_t) CommandRegisters::PS_CONTR) = ps_ctrl.raw;
327}
328
330 AlsPsStatusRegister als_status{0};
331 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
332 if (!als_status.ps_new_data) {
333 return this->ps_readings_;
334 }
335
336 uint8_t ps_low = this->reg((uint8_t) CommandRegisters::PS_DATA_0).get();
337 PsData1Register ps_high;
338 ps_high.raw = this->reg((uint8_t) CommandRegisters::PS_DATA_1).get();
339
340 uint16_t val = encode_uint16(ps_high.ps_data_high, ps_low);
341 return val;
342}
343
345 AlsControlRegister501 als_ctrl{0};
346 als_ctrl.als_mode_active = true;
347 als_ctrl.gain = gain;
348 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
349 delay(2);
350
351 AlsControlRegister501 read_als_ctrl{0};
352 read_als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
353 if (read_als_ctrl.gain != gain) {
354 ESP_LOGW(TAG, "Failed to set gain. We will try one more time.");
355 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
356 delay(2);
357 }
358}
359
363 meas.integration_time = time;
364 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
365 delay(2);
366
367 MeasurementRateRegister501 read_meas{0};
368 read_meas.raw = this->reg((uint8_t) CommandRegisters::MEAS_RATE).get();
369 if (read_meas.integration_time != time) {
370 ESP_LOGW(TAG, "Failed to set integration time. We will try one more time.");
371 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
372 delay(2);
373 }
374}
375
377 AlsPsStatusRegister als_status{0};
378 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
379 if (!als_status.als_new_data)
381 ESP_LOGV(TAG, "Data ready, reported gain is %.0fx", get_gain_coeff(als_status.gain));
382 if (data.gain != als_status.gain) {
383 ESP_LOGW(TAG, "Actual gain differs from requested (%.0f)", get_gain_coeff(data.gain));
385 }
386 data.gain = als_status.gain;
388}
389
391 data.ch1 = 0;
392 data.ch0 = 0;
393 uint8_t ch1_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_0).get();
394 uint8_t ch1_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_1).get();
395 uint8_t ch0_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_0).get();
396 uint8_t ch0_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_1).get();
397 data.ch1 = encode_uint16(ch1_1, ch1_0);
398 data.ch0 = encode_uint16(ch0_1, ch0_0);
399
400 ESP_LOGD(TAG, "Got sensor data: CH1 = %d, CH0 = %d", data.ch1, data.ch0);
401}
402
404 if (!this->automatic_mode_enabled_)
405 return false;
406
407 // sometimes sensors fail to change sensitivity. this prevents us from infinite loop
408 if (data.number_of_adjustments++ > MAX_SENSITIVITY_ADJUSTMENTS) {
409 ESP_LOGW(TAG, "Too many sensitivity adjustments done. Something wrong with the sensor. Stopping.");
410 return false;
411 }
412
413 ESP_LOGV(TAG, "Adjusting sensitivity, run #%d", data.number_of_adjustments);
414
415 // available combinations of gain and integration times:
416 static const GainTimePair GAIN_TIME_PAIRS[] = {
420 };
421
422 GainTimePair current_pair = {data.gain, data.integration_time};
423
424 // Here comes funky business with this sensor. it has no internal error checking mechanism
425 // as in later versions (LTR-303/329/559/..) and sensor gets overwhelmed when saturated
426 // and readings are strange. We only check high sensitivity mode for now.
427 // Nothing is documented and it is a result of real-world testing.
428 if (data.gain == AlsGain501::GAIN_150) {
429 // when sensor is saturated it returns various crazy numbers
430 // CH1 = 1, CH0 = 0
431 if (data.ch1 == 1 && data.ch0 == 0) {
432 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = 1, CH0 = 0, Gain 150x");
433 // fake saturation
434 data.ch0 = 0xffff;
435 data.ch1 = 0xffff;
436 } else if (data.ch1 == 65535 && data.ch0 == 0) {
437 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = 65535, CH0 = 0, Gain 150x");
438 data.ch0 = 0xffff;
439 } else if (data.ch1 > 1000 && data.ch0 == 0) {
440 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = %d, CH0 = 0, Gain 150x", data.ch1);
441 data.ch0 = 0xffff;
442 }
443 }
444
445 static const uint16_t LOW_INTENSITY_THRESHOLD_1 = 100;
446 static const uint16_t LOW_INTENSITY_THRESHOLD_200 = 2000;
447 static const uint16_t HIGH_INTENSITY_THRESHOLD = 25000;
448
449 if (data.ch0 <= (data.gain == AlsGain501::GAIN_1 ? LOW_INTENSITY_THRESHOLD_1 : LOW_INTENSITY_THRESHOLD_200) ||
450 (data.gain == AlsGain501::GAIN_1 && data.lux < 320)) {
451 GainTimePair next_pair = get_next(GAIN_TIME_PAIRS, current_pair);
452 if (next_pair != current_pair) {
453 data.gain = next_pair.gain;
454 data.integration_time = next_pair.time;
455 ESP_LOGV(TAG, "Low illuminance. Increasing sensitivity.");
456 return true;
457 }
458
459 } else if (data.ch0 >= HIGH_INTENSITY_THRESHOLD || data.ch1 >= HIGH_INTENSITY_THRESHOLD) {
460 GainTimePair prev_pair = get_prev(GAIN_TIME_PAIRS, current_pair);
461 if (prev_pair != current_pair) {
462 data.gain = prev_pair.gain;
463 data.integration_time = prev_pair.time;
464 ESP_LOGV(TAG, "High illuminance. Decreasing sensitivity.");
465 return true;
466 }
467 } else {
468 ESP_LOGD(TAG, "Illuminance is good enough.");
469 return false;
470 }
471 ESP_LOGD(TAG, "Can't adjust sensitivity anymore.");
472 return false;
473}
474
476 if ((data.ch0 == 0xFFFF) || (data.ch1 == 0xFFFF)) {
477 ESP_LOGW(TAG, "Sensors got saturated");
478 data.lux = 0.0f;
479 return;
480 }
481
482 if ((data.ch0 == 0x0000) && (data.ch1 == 0x0000)) {
483 ESP_LOGW(TAG, "Sensors blacked out");
484 data.lux = 0.0f;
485 return;
486 }
487
488 float ch0 = data.ch0;
489 float ch1 = data.ch1;
490 float ratio = ch1 / (ch0 + ch1);
491 float als_gain = get_gain_coeff(data.gain);
492 float als_time = ((float) get_itime_ms(data.integration_time)) / 100.0f;
493 float inv_pfactor = this->glass_attenuation_factor_;
494 float lux = 0.0f;
495
496 // method from
497 // https://github.com/fards/Ainol_fire_kernel/blob/83832cf8a3082fd8e963230f4b1984479d1f1a84/customer/drivers/lightsensor/ltr501als.c#L295
498
499 if (ratio < 0.45f) {
500 lux = 1.7743f * ch0 + 1.1059f * ch1;
501 } else if (ratio < 0.64f) {
502 lux = 3.7725f * ch0 - 1.3363f * ch1;
503 } else if (ratio < 0.85f) {
504 lux = 1.6903f * ch0 - 0.1693f * ch1;
505 } else {
506 ESP_LOGW(TAG, "Impossible ch1/(ch0 + ch1) ratio");
507 lux = 0.0f;
508 }
509
510 lux = inv_pfactor * lux / als_gain / als_time;
511 data.lux = lux;
512
513 ESP_LOGD(TAG, "Lux calculation: ratio %.3f, gain %.0fx, int time %.1f, inv_pfactor %.3f, lux %.3f", ratio, als_gain,
514 als_time, inv_pfactor, lux);
515}
516
518 if (this->proximity_counts_sensor_ != nullptr) {
520 }
521 if (this->ambient_light_sensor_ != nullptr) {
523 }
524 if (this->infrared_counts_sensor_ != nullptr) {
526 }
527 if (this->full_spectrum_counts_sensor_ != nullptr) {
529 }
530}
531
533 if (this->actual_gain_sensor_ != nullptr) {
534 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.gain));
535 }
536 if (this->actual_integration_time_sensor_ != nullptr) {
537 this->actual_integration_time_sensor_->publish_state(get_itime_ms(data.integration_time));
538 }
539}
540} // namespace esphome::ltr501
void mark_failed()
Mark this component as failed.
bool is_ready() const
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:296
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:195
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:164
uint8_t get() const
returns the register value
Definition i2c.cpp:126
LtrDataAvail is_als_data_ready_(AlsReadings &data)
Definition ltr501.cpp:376
void configure_gain_(AlsGain501 gain)
Definition ltr501.cpp:344
void publish_data_part_1_(AlsReadings &data)
Definition ltr501.cpp:517
void publish_data_part_2_(AlsReadings &data)
Definition ltr501.cpp:532
void configure_integration_time_(IntegrationTime501 time)
Definition ltr501.cpp:360
sensor::Sensor * actual_integration_time_sensor_
Definition ltr501.h:151
CallbackManager< void()> on_ps_high_trigger_callback_
Definition ltr501.h:161
IntegrationTime501 integration_time_
Definition ltr501.h:133
struct esphome::ltr501::LTRAlsPs501Component::AlsReadings als_readings_
void read_sensor_data_(AlsReadings &data)
Definition ltr501.cpp:390
MeasurementRepeatRate repeat_rate_
Definition ltr501.h:134
CallbackManager< void()> on_ps_low_trigger_callback_
Definition ltr501.h:162
void apply_lux_calculation_(AlsReadings &data)
Definition ltr501.cpp:475
sensor::Sensor * proximity_counts_sensor_
Definition ltr501.h:152
sensor::Sensor * infrared_counts_sensor_
Definition ltr501.h:147
bool are_adjustments_required_(AlsReadings &data)
Definition ltr501.cpp:403
sensor::Sensor * full_spectrum_counts_sensor_
Definition ltr501.h:148
sensor::Sensor * actual_gain_sensor_
Definition ltr501.h:150
sensor::Sensor * ambient_light_sensor_
Definition ltr501.h:149
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
AlsGain501 gain
mopeka_std_values val[3]
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:13
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
@ LTR_TYPE_ALS_AND_PS
Definition ltr501.h:19
@ LTR_TYPE_ALS_ONLY
Definition ltr501.h:17
ESPHOME_LOG_TAG(TAG, "ltr501")
bool operator!=(const GainTimePair &lhs, const GainTimePair &rhs)
Definition ltr501.cpp:25
T get_next(const T(&array)[size], const T val)
Definition ltr501.cpp:29
bool operator==(const GainTimePair &lhs, const GainTimePair &rhs)
Definition ltr501.cpp:21
T get_prev(const T(&array)[size], const T val)
Definition ltr501.cpp:44
uint16_t size
Definition helpers.cpp:34
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:998
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t