ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
tsl2591.cpp
Go to the documentation of this file.
1#include "tsl2591.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
4
5namespace esphome {
6namespace tsl2591 {
7
8static const char *const TAG = "tsl2591.sensor";
9
10// Various constants used in TSL2591 register manipulation
11#define TSL2591_COMMAND_BIT (0xA0) // 1010 0000: bits 7 and 5 for 'command, normal'
12#define TSL2591_ENABLE_POWERON (0x01) // Flag for ENABLE register, to enable
13#define TSL2591_ENABLE_POWEROFF (0x00) // Flag for ENABLE register, to disable
14#define TSL2591_ENABLE_AEN (0x02) // Flag for ENABLE register, to turn on ADCs
15
16// TSL2591 registers from the datasheet. We only define what we use.
17#define TSL2591_REGISTER_ENABLE (0x00)
18#define TSL2591_REGISTER_CONTROL (0x01)
19#define TSL2591_REGISTER_DEVICE_ID (0x12)
20#define TSL2591_REGISTER_STATUS (0x13)
21#define TSL2591_REGISTER_CHAN0_LOW (0x14)
22#define TSL2591_REGISTER_CHAN0_HIGH (0x15)
23#define TSL2591_REGISTER_CHAN1_LOW (0x16)
24#define TSL2591_REGISTER_CHAN1_HIGH (0x17)
25
27 // Enable the device by setting the control bit to 0x01. Also turn on ADCs.
28 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN)) {
29 ESP_LOGE(TAG, "I2C write failed");
30 }
31}
32
34 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWEROFF)) {
35 ESP_LOGE(TAG, "I2C write failed");
36 }
37}
38
44
46 switch (this->component_gain_) {
48 this->gain_ = TSL2591_GAIN_LOW;
49 break;
51 this->gain_ = TSL2591_GAIN_MED;
52 break;
55 break;
57 this->gain_ = TSL2591_GAIN_MAX;
58 break;
60 this->gain_ = TSL2591_GAIN_MED;
61 break;
62 }
63
64 uint8_t id;
65 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_ID, &id)) {
66 ESP_LOGE(TAG, "I2C read failed");
67 this->mark_failed();
68 return;
69 }
70
71 if (id != 0x50) {
72 ESP_LOGE(TAG, "Unknown chip ID");
73 this->mark_failed();
74 return;
75 }
76
79}
80
82 ESP_LOGCONFIG(TAG, "TSL2591:");
83 LOG_I2C_DEVICE(this);
84
85 if (this->is_failed()) {
86 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
87 return;
88 }
89
90 ESP_LOGCONFIG(TAG, " Name: %s", this->name_);
92 int gain = 0;
93 std::string gain_word = "unknown";
94 switch (raw_gain) {
96 gain = 1;
97 gain_word = "low";
98 break;
100 gain = 25;
101 gain_word = "medium";
102 break;
104 gain = 400;
105 gain_word = "high";
106 break;
108 gain = 9500;
109 gain_word = "maximum";
110 break;
112 gain = -1;
113 gain_word = "auto";
114 break;
115 }
116 TSL2591IntegrationTime raw_timing = this->integration_time_;
117 int timing_ms = (1 + raw_timing) * 100;
118 ESP_LOGCONFIG(TAG,
119 " Gain: %dx (%s)"
120 " Integration Time: %d ms\n"
121 " Power save mode enabled: %s\n"
122 " Device factor: %f\n"
123 " Glass attenuation factor: %f",
124 gain, gain_word.c_str(), timing_ms, ONOFF(this->power_save_mode_enabled_), this->device_factor_,
126 LOG_SENSOR(" ", "Full spectrum:", this->full_spectrum_sensor_);
127 LOG_SENSOR(" ", "Infrared:", this->infrared_sensor_);
128 LOG_SENSOR(" ", "Visible:", this->visible_sensor_);
129 LOG_SENSOR(" ", "Calculated lux:", this->calculated_lux_sensor_);
130 LOG_SENSOR(" ", "Actual gain:", this->actual_gain_sensor_);
131
132 LOG_UPDATE_INTERVAL(this);
133}
134
136 uint32_t combined = this->get_combined_illuminance();
137 uint16_t visible = this->get_illuminance(TSL2591_SENSOR_CHANNEL_VISIBLE, combined);
138 uint16_t infrared = this->get_illuminance(TSL2591_SENSOR_CHANNEL_INFRARED, combined);
139 uint16_t full = this->get_illuminance(TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM, combined);
140 float lux = this->get_calculated_lux(full, infrared);
141 uint16_t actual_gain = this->get_actual_gain();
142 ESP_LOGD(TAG, "Got illuminance: combined 0x%" PRIX32 ", full %d, IR %d, vis %d. Calc lux: %f. Actual gain: %d.",
143 combined, full, infrared, visible, lux, actual_gain);
144 if (this->full_spectrum_sensor_ != nullptr) {
146 }
147 if (this->infrared_sensor_ != nullptr) {
148 this->infrared_sensor_->publish_state(infrared);
149 }
150 if (this->visible_sensor_ != nullptr) {
151 this->visible_sensor_->publish_state(visible);
152 }
153 if (this->calculated_lux_sensor_ != nullptr) {
155 }
156
157 if (this->component_gain_ == TSL2591_CGAIN_AUTO) {
158 this->automatic_gain_update(full);
159 }
160
161 if (this->actual_gain_sensor_ != nullptr) {
162 this->actual_gain_sensor_->publish_state(actual_gain);
163 }
164 this->status_clear_warning();
165}
166
167#define interval_name "tsl2591_interval_for_update"
168
170 if (!this->is_adc_valid()) {
171 uint64_t now = millis();
172 ESP_LOGD(TAG, "Elapsed %3llu ms; still waiting for valid ADC", (now - this->interval_start_));
173 if (now > this->interval_timeout_) {
174 ESP_LOGW(TAG, "Interval timeout for '%s' expired before ADCs became valid", this->name_);
175 this->cancel_interval(interval_name);
176 }
177 return;
178 }
179 this->cancel_interval(interval_name);
180 this->process_update_();
181}
182
184 if (!is_failed()) {
185 if (this->power_save_mode_enabled_) {
186 // we enabled it here, else ADC will never become valid
187 // but actually doing the reads will disable device if needed
188 this->enable();
189 }
190 if (this->is_adc_valid()) {
191 this->process_update_();
192 } else {
193 this->interval_start_ = millis();
194 this->interval_timeout_ = this->interval_start_ + 620;
195 this->set_interval(interval_name, 100, [this] { this->interval_function_for_update_(); });
196 }
197 }
198}
199
201 this->infrared_sensor_ = infrared_sensor;
202}
203
204void TSL2591Component::set_visible_sensor(sensor::Sensor *visible_sensor) { this->visible_sensor_ = visible_sensor; }
205
207 this->full_spectrum_sensor_ = full_spectrum_sensor;
208}
209
211 this->calculated_lux_sensor_ = calculated_lux_sensor;
212}
213
215 this->actual_gain_sensor_ = actual_gain_sensor;
216}
217
221
223
224void TSL2591Component::set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor) {
225 this->device_factor_ = device_factor;
226 this->glass_attenuation_factor_ = glass_attenuation_factor;
227}
228
230 this->enable();
232 this->gain_ = gain;
233 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL,
234 static_cast<uint8_t>(this->integration_time_) | static_cast<uint8_t>(this->gain_))) {
235 ESP_LOGE(TAG, "I2C write failed");
236 }
237 // The ADC values can be confused if gain or integration time are changed in the middle of a cycle.
238 // So, we unconditionally disable the device to turn the ADCs off. When re-enabling, the ADCs
239 // will tell us when they are ready again. That avoids an initial bogus reading.
240 this->disable();
241 if (!this->power_save_mode_enabled_) {
242 this->enable();
243 }
244}
245
247
248void TSL2591Component::set_name(const char *name) { this->name_ = name; }
249
251 uint8_t status;
252 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_STATUS, &status)) {
253 ESP_LOGE(TAG, "I2C read failed");
254 return false;
255 }
256 return status & 0x01;
257}
258
260 this->enable();
261 // Wait x ms for ADC to complete and signal valid.
262 // The max integration time is 600ms, so that's our max delay.
263 // (But we use 620ms as a bit of slack.)
264 // We'll do mini-delays and break out as soon as the ADC is good.
265 bool avalid;
266 const uint8_t mini_delay = 100;
267 for (uint16_t d = 0; d < 620; d += mini_delay) {
268 avalid = this->is_adc_valid();
269 if (avalid) {
270 break;
271 }
272 // we only log this if we need any delay, since normally we don't
273 ESP_LOGD(TAG, " after %3d ms: ADC valid? %s", d, avalid ? "true" : "false");
274 delay(mini_delay);
275 }
276 if (!avalid) {
277 // still not valid after a sutiable delay
278 // we don't mark the device as failed since it might come around in the future (probably not :-()
279 ESP_LOGE(TAG, "Device '%s' returned invalid readings", this->name_);
281 return 0;
282 }
283
284 // CHAN0 must be read before CHAN1
285 // See: https://forums.adafruit.com/viewtopic.php?f=19&t=124176
286 // Also, low byte must be read before high byte..
287 // We read the registers in the order described in the datasheet.
288 uint32_t x32;
289 uint8_t ch0low, ch0high, ch1low, ch1high;
290 uint16_t ch0_16;
291 uint16_t ch1_16;
292 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_LOW, &ch0low)) {
293 ESP_LOGE(TAG, "I2C read failed");
294 return 0;
295 }
296 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_HIGH, &ch0high)) {
297 ESP_LOGE(TAG, "I2C read failed");
298 return 0;
299 }
300 ch0_16 = (ch0high << 8) | ch0low;
301 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_LOW, &ch1low)) {
302 ESP_LOGE(TAG, "I2C read failed");
303 return 0;
304 }
305 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_HIGH, &ch1high)) {
306 ESP_LOGE(TAG, "I2C read failed");
307 return 0;
308 }
309 ch1_16 = (ch1high << 8) | ch1low;
310 x32 = (ch1_16 << 16) | ch0_16;
311
313 return x32;
314}
315
317 uint32_t combined = this->get_combined_illuminance();
318 return this->get_illuminance(channel, combined);
319}
320// logic cloned from Adafruit TSL2591 library
321uint16_t TSL2591Component::get_illuminance(TSL2591SensorChannel channel, uint32_t combined_illuminance) {
323 // Reads two byte value from channel 0 (visible + infrared)
324 return (combined_illuminance & 0xFFFF);
325 } else if (channel == TSL2591_SENSOR_CHANNEL_INFRARED) {
326 // Reads two byte value from channel 1 (infrared)
327 return (combined_illuminance >> 16);
328 } else if (channel == TSL2591_SENSOR_CHANNEL_VISIBLE) {
329 // Reads all and subtracts out the infrared
330 return ((combined_illuminance & 0xFFFF) - (combined_illuminance >> 16));
331 }
332 // unknown channel!
333 ESP_LOGE(TAG, "get_illuminance() caller requested an unknown channel: %d", channel);
334 return 0;
335}
336
351float TSL2591Component::get_calculated_lux(uint16_t full_spectrum, uint16_t infrared) {
352 // Check for overflow conditions first
353 uint16_t max_count = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS ? 36863 : 65535);
354 if ((full_spectrum == max_count) || (infrared == max_count)) {
355 // Signal an overflow
356 ESP_LOGW(TAG, "Apparent saturation on '%s'; try reducing the gain or integration time", this->name_);
357 return NAN;
358 }
359
360 if ((full_spectrum == 0) && (infrared == 0)) {
361 // trivial conversion; avoids divide by 0
362 ESP_LOGW(TAG, "Zero reading on both '%s' sensors", this->name_);
363 return 0.0F;
364 }
365
366 float atime = 100.F + (this->integration_time_ * 100);
367
368 float again;
369 switch (this->gain_) {
370 case TSL2591_GAIN_LOW:
371 again = 1.0F;
372 break;
373 case TSL2591_GAIN_MED:
374 again = 25.0F;
375 break;
377 again = 400.0F;
378 break;
379 case TSL2591_GAIN_MAX:
380 again = 9500.0F;
381 break;
382 default:
383 again = 1.0F;
384 break;
385 }
386 // This lux equation is copied from the Adafruit TSL2591 v1.4.0 and modified slightly.
387 // See: https://github.com/adafruit/Adafruit_TSL2591_Library/issues/14
388 // and that library code.
389 // They said:
390 // Note: This algorithm is based on preliminary coefficients
391 // provided by AMS and may need to be updated in the future
392 // However, we use gain multipliers that are more in line with the midpoints
393 // of ranges from the datasheet. We don't know why the other libraries
394 // used the values they did for HIGH and MAX.
395 // If cpl or full_spectrum are 0, this will return NaN due to divide by 0.
396 // For the curious "cpl" is counts per lux, a term used in AMS application notes.
397 float cpl = (atime * again) / (this->device_factor_ * this->glass_attenuation_factor_);
398 float lux = (((float) full_spectrum - (float) infrared)) * (1.0F - ((float) infrared / (float) full_spectrum)) / cpl;
399 return std::max(lux, 0.0F);
400}
401
415void TSL2591Component::automatic_gain_update(uint16_t full_spectrum) {
416 TSL2591Gain new_gain = this->gain_;
417 uint fs_divider = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS) ? 2 : 1;
418
419 switch (this->gain_) {
420 case TSL2591_GAIN_LOW:
421 if (full_spectrum < 54) { // 1/3 FS / GAIN_HIGH
422 new_gain = TSL2591_GAIN_HIGH;
423 } else if (full_spectrum < 875) { // 1/3 FS / GAIN_MED
424 new_gain = TSL2591_GAIN_MED;
425 }
426 break;
427 case TSL2591_GAIN_MED:
428 if (full_spectrum < 57) { // 1/3 FS / (GAIN_MAX/GAIN_MED)
429 new_gain = TSL2591_GAIN_MAX;
430 } else if (full_spectrum < 1365) { // 1/3 FS / (GAIN_HIGH/GAIN_MED)
431 new_gain = TSL2591_GAIN_HIGH;
432 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_LOW/GAIN_MED) clipped to 95% FS
433 new_gain = TSL2591_GAIN_LOW;
434 }
435 break;
437 if (full_spectrum < 920) { // 1/3 FS / (GAIN_MAX/GAIN_HIGH)
438 new_gain = TSL2591_GAIN_MAX;
439 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
440 new_gain = TSL2591_GAIN_LOW;
441 }
442 break;
443 case TSL2591_GAIN_MAX:
444 if (full_spectrum > 62000 / fs_divider) // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
445 new_gain = TSL2591_GAIN_MED;
446 break;
447 }
448
449 if (this->gain_ != new_gain) {
450 this->gain_ = new_gain;
452 }
453 ESP_LOGD(TAG, "Gain setting: %d", this->gain_);
454}
455
461 switch (this->gain_) {
462 case TSL2591_GAIN_LOW:
463 return 1.0F;
464 case TSL2591_GAIN_MED:
465 return 25.0F;
467 return 400.0F;
468 case TSL2591_GAIN_MAX:
469 return 9500.0F;
470 default:
471 // Shouldn't get here, but just in case.
472 return NAN;
473 }
474}
475
476} // namespace tsl2591
477} // namespace esphome
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
bool is_failed() const
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_interval(const std voi set_interval)(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.h:350
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_interval(const std boo cancel_interval)(const char *name)
Cancel an interval function.
Definition component.h:372
void status_clear_warning()
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:265
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:240
Base-class for all sensors.
Definition sensor.h:47
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
TSL2591IntegrationTime integration_time_
Definition tsl2591.h:260
void dump_config() override
Used by ESPHome framework.
Definition tsl2591.cpp:81
TSL2591ComponentGain component_gain_
Definition tsl2591.h:261
void automatic_gain_update(uint16_t full_spectrum)
Updates the gain setting based on the most recent full spectrum reading.
Definition tsl2591.cpp:415
bool is_adc_valid()
Are the device ADC values valid?
Definition tsl2591.cpp:250
sensor::Sensor * infrared_sensor_
Definition tsl2591.h:256
float get_calculated_lux(uint16_t full_spectrum, uint16_t infrared)
Calculates and returns a lux value based on the ADC readings.
Definition tsl2591.cpp:351
sensor::Sensor * calculated_lux_sensor_
Definition tsl2591.h:258
void set_visible_sensor(sensor::Sensor *visible_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:204
void set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor)
Sets the device and glass attenuation factors.
Definition tsl2591.cpp:224
sensor::Sensor * full_spectrum_sensor_
Definition tsl2591.h:255
void set_integration_time(TSL2591IntegrationTime integration_time)
Used by ESPHome framework.
Definition tsl2591.cpp:218
void set_calculated_lux_sensor(sensor::Sensor *calculated_lux_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:210
uint32_t get_combined_illuminance()
Get the combined illuminance value.
Definition tsl2591.cpp:259
void set_name(const char *name)
Sets the name for this instance of the device.
Definition tsl2591.cpp:248
sensor::Sensor * visible_sensor_
Definition tsl2591.h:257
void set_infrared_sensor(sensor::Sensor *infrared_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:200
sensor::Sensor * actual_gain_sensor_
Definition tsl2591.h:259
void set_actual_gain_sensor(sensor::Sensor *actual_gain_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:214
void set_gain(TSL2591ComponentGain gain)
Used by ESPHome framework.
Definition tsl2591.cpp:222
void enable()
Powers on the TSL2591 device and enables its sensors.
Definition tsl2591.cpp:26
void update() override
Used by ESPHome framework.
Definition tsl2591.cpp:183
void set_integration_time_and_gain(TSL2591IntegrationTime integration_time, TSL2591Gain gain)
Set device integration time and gain.
Definition tsl2591.cpp:229
void set_full_spectrum_sensor(sensor::Sensor *full_spectrum_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:206
void disable()
Powers off the TSL2591 device.
Definition tsl2591.cpp:33
float get_actual_gain()
Reads the actual gain used.
Definition tsl2591.cpp:460
uint16_t get_illuminance(TSL2591SensorChannel channel)
Get an individual sensor channel reading.
Definition tsl2591.cpp:316
void setup() override
Used by ESPHome framework.
Definition tsl2591.cpp:45
void set_power_save_mode(bool enable)
Should the device be powered down between readings?
Definition tsl2591.cpp:246
uint16_t id
AlsGain501 gain
IntegrationTime501 integration_time
TSL2591Gain
Enum listing all gain settings for the TSL2591.
Definition tsl2591.h:44
TSL2591ComponentGain
Enum listing all gain settings for the TSL2591 component.
Definition tsl2591.h:31
TSL2591IntegrationTime
Enum listing all conversion/integration time settings for the TSL2591.
Definition tsl2591.h:17
@ TSL2591_INTEGRATION_TIME_100MS
Definition tsl2591.h:18
TSL2591SensorChannel
Enum listing sensor channels.
Definition tsl2591.h:55
@ TSL2591_SENSOR_CHANNEL_INFRARED
Definition tsl2591.h:57
@ TSL2591_SENSOR_CHANNEL_VISIBLE
Definition tsl2591.h:56
@ TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM
Definition tsl2591.h:58
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void HOT delay(uint32_t ms)
Definition core.cpp:27
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25