ESPHome 2026.11.0b6
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"
5
6namespace esphome::tsl2591 {
7
8ESPHOME_LOG_TAG(TAG, "tsl2591.sensor");
9
10static constexpr uint32_t ADC_WAIT_INTERVAL_ID = 0;
11
12// Various constants used in TSL2591 register manipulation
13#define TSL2591_COMMAND_BIT (0xA0) // 1010 0000: bits 7 and 5 for 'command, normal'
14#define TSL2591_ENABLE_POWERON (0x01) // Flag for ENABLE register, to enable
15#define TSL2591_ENABLE_POWEROFF (0x00) // Flag for ENABLE register, to disable
16#define TSL2591_ENABLE_AEN (0x02) // Flag for ENABLE register, to turn on ADCs
17
18// TSL2591 registers from the datasheet. We only define what we use.
19#define TSL2591_REGISTER_ENABLE (0x00)
20#define TSL2591_REGISTER_CONTROL (0x01)
21#define TSL2591_REGISTER_DEVICE_ID (0x12)
22#define TSL2591_REGISTER_STATUS (0x13)
23#define TSL2591_REGISTER_CHAN0_LOW (0x14)
24#define TSL2591_REGISTER_CHAN0_HIGH (0x15)
25#define TSL2591_REGISTER_CHAN1_LOW (0x16)
26#define TSL2591_REGISTER_CHAN1_HIGH (0x17)
27
29 // Enable the device by setting the control bit to 0x01. Also turn on ADCs.
30 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN)) {
31 ESP_LOGE(TAG, "I2C write failed");
32 }
33}
34
36 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWEROFF)) {
37 ESP_LOGE(TAG, "I2C write failed");
38 }
39}
40
46
48 switch (this->component_gain_) {
50 this->gain_ = TSL2591_GAIN_LOW;
51 break;
53 this->gain_ = TSL2591_GAIN_MED;
54 break;
57 break;
59 this->gain_ = TSL2591_GAIN_MAX;
60 break;
62 this->gain_ = TSL2591_GAIN_MED;
63 break;
64 }
65
66 if (!this->check_chip_id(this, TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_ID, 0x50))
67 return;
68
71}
72
74 ESP_LOGCONFIG(TAG, "TSL2591:");
75 LOG_I2C_DEVICE(this);
76
77 if (this->is_failed())
78 return;
79
80 ESP_LOGCONFIG(TAG, " Name: %s", this->name_);
82 int gain = 0;
83 std::string gain_word = "unknown";
84 switch (raw_gain) {
86 gain = 1;
87 gain_word = "low";
88 break;
90 gain = 25;
91 gain_word = "medium";
92 break;
94 gain = 400;
95 gain_word = "high";
96 break;
98 gain = 9500;
99 gain_word = "maximum";
100 break;
102 gain = -1;
103 gain_word = "auto";
104 break;
105 }
106 TSL2591IntegrationTime raw_timing = this->integration_time_;
107 int timing_ms = (1 + raw_timing) * 100;
108 ESP_LOGCONFIG(TAG,
109 " Gain: %dx (%s)"
110 " Integration Time: %d ms\n"
111 " Power save mode enabled: %s\n"
112 " Device factor: %f\n"
113 " Glass attenuation factor: %f",
114 gain, gain_word.c_str(), timing_ms, ONOFF(this->power_save_mode_enabled_), this->device_factor_,
116 LOG_SENSOR(" ", "Full spectrum:", this->full_spectrum_sensor_);
117 LOG_SENSOR(" ", "Infrared:", this->infrared_sensor_);
118 LOG_SENSOR(" ", "Visible:", this->visible_sensor_);
119 LOG_SENSOR(" ", "Calculated lux:", this->calculated_lux_sensor_);
120 LOG_SENSOR(" ", "Actual gain:", this->actual_gain_sensor_);
121
122 LOG_UPDATE_INTERVAL(this);
123}
124
126 uint32_t combined = this->get_combined_illuminance();
127 uint16_t visible = this->get_illuminance(TSL2591_SENSOR_CHANNEL_VISIBLE, combined);
128 uint16_t infrared = this->get_illuminance(TSL2591_SENSOR_CHANNEL_INFRARED, combined);
129 uint16_t full = this->get_illuminance(TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM, combined);
130 float lux = this->get_calculated_lux(full, infrared);
131 uint16_t actual_gain = this->get_actual_gain();
132 ESP_LOGD(TAG, "Got illuminance: combined 0x%" PRIX32 ", full %d, IR %d, vis %d. Calc lux: %f. Actual gain: %d.",
133 combined, full, infrared, visible, lux, actual_gain);
134 PUBLISH_STATE(this->full_spectrum_sensor_, full);
135 PUBLISH_STATE(this->infrared_sensor_, infrared);
136 PUBLISH_STATE(this->visible_sensor_, visible);
137 PUBLISH_STATE(this->calculated_lux_sensor_, lux);
138
139 if (this->component_gain_ == TSL2591_CGAIN_AUTO) {
140 this->automatic_gain_update(full);
141 }
142
143 PUBLISH_STATE(this->actual_gain_sensor_, actual_gain);
144 this->status_clear_warning();
145}
146
148 if (!this->is_adc_valid()) {
149 uint64_t now = millis();
150 ESP_LOGD(TAG, "Elapsed %3llu ms; still waiting for valid ADC", (now - this->interval_start_));
151 if (now > this->interval_timeout_) {
152 ESP_LOGW(TAG, "Interval timeout for '%s' expired before ADCs became valid", this->name_);
153 this->cancel_interval(ADC_WAIT_INTERVAL_ID);
154 }
155 return;
156 }
157 this->cancel_interval(ADC_WAIT_INTERVAL_ID);
158 this->process_update_();
159}
160
162 if (!is_failed()) {
163 if (this->power_save_mode_enabled_) {
164 // we enabled it here, else ADC will never become valid
165 // but actually doing the reads will disable device if needed
166 this->enable();
167 }
168 if (this->is_adc_valid()) {
169 this->process_update_();
170 } else {
171 this->interval_start_ = millis();
172 this->interval_timeout_ = this->interval_start_ + 620;
173 this->set_interval(ADC_WAIT_INTERVAL_ID, 100, [this] { this->interval_function_for_update_(); });
174 }
175 }
176}
177
178void TSL2591Component::set_integration_time(TSL2591IntegrationTime integration_time) {
180}
181
182void TSL2591Component::set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor) {
183 this->device_factor_ = device_factor;
184 this->glass_attenuation_factor_ = glass_attenuation_factor;
185}
186
188 this->enable();
190 this->gain_ = gain;
191 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL,
192 static_cast<uint8_t>(this->integration_time_) | static_cast<uint8_t>(this->gain_))) {
193 ESP_LOGE(TAG, "I2C write failed");
194 }
195 // The ADC values can be confused if gain or integration time are changed in the middle of a cycle.
196 // So, we unconditionally disable the device to turn the ADCs off. When re-enabling, the ADCs
197 // will tell us when they are ready again. That avoids an initial bogus reading.
198 this->disable();
199 if (!this->power_save_mode_enabled_) {
200 this->enable();
201 }
202}
203
205 uint8_t status;
206 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_STATUS, &status)) {
207 ESP_LOGE(TAG, "I2C read failed");
208 return false;
209 }
210 return status & 0x01;
211}
212
214 this->enable();
215 // Wait x ms for ADC to complete and signal valid.
216 // The max integration time is 600ms, so that's our max delay.
217 // (But we use 620ms as a bit of slack.)
218 // We'll do mini-delays and break out as soon as the ADC is good.
219 bool avalid;
220 const uint8_t mini_delay = 100;
221 for (uint16_t d = 0; d < 620; d += mini_delay) {
222 avalid = this->is_adc_valid();
223 if (avalid) {
224 break;
225 }
226 // we only log this if we need any delay, since normally we don't
227 ESP_LOGD(TAG, " after %3d ms: ADC valid? %s", d, avalid ? LOG_STR_LITERAL("true") : LOG_STR_LITERAL("false"));
228 delay(mini_delay);
229 }
230 if (!avalid) {
231 // still not valid after a sutiable delay
232 // we don't mark the device as failed since it might come around in the future (probably not :-()
233 ESP_LOGE(TAG, "Device '%s' returned invalid readings", this->name_);
235 return 0;
236 }
237
238 // CHAN0 must be read before CHAN1
239 // See: https://forums.adafruit.com/viewtopic.php?f=19&t=124176
240 // Also, low byte must be read before high byte..
241 // We read the registers in the order described in the datasheet.
242 uint32_t x32;
243 uint8_t ch0low, ch0high, ch1low, ch1high;
244 uint16_t ch0_16;
245 uint16_t ch1_16;
246 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_LOW, &ch0low)) {
247 ESP_LOGE(TAG, "I2C read failed");
248 return 0;
249 }
250 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_HIGH, &ch0high)) {
251 ESP_LOGE(TAG, "I2C read failed");
252 return 0;
253 }
254 ch0_16 = encode_uint16(ch0high, ch0low);
255 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_LOW, &ch1low)) {
256 ESP_LOGE(TAG, "I2C read failed");
257 return 0;
258 }
259 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_HIGH, &ch1high)) {
260 ESP_LOGE(TAG, "I2C read failed");
261 return 0;
262 }
263 ch1_16 = encode_uint16(ch1high, ch1low);
264 x32 = (ch1_16 << 16) | ch0_16;
265
267 return x32;
268}
269
271 uint32_t combined = this->get_combined_illuminance();
272 return this->get_illuminance(channel, combined);
273}
274// logic cloned from Adafruit TSL2591 library
275uint16_t TSL2591Component::get_illuminance(TSL2591SensorChannel channel, uint32_t combined_illuminance) {
277 // Reads two byte value from channel 0 (visible + infrared)
278 return (combined_illuminance & 0xFFFF);
279 } else if (channel == TSL2591_SENSOR_CHANNEL_INFRARED) {
280 // Reads two byte value from channel 1 (infrared)
281 return (combined_illuminance >> 16);
282 } else if (channel == TSL2591_SENSOR_CHANNEL_VISIBLE) {
283 // Reads all and subtracts out the infrared
284 uint16_t full = combined_illuminance & 0xFFFF;
285 uint16_t ir = combined_illuminance >> 16;
286 return (ir > full) ? 0 : (full - ir);
287 }
288 // unknown channel!
289 ESP_LOGE(TAG, "get_illuminance() caller requested an unknown channel: %d", channel);
290 return 0;
291}
292
307float TSL2591Component::get_calculated_lux(uint16_t full_spectrum, uint16_t infrared) {
308 // Check for overflow conditions first
309 uint16_t max_count = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS ? 36863 : 65535);
310 if ((full_spectrum == max_count) || (infrared == max_count)) {
311 // Signal an overflow
312 ESP_LOGW(TAG, "Apparent saturation on '%s'; try reducing the gain or integration time", this->name_);
313 return NAN;
314 }
315
316 if ((full_spectrum == 0) && (infrared == 0)) {
317 // trivial conversion; avoids divide by 0
318 ESP_LOGW(TAG, "Zero reading on both '%s' sensors", this->name_);
319 return 0.0F;
320 }
321
322 float atime = 100.F + (this->integration_time_ * 100);
323
324 float again;
325 switch (this->gain_) {
326 case TSL2591_GAIN_LOW:
327 again = 1.0F;
328 break;
329 case TSL2591_GAIN_MED:
330 again = 25.0F;
331 break;
333 again = 400.0F;
334 break;
335 case TSL2591_GAIN_MAX:
336 again = 9500.0F;
337 break;
338 default:
339 again = 1.0F;
340 break;
341 }
342 // This lux equation is copied from the Adafruit TSL2591 v1.4.0 and modified slightly.
343 // See: https://github.com/adafruit/Adafruit_TSL2591_Library/issues/14
344 // and that library code.
345 // They said:
346 // Note: This algorithm is based on preliminary coefficients
347 // provided by AMS and may need to be updated in the future
348 // However, we use gain multipliers that are more in line with the midpoints
349 // of ranges from the datasheet. We don't know why the other libraries
350 // used the values they did for HIGH and MAX.
351 // If cpl or full_spectrum are 0, this will return NaN due to divide by 0.
352 // For the curious "cpl" is counts per lux, a term used in AMS application notes.
353 float cpl = (atime * again) / (this->device_factor_ * this->glass_attenuation_factor_);
354 float lux = (((float) full_spectrum - (float) infrared)) * (1.0F - ((float) infrared / (float) full_spectrum)) / cpl;
355 return std::max(lux, 0.0F);
356}
357
371void TSL2591Component::automatic_gain_update(uint16_t full_spectrum) {
372 TSL2591Gain new_gain = this->gain_;
373 uint fs_divider = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS) ? 2 : 1;
374
375 switch (this->gain_) {
376 case TSL2591_GAIN_LOW:
377 if (full_spectrum < 54) { // 1/3 FS / GAIN_HIGH
378 new_gain = TSL2591_GAIN_HIGH;
379 } else if (full_spectrum < 875) { // 1/3 FS / GAIN_MED
380 new_gain = TSL2591_GAIN_MED;
381 }
382 break;
383 case TSL2591_GAIN_MED:
384 if (full_spectrum < 57) { // 1/3 FS / (GAIN_MAX/GAIN_MED)
385 new_gain = TSL2591_GAIN_MAX;
386 } else if (full_spectrum < 1365) { // 1/3 FS / (GAIN_HIGH/GAIN_MED)
387 new_gain = TSL2591_GAIN_HIGH;
388 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_LOW/GAIN_MED) clipped to 95% FS
389 new_gain = TSL2591_GAIN_LOW;
390 }
391 break;
393 if (full_spectrum < 920) { // 1/3 FS / (GAIN_MAX/GAIN_HIGH)
394 new_gain = TSL2591_GAIN_MAX;
395 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
396 new_gain = TSL2591_GAIN_LOW;
397 }
398 break;
399 case TSL2591_GAIN_MAX:
400 if (full_spectrum > 62000 / fs_divider) // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
401 new_gain = TSL2591_GAIN_MED;
402 break;
403 }
404
405 if (this->gain_ != new_gain) {
406 this->gain_ = new_gain;
408 }
409 ESP_LOGD(TAG, "Gain setting: %d", this->gain_);
410}
411
417 switch (this->gain_) {
418 case TSL2591_GAIN_LOW:
419 return 1.0F;
420 case TSL2591_GAIN_MED:
421 return 25.0F;
423 return 400.0F;
424 case TSL2591_GAIN_MAX:
425 return 9500.0F;
426 default:
427 // Shouldn't get here, but just in case.
428 return NAN;
429 }
430}
431
432} // namespace esphome::tsl2591
uint8_t status
Definition bl0942.h:8
bool is_failed() const
Definition component.h:287
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
void status_clear_warning()
Definition component.h:309
bool check_chip_id(Component *component, uint8_t a_register, uint8_t expected, uint8_t mask=0xFF)
Read the 8-bit ID at a_register and accept it when it matches expected in the bits set in mask.
Definition i2c.h:232
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:312
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:272
TSL2591IntegrationTime integration_time_
Definition tsl2591.h:254
void dump_config() override
Used by ESPHome framework.
Definition tsl2591.cpp:73
TSL2591ComponentGain component_gain_
Definition tsl2591.h:255
void automatic_gain_update(uint16_t full_spectrum)
Updates the gain setting based on the most recent full spectrum reading.
Definition tsl2591.cpp:371
bool is_adc_valid()
Are the device ADC values valid?
Definition tsl2591.cpp:204
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:307
void set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor)
Sets the device and glass attenuation factors.
Definition tsl2591.cpp:182
uint32_t get_combined_illuminance()
Get the combined illuminance value.
Definition tsl2591.cpp:213
void enable()
Powers on the TSL2591 device and enables its sensors.
Definition tsl2591.cpp:28
void update() override
Used by ESPHome framework.
Definition tsl2591.cpp:161
void set_integration_time_and_gain(TSL2591IntegrationTime integration_time, TSL2591Gain gain)
Set device integration time and gain.
Definition tsl2591.cpp:187
void disable()
Powers off the TSL2591 device.
Definition tsl2591.cpp:35
float get_actual_gain()
Reads the actual gain used.
Definition tsl2591.cpp:416
uint16_t get_illuminance(TSL2591SensorChannel channel)
Get an individual sensor channel reading.
Definition tsl2591.cpp:270
void setup() override
Used by ESPHome framework.
Definition tsl2591.cpp:47
AlsGain501 gain
IntegrationTime501 integration_time
TSL2591Gain
Enum listing all gain settings for the TSL2591.
Definition tsl2591.h:43
TSL2591ComponentGain
Enum listing all gain settings for the TSL2591 component.
Definition tsl2591.h:30
TSL2591IntegrationTime
Enum listing all conversion/integration time settings for the TSL2591.
Definition tsl2591.h:16
@ TSL2591_INTEGRATION_TIME_100MS
Definition tsl2591.h:17
TSL2591SensorChannel
Enum listing sensor channels.
Definition tsl2591.h:54
@ TSL2591_SENSOR_CHANNEL_INFRARED
Definition tsl2591.h:56
@ TSL2591_SENSOR_CHANNEL_VISIBLE
Definition tsl2591.h:55
@ TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM
Definition tsl2591.h:57
ESPHOME_LOG_TAG(TAG, "tsl2591.sensor")
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:1043
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t