ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
tcs34725.cpp
Go to the documentation of this file.
1#include "tcs34725.h"
2#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
5#include <algorithm>
6
8
9ESPHOME_LOG_TAG(TAG, "tcs34725");
10
11static const uint8_t TCS34725_ADDRESS = 0x29;
12static const uint8_t TCS34725_COMMAND_BIT = 0x80;
13static const uint8_t TCS34725_REGISTER_ID = TCS34725_COMMAND_BIT | 0x12;
14static const uint8_t TCS34725_REGISTER_ATIME = TCS34725_COMMAND_BIT | 0x01;
15static const uint8_t TCS34725_REGISTER_CONTROL = TCS34725_COMMAND_BIT | 0x0F;
16static const uint8_t TCS34725_REGISTER_ENABLE = TCS34725_COMMAND_BIT | 0x00;
17static const uint8_t TCS34725_REGISTER_CRGBDATAL = TCS34725_COMMAND_BIT | 0x14;
18
20 uint8_t id;
21 if (this->read_register(TCS34725_REGISTER_ID, &id, 1) != i2c::ERROR_OK) {
22 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
23 return;
24 }
25 if (this->write_config_register_(TCS34725_REGISTER_ATIME, this->integration_reg_) != i2c::ERROR_OK ||
26 this->write_config_register_(TCS34725_REGISTER_CONTROL, this->gain_reg_) != i2c::ERROR_OK) {
27 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
28 return;
29 }
30 if (this->write_config_register_(TCS34725_REGISTER_ENABLE, 0x01) !=
31 i2c::ERROR_OK) { // Power on (internal oscillator on)
32 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
33 return;
34 }
35 delay(3);
36 if (this->write_config_register_(TCS34725_REGISTER_ENABLE, 0x03) !=
37 i2c::ERROR_OK) { // Power on (internal oscillator on) + RGBC ADC Enable
38 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
39 return;
40 }
41}
42
44 ESP_LOGCONFIG(TAG, "TCS34725:");
45 LOG_I2C_DEVICE(this);
46 LOG_UPDATE_INTERVAL(this);
47
48 LOG_SENSOR(" ", "Clear Channel", this->clear_sensor_);
49 LOG_SENSOR(" ", "Red Channel", this->red_sensor_);
50 LOG_SENSOR(" ", "Green Channel", this->green_sensor_);
51 LOG_SENSOR(" ", "Blue Channel", this->blue_sensor_);
52 LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_);
53 LOG_SENSOR(" ", "Color Temperature", this->color_temperature_sensor_);
54}
55
69void TCS34725Component::calculate_temperature_and_lux_(uint16_t r, uint16_t g, uint16_t b, uint16_t c) {
70 float sat; /* Digital saturation level */
71
72 this->illuminance_ = NAN;
73 this->color_temperature_ = NAN;
74
75 const float ga = this->glass_attenuation_; // Glass Attenuation Factor
76 static const float DF = 310.f; // Device Factor
77 static const float R_COEF = 0.136f; //
78 static const float G_COEF = 1.f; // used in lux computation
79 static const float B_COEF = -0.444f; //
80 static const float CT_COEF = 3810.f; // Color Temperature Coefficient
81 static const float CT_OFFSET = 1391.f; // Color Temperatuer Offset
82 static const float MAX_ILLUMINANCE = 100000.0f; // Cap illuminance at 100,000 lux
83 static const float MAX_COLOR_TEMPERATURE = 15000.0f; // Maximum expected color temperature in Kelvin
84 static const float MIN_COLOR_TEMPERATURE = 1000.0f; // Maximum reasonable color temperature in Kelvin
85
86 if (c == 0) {
87 return;
88 }
89
90 /* Analog/Digital saturation:
91 *
92 * (a) As light becomes brighter, the clear channel will tend to
93 * saturate first since R+G+B is approximately equal to C.
94 * (b) The TCS34725 accumulates 1024 counts per 2.4ms of integration
95 * time, up to a maximum values of 65535. This means analog
96 * saturation can occur up to an integration time of 153.6ms
97 * (64*2.4ms=153.6ms).
98 * (c) If the integration time is > 153.6ms, digital saturation will
99 * occur before analog saturation. Digital saturation occurs when
100 * the count reaches 65535.
101 */
102 if ((256 - this->integration_reg_) > 63) {
103 /* Track digital saturation */
104 sat = 65535.f;
105 } else {
106 /* Track analog saturation */
107 sat = 1024.f * (256.f - this->integration_reg_);
108 }
109
110 /* Ripple rejection:
111 *
112 * (a) An integration time of 50ms or multiples of 50ms are required to
113 * reject both 50Hz and 60Hz ripple.
114 * (b) If an integration time faster than 50ms is required, you may need
115 * to average a number of samples over a 50ms period to reject ripple
116 * from fluorescent and incandescent light sources.
117 *
118 * Ripple saturation notes:
119 *
120 * (a) If there is ripple in the received signal, the value read from C
121 * will be less than the max, but still have some effects of being
122 * saturated. This means that you can be below the 'sat' value, but
123 * still be saturating. At integration times >150ms this can be
124 * ignored, but <= 150ms you should calculate the 75% saturation
125 * level to avoid this problem.
126 */
127 if (this->integration_time_ < 150) {
128 /* Adjust sat to 75% to avoid analog saturation if atime < 153.6ms */
129 sat -= sat / 4.f;
130 }
131 /* Check for saturation and mark the sample as invalid if true */
132 if (c >= sat) {
133 if (this->integration_time_auto_) {
134 ESP_LOGI(TAG, "Saturation too high, sample discarded, autogain ongoing");
135 return;
136 } else {
137 ESP_LOGW(TAG,
138 "Saturation too high, sample with saturation %.1f and clear %d lux/color temperature cannot reliably "
139 "calculated, reduce integration/gain or use a grey filter.",
140 sat, c);
141 return;
142 }
143 }
144
145 // Lux Calculation (DN40 3.2)
146
147 float g1 = R_COEF * (float) r + G_COEF * (float) g + B_COEF * (float) b;
148 float cpl = (this->integration_time_ * this->gain_) / (ga * DF);
149
150 this->illuminance_ = std::max(g1 / cpl, 0.0f);
151
152 if (this->illuminance_ > MAX_ILLUMINANCE) {
153 ESP_LOGW(TAG, "Calculated illuminance greater than limit (%f), setting to NAN", this->illuminance_);
154 this->illuminance_ = NAN;
155 return;
156 }
157
158 if (r == 0) {
159 ESP_LOGW(TAG, "Red channel is zero, cannot compute color temperature");
160 return;
161 }
162
163 // Color Temperature Calculation (DN40)
164 /* A simple method of measuring color temp is to use the ratio of blue */
165 /* to red light. */
166
167 this->color_temperature_ = (CT_COEF * (float) b) / (float) r + CT_OFFSET;
168
169 // Ensure the color temperature stays within reasonable bounds
170 if (this->color_temperature_ < MIN_COLOR_TEMPERATURE) {
171 ESP_LOGW(TAG, "Calculated color temperature value too low (%f), setting to NAN", this->color_temperature_);
172 this->color_temperature_ = NAN;
173 } else if (this->color_temperature_ > MAX_COLOR_TEMPERATURE) {
174 ESP_LOGW(TAG, "Calculated color temperature value too high (%f), setting to NAN", this->color_temperature_);
175 this->color_temperature_ = NAN;
176 }
177}
178
180 uint16_t data[4]; // Clear, red, green and blue channels
181
182 // Perform burst
183 if (!this->read_bytes_16_le(TCS34725_REGISTER_CRGBDATAL, data, 4)) {
184 this->status_set_warning();
185 ESP_LOGW(TAG, "Error reading TCS34725 sensor data");
186 return;
187 }
188
189 // Extract the data
190 uint16_t raw_c = data[0]; // Clear channel
191 uint16_t raw_r = data[1]; // Red channel
192 uint16_t raw_g = data[2]; // Green channel
193 uint16_t raw_b = data[3]; // Blue channel
194
195 ESP_LOGV(TAG, "Raw values clear=%d red=%d green=%d blue=%d", raw_c, raw_r, raw_g, raw_b);
196
197 float channel_c;
198 float channel_r;
199 float channel_g;
200 float channel_b;
201 // avoid division by 0 and return black if clear is 0
202 if (raw_c == 0) {
203 channel_c = channel_r = channel_g = channel_b = 0.0f;
204 } else {
205 float max_count = this->integration_time_ <= 153.6f ? this->integration_time_ * 1024.0f / 2.4f : 65535.0f;
206 float sum = raw_c;
207 channel_r = raw_r / sum * 100.0f;
208 channel_g = raw_g / sum * 100.0f;
209 channel_b = raw_b / sum * 100.0f;
210 channel_c = raw_c / max_count * 100.0f;
211 }
212
213 if (this->clear_sensor_ != nullptr)
214 this->clear_sensor_->publish_state(channel_c);
215 if (this->red_sensor_ != nullptr)
216 this->red_sensor_->publish_state(channel_r);
217 if (this->green_sensor_ != nullptr)
218 this->green_sensor_->publish_state(channel_g);
219 if (this->blue_sensor_ != nullptr)
220 this->blue_sensor_->publish_state(channel_b);
221
223 calculate_temperature_and_lux_(raw_r, raw_g, raw_b, raw_c);
224 }
225
226 // do not publish values if auto gain finding ongoing, and oversaturated
227 // so: publish when:
228 // - not auto mode
229 // - clear not oversaturated
230 // - clear oversaturated but gain and timing cannot go lower
231 if (!this->integration_time_auto_ || raw_c < 65530 || (this->gain_reg_ == 0 && this->integration_time_ < 200)) {
232 if (this->illuminance_sensor_ != nullptr)
234
235 if (this->color_temperature_sensor_ != nullptr)
237 }
238
239 ESP_LOGD(TAG,
240 "Got Red=%.1f%%,Green=%.1f%%,Blue=%.1f%%,Clear=%.1f%% Illuminance=%.1flx Color "
241 "Temperature=%.1fK",
242 channel_r, channel_g, channel_b, channel_c, this->illuminance_, this->color_temperature_);
243
244 if (this->integration_time_auto_) {
245 // change integration time an gain to achieve maximum resolution an dynamic range
246 // calculate optimal integration time to achieve 70% satuaration
247 float integration_time_ideal;
248
249 integration_time_ideal = 60 / ((float) std::max((uint16_t) 1, raw_c) / 655.35f) * this->integration_time_;
250
251 uint8_t gain_reg_val_new = this->gain_reg_;
252 // increase gain if less than 20% of white channel used and high integration time
253 // increase only if not already maximum
254 // do not use max gain, as ist will not get better
255 if (this->gain_reg_ < 3) {
256 if (((float) raw_c / 655.35f < 20.f) && (this->integration_time_ > 600.f)) {
257 gain_reg_val_new = this->gain_reg_ + 1;
258 // update integration time to new situation
259 integration_time_ideal = integration_time_ideal / 4;
260 }
261 }
262
263 // decrease gain, if very high clear values and integration times alreadey low
264 if (this->gain_reg_ > 0) {
265 if (70 < ((float) raw_c / 655.35f) && (this->integration_time_ < 200)) {
266 gain_reg_val_new = this->gain_reg_ - 1;
267 // update integration time to new situation
268 integration_time_ideal = integration_time_ideal * 4;
269 }
270 }
271
272 // saturate integration times
273 float integration_time_next = integration_time_ideal;
274 if (integration_time_ideal > 2.4f * 256) {
275 integration_time_next = 2.4f * 256;
276 }
277 if (integration_time_ideal < 154) {
278 integration_time_next = 154;
279 }
280
281 // calculate register value from timing
282 uint8_t regval_atime = (uint8_t) (256.f - integration_time_next / 2.4f);
283 ESP_LOGD(TAG, "Integration time: %.1fms, ideal: %.1fms regval_new %d Gain: %.f Clear channel raw: %d gain reg: %d",
284 this->integration_time_, integration_time_next, regval_atime, this->gain_, raw_c, this->gain_reg_);
285
286 if (this->integration_reg_ != regval_atime || gain_reg_val_new != this->gain_reg_) {
287 this->integration_reg_ = regval_atime;
288 this->gain_reg_ = gain_reg_val_new;
289 set_gain((TCS34725Gain) gain_reg_val_new);
290 if (this->write_config_register_(TCS34725_REGISTER_ATIME, this->integration_reg_) != i2c::ERROR_OK ||
291 this->write_config_register_(TCS34725_REGISTER_CONTROL, this->gain_reg_) != i2c::ERROR_OK) {
292 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
293 ESP_LOGW(TAG, "TCS34725I update timing failed!");
294 } else {
295 this->integration_time_ = integration_time_next;
296 }
297 }
298 }
299 this->status_clear_warning();
300}
302 // if an integration time is 0x100, this is auto start with 154ms as this gives best starting point
303 TCS34725IntegrationTime my_integration_time_regval;
304
306 this->integration_time_auto_ = true;
307 this->integration_reg_ = TCS34725_INTEGRATION_TIME_154MS;
308 my_integration_time_regval = TCS34725_INTEGRATION_TIME_154MS;
309 } else {
310 this->integration_reg_ = integration_time;
311 my_integration_time_regval = integration_time;
312 this->integration_time_auto_ = false;
313 }
314 this->integration_time_ = (256.f - (float) my_integration_time_regval) * 2.4f;
315 ESP_LOGI(TAG, "TCS34725I Integration time set to: %.1fms", this->integration_time_);
316}
318 this->gain_reg_ = gain;
319 switch (gain) {
321 this->gain_ = 1.f;
322 break;
324 this->gain_ = 4.f;
325 break;
327 this->gain_ = 16.f;
328 break;
330 this->gain_ = 60.f;
331 break;
332 default:
333 this->gain_ = 1.f;
334 break;
335 }
336}
337
339 // The Glass Attenuation (FA) factor used to compensate for lower light
340 // levels at the device due to the possible presence of glass. The GA is
341 // the inverse of the glass transmissivity (T), so GA = 1/T. A transmissivity
342 // of 50% gives GA = 1 / 0.50 = 2. If no glass is present, use GA = 1.
343 // See Application Note: DN40-Rev 1.0
344 this->glass_attenuation_ = ga;
345}
346
347} // namespace esphome::tcs34725
void mark_failed()
Mark this component as failed.
void status_clear_warning()
Definition component.h:296
bool read_bytes_16_le(uint8_t a_register, uint16_t *data, uint8_t len)
Read len 16-bit values stored least significant byte first; no conversion is compiled on little-endia...
Definition i2c.h:284
ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len)
reads an array of bytes from a specific register in the I²C device
Definition i2c.cpp:28
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
sensor::Sensor * illuminance_sensor_
Definition tcs34725.h:72
i2c::ErrorCode write_config_register_(uint8_t a_register, uint8_t data)
Definition tcs34725.h:65
void set_integration_time(TCS34725IntegrationTime integration_time)
Definition tcs34725.cpp:301
void set_gain(TCS34725Gain gain)
Definition tcs34725.cpp:317
sensor::Sensor * color_temperature_sensor_
Definition tcs34725.h:73
uint16_t id
AlsGain501 gain
IntegrationTime501 integration_time
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
FLAG_HAS_TRANSITION float
static float float b
@ TCS34725_INTEGRATION_TIME_154MS
Definition tcs34725.h:15
@ TCS34725_INTEGRATION_TIME_AUTO
Definition tcs34725.h:28
ESPHOME_LOG_TAG(TAG, "tcs34725")
void HOT delay(uint32_t ms)
Definition hal.cpp:85