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