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