ESPHome 2026.5.1
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
11static const char *const 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 if (this->is_failed()) {
120 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
121 }
122}
123
125 if (!this->is_als_()) {
126 ESP_LOGW(TAG, "Update. ALS data not available. Change configuration to ALS or ALS_PS.");
127 return;
128 }
129 if (this->is_ready() && this->is_als_() && this->state_ == State::IDLE) {
130 ESP_LOGV(TAG, "Update. Initiating new ALS data collection.");
131
133
134 this->als_readings_.ch0 = 0;
135 this->als_readings_.ch1 = 0;
136 this->als_readings_.gain = this->gain_;
138 this->als_readings_.lux = 0;
140
141 } else {
142 ESP_LOGV(TAG, "Update. Component not ready yet.");
143 }
144}
145
148
149 switch (this->state_) {
151 err = this->write(nullptr, 0);
152 if (err != i2c::ERROR_OK) {
153 ESP_LOGW(TAG, "i2c connection failed");
154 this->mark_failed();
155 }
156 this->configure_reset_();
157 if (this->is_als_()) {
158 this->configure_als_();
160 }
161 if (this->is_ps_()) {
162 this->configure_ps_();
163 }
164
165 this->state_ = State::IDLE;
166 break;
167
168 case State::IDLE:
169 if (this->is_ps_()) {
170 this->check_and_trigger_ps_();
171 }
172 break;
173
176 this->tries_ = 0;
177 ESP_LOGV(TAG, "Reading sensor data assuming gain = %.0fx, time = %d ms",
178 get_gain_coeff(this->als_readings_.gain), get_itime_ms(this->als_readings_.integration_time));
179 this->read_sensor_data_(this->als_readings_);
181 this->state_ = State::DATA_COLLECTED;
182 } else if (this->tries_ >= MAX_TRIES) {
183 ESP_LOGW(TAG, "Can't get data after several tries. Aborting.");
184 this->tries_ = 0;
185 this->status_set_warning();
186 this->state_ = State::IDLE;
187 return;
188 } else {
189 this->tries_++;
190 }
191 break;
192
195 // first measurement in auto mode (COLLECTING_DATA_AUTO state) require device reconfiguration
196 if (this->state_ == State::COLLECTING_DATA_AUTO || this->are_adjustments_required_(this->als_readings_)) {
197 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
198 ESP_LOGD(TAG, "Reconfiguring sensitivity: gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
199 get_itime_ms(this->als_readings_.integration_time));
202 // if sensitivity adjustment needed - need to wait for first data samples after setting new parameters
203 this->set_timeout(2 * get_meas_time_ms(this->repeat_rate_),
204 [this]() { this->state_ = State::WAITING_FOR_DATA; });
205 } else {
206 this->state_ = State::READY_TO_PUBLISH;
207 }
208 break;
209
211 // nothing to be done, just waiting for the timeout
212 break;
213
216 this->state_ = State::KEEP_PUBLISHING;
217 break;
218
221 this->status_clear_warning();
222 this->state_ = State::IDLE;
223 break;
224
225 default:
226 break;
227 }
228}
229
231 uint16_t ps_data = this->read_ps_data_();
232 uint32_t now = millis();
233
234 if (ps_data != this->ps_readings_) {
235 this->ps_readings_ = ps_data;
236 // Higher values - object is closer to sensor
237 if (ps_data > this->ps_threshold_high_ &&
238 now - this->last_ps_high_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
239 this->last_ps_high_trigger_time_ = now;
240 ESP_LOGD(TAG, "Proximity high threshold triggered. Value = %d, Trigger level = %d", ps_data,
241 this->ps_threshold_high_);
242 this->on_ps_high_trigger_callback_.call();
243 } else if (ps_data < this->ps_threshold_low_ &&
244 now - this->last_ps_low_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
245 this->last_ps_low_trigger_time_ = now;
246 ESP_LOGD(TAG, "Proximity low threshold triggered. Value = %d, Trigger level = %d", ps_data,
247 this->ps_threshold_low_);
248 this->on_ps_low_trigger_callback_.call();
249 }
250 }
251}
252
254 uint8_t manuf_id = this->reg((uint8_t) CommandRegisters::MANUFAC_ID).get();
255 if (manuf_id != 0x05) { // 0x05 is Lite-On Semiconductor Corp. ID
256 ESP_LOGW(TAG, "Unknown manufacturer ID: 0x%02X", manuf_id);
257 this->mark_failed();
258 return false;
259 }
260
261 // Things getting not really funny here, we can't identify device type by part number ID
262 // ======================== ========= ===== =================
263 // Device Part ID Rev Capabilities
264 // ======================== ========= ===== =================
265 // ltr-558als 0x08 0 als + ps
266 // ltr-501als 0x08 0 als + ps
267 // ltr-301als - 0x08 0 als only
268
269 PartIdRegister part_id{0};
270 part_id.raw = this->reg((uint8_t) CommandRegisters::PART_ID).get();
271 if (part_id.part_number_id != 0x08) {
272 ESP_LOGW(TAG, "Unknown part number ID: 0x%02X. LTR-501/301 shall have 0x08. It might not work properly.",
273 part_id.part_number_id);
274 this->status_set_warning();
275 return true;
276 }
277 return true;
278}
279
281 ESP_LOGV(TAG, "Resetting");
282
283 AlsControlRegister501 als_ctrl{0};
284 als_ctrl.sw_reset = true;
285 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
286 delay(2);
287
288 uint8_t tries = MAX_TRIES;
289 do {
290 ESP_LOGV(TAG, "Waiting chip to reset");
291 delay(2);
292 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
293 } while (als_ctrl.sw_reset && tries--); // while sw reset bit is on - keep waiting
294
295 if (als_ctrl.sw_reset) {
296 ESP_LOGW(TAG, "Reset failed");
297 }
298}
299
301 AlsControlRegister501 als_ctrl{0};
302 als_ctrl.sw_reset = false;
303 als_ctrl.als_mode_active = true;
304 als_ctrl.gain = this->gain_;
305
306 ESP_LOGV(TAG, "Setting active mode and gain reg 0x%02X", als_ctrl.raw);
307 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
308 delay(5);
309
310 uint8_t tries = MAX_TRIES;
311 do {
312 ESP_LOGV(TAG, "Waiting for ALS device to become active");
313 delay(2);
314 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
315 } while (!als_ctrl.als_mode_active && tries--); // while active mode is not set - keep waiting
316
317 if (!als_ctrl.als_mode_active) {
318 ESP_LOGW(TAG, "Failed to activate ALS device");
319 }
320}
321
323 PsMeasurementRateRegister ps_meas{0};
325 this->reg((uint8_t) CommandRegisters::PS_MEAS_RATE) = ps_meas.raw;
326
327 PsControlRegister501 ps_ctrl{0};
328 ps_ctrl.ps_mode_active = true;
329 ps_ctrl.ps_mode_xxx = true;
330 this->reg((uint8_t) CommandRegisters::PS_CONTR) = ps_ctrl.raw;
331}
332
334 AlsPsStatusRegister als_status{0};
335 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
336 if (!als_status.ps_new_data) {
337 return this->ps_readings_;
338 }
339
340 uint8_t ps_low = this->reg((uint8_t) CommandRegisters::PS_DATA_0).get();
341 PsData1Register ps_high;
342 ps_high.raw = this->reg((uint8_t) CommandRegisters::PS_DATA_1).get();
343
344 uint16_t val = encode_uint16(ps_high.ps_data_high, ps_low);
345 return val;
346}
347
349 AlsControlRegister501 als_ctrl{0};
350 als_ctrl.als_mode_active = true;
351 als_ctrl.gain = gain;
352 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
353 delay(2);
354
355 AlsControlRegister501 read_als_ctrl{0};
356 read_als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
357 if (read_als_ctrl.gain != gain) {
358 ESP_LOGW(TAG, "Failed to set gain. We will try one more time.");
359 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
360 delay(2);
361 }
362}
363
367 meas.integration_time = time;
368 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
369 delay(2);
370
371 MeasurementRateRegister501 read_meas{0};
372 read_meas.raw = this->reg((uint8_t) CommandRegisters::MEAS_RATE).get();
373 if (read_meas.integration_time != time) {
374 ESP_LOGW(TAG, "Failed to set integration time. We will try one more time.");
375 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
376 delay(2);
377 }
378}
379
381 AlsPsStatusRegister als_status{0};
382 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
383 if (!als_status.als_new_data)
385 ESP_LOGV(TAG, "Data ready, reported gain is %.0fx", get_gain_coeff(als_status.gain));
386 if (data.gain != als_status.gain) {
387 ESP_LOGW(TAG, "Actual gain differs from requested (%.0f)", get_gain_coeff(data.gain));
389 }
390 data.gain = als_status.gain;
392}
393
395 data.ch1 = 0;
396 data.ch0 = 0;
397 uint8_t ch1_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_0).get();
398 uint8_t ch1_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_1).get();
399 uint8_t ch0_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_0).get();
400 uint8_t ch0_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_1).get();
401 data.ch1 = encode_uint16(ch1_1, ch1_0);
402 data.ch0 = encode_uint16(ch0_1, ch0_0);
403
404 ESP_LOGD(TAG, "Got sensor data: CH1 = %d, CH0 = %d", data.ch1, data.ch0);
405}
406
408 if (!this->automatic_mode_enabled_)
409 return false;
410
411 // sometimes sensors fail to change sensitivity. this prevents us from infinite loop
412 if (data.number_of_adjustments++ > MAX_SENSITIVITY_ADJUSTMENTS) {
413 ESP_LOGW(TAG, "Too many sensitivity adjustments done. Something wrong with the sensor. Stopping.");
414 return false;
415 }
416
417 ESP_LOGV(TAG, "Adjusting sensitivity, run #%d", data.number_of_adjustments);
418
419 // available combinations of gain and integration times:
420 static const GainTimePair GAIN_TIME_PAIRS[] = {
424 };
425
426 GainTimePair current_pair = {data.gain, data.integration_time};
427
428 // Here comes funky business with this sensor. it has no internal error checking mechanism
429 // as in later versions (LTR-303/329/559/..) and sensor gets overwhelmed when saturated
430 // and readings are strange. We only check high sensitivity mode for now.
431 // Nothing is documented and it is a result of real-world testing.
432 if (data.gain == AlsGain501::GAIN_150) {
433 // when sensor is saturated it returns various crazy numbers
434 // CH1 = 1, CH0 = 0
435 if (data.ch1 == 1 && data.ch0 == 0) {
436 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = 1, CH0 = 0, Gain 150x");
437 // fake saturation
438 data.ch0 = 0xffff;
439 data.ch1 = 0xffff;
440 } else if (data.ch1 == 65535 && data.ch0 == 0) {
441 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = 65535, CH0 = 0, Gain 150x");
442 data.ch0 = 0xffff;
443 } else if (data.ch1 > 1000 && data.ch0 == 0) {
444 ESP_LOGV(TAG, "Looks like sensor got saturated (?) CH1 = %d, CH0 = 0, Gain 150x", data.ch1);
445 data.ch0 = 0xffff;
446 }
447 }
448
449 static const uint16_t LOW_INTENSITY_THRESHOLD_1 = 100;
450 static const uint16_t LOW_INTENSITY_THRESHOLD_200 = 2000;
451 static const uint16_t HIGH_INTENSITY_THRESHOLD = 25000;
452
453 if (data.ch0 <= (data.gain == AlsGain501::GAIN_1 ? LOW_INTENSITY_THRESHOLD_1 : LOW_INTENSITY_THRESHOLD_200) ||
454 (data.gain == AlsGain501::GAIN_1 && data.lux < 320)) {
455 GainTimePair next_pair = get_next(GAIN_TIME_PAIRS, current_pair);
456 if (next_pair != current_pair) {
457 data.gain = next_pair.gain;
458 data.integration_time = next_pair.time;
459 ESP_LOGV(TAG, "Low illuminance. Increasing sensitivity.");
460 return true;
461 }
462
463 } else if (data.ch0 >= HIGH_INTENSITY_THRESHOLD || data.ch1 >= HIGH_INTENSITY_THRESHOLD) {
464 GainTimePair prev_pair = get_prev(GAIN_TIME_PAIRS, current_pair);
465 if (prev_pair != current_pair) {
466 data.gain = prev_pair.gain;
467 data.integration_time = prev_pair.time;
468 ESP_LOGV(TAG, "High illuminance. Decreasing sensitivity.");
469 return true;
470 }
471 } else {
472 ESP_LOGD(TAG, "Illuminance is good enough.");
473 return false;
474 }
475 ESP_LOGD(TAG, "Can't adjust sensitivity anymore.");
476 return false;
477}
478
480 if ((data.ch0 == 0xFFFF) || (data.ch1 == 0xFFFF)) {
481 ESP_LOGW(TAG, "Sensors got saturated");
482 data.lux = 0.0f;
483 return;
484 }
485
486 if ((data.ch0 == 0x0000) && (data.ch1 == 0x0000)) {
487 ESP_LOGW(TAG, "Sensors blacked out");
488 data.lux = 0.0f;
489 return;
490 }
491
492 float ch0 = data.ch0;
493 float ch1 = data.ch1;
494 float ratio = ch1 / (ch0 + ch1);
495 float als_gain = get_gain_coeff(data.gain);
496 float als_time = ((float) get_itime_ms(data.integration_time)) / 100.0f;
497 float inv_pfactor = this->glass_attenuation_factor_;
498 float lux = 0.0f;
499
500 // method from
501 // https://github.com/fards/Ainol_fire_kernel/blob/83832cf8a3082fd8e963230f4b1984479d1f1a84/customer/drivers/lightsensor/ltr501als.c#L295
502
503 if (ratio < 0.45) {
504 lux = 1.7743 * ch0 + 1.1059 * ch1;
505 } else if (ratio < 0.64) {
506 lux = 3.7725 * ch0 - 1.3363 * ch1;
507 } else if (ratio < 0.85) {
508 lux = 1.6903 * ch0 - 0.1693 * ch1;
509 } else {
510 ESP_LOGW(TAG, "Impossible ch1/(ch0 + ch1) ratio");
511 lux = 0.0f;
512 }
513
514 lux = inv_pfactor * lux / als_gain / als_time;
515 data.lux = lux;
516
517 ESP_LOGD(TAG, "Lux calculation: ratio %.3f, gain %.0fx, int time %.1f, inv_pfactor %.3f, lux %.3f", ratio, als_gain,
518 als_time, inv_pfactor, lux);
519}
520
522 if (this->proximity_counts_sensor_ != nullptr) {
524 }
525 if (this->ambient_light_sensor_ != nullptr) {
527 }
528 if (this->infrared_counts_sensor_ != nullptr) {
530 }
531 if (this->full_spectrum_counts_sensor_ != nullptr) {
533 }
534}
535
537 if (this->actual_gain_sensor_ != nullptr) {
538 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.gain));
539 }
540 if (this->actual_integration_time_sensor_ != nullptr) {
541 this->actual_integration_time_sensor_->publish_state(get_itime_ms(data.integration_time));
542 }
543}
544} // namespace esphome::ltr501
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:284
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:510
bool is_ready() const
void status_clear_warning()
Definition component.h:306
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:183
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:152
uint8_t get() const
returns the register value
Definition i2c.cpp:84
LtrDataAvail is_als_data_ready_(AlsReadings &data)
Definition ltr501.cpp:380
void configure_gain_(AlsGain501 gain)
Definition ltr501.cpp:348
void publish_data_part_1_(AlsReadings &data)
Definition ltr501.cpp:521
void publish_data_part_2_(AlsReadings &data)
Definition ltr501.cpp:536
void configure_integration_time_(IntegrationTime501 time)
Definition ltr501.cpp:364
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:394
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:479
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:407
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:68
AlsGain501 gain
mopeka_std_values val[3]
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:12
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:14
@ LTR_TYPE_ALS_AND_PS
Definition ltr501.h:19
@ LTR_TYPE_ALS_ONLY
Definition ltr501.h:17
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:25
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:859
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t