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