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