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