ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
apds9960.cpp
Go to the documentation of this file.
1#include "apds9960.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
4
6
7ESPHOME_LOG_TAG(TAG, "apds9960");
8
9#define APDS9960_ERROR_CHECK(func) \
10 if (!(func)) { \
11 this->mark_failed(LOG_STR("Setting up APDS9960 registers failed")); \
12 return; \
13 }
14
15static constexpr i2c::I2CRegValue APDS9960_TIMING[] PROGMEM = {
16 // ATime (ADC integration time, 2.78ms increments, 0x81) -> 0xDB (103ms)
17 {0x81, 0xDB},
18 // WTime (Wait time, 0x83) -> 0xF6 (27ms)
19 {0x83, 0xF6},
20 // PPulse (0x8E) -> 0x87 (16us, 8 pulses)
21 {0x8E, 0x87},
22 // POffset UR (0x9D) -> 0 (no offset)
23 {0x9D, 0x00},
24 // POffset DL (0x9E) -> 0 (no offset)
25 {0x9E, 0x00},
26 // Config 1 (0x8D) -> 0x60 (no wtime factor)
27 {0x8D, 0x60},
28};
29
30static constexpr i2c::I2CRegValue APDS9960_INTERRUPT_GESTURE[] PROGMEM = {
31 // Pers (0x8C) -> 0x11 (2 consecutive proximity or ALS for interrupt)
32 {0x8C, 0x11},
33 // Config 2 (0x90) -> 0x01 (no saturation interrupts or LED boost)
34 {0x90, 0x01},
35 // Config 3 (0x9F) -> 0x00 (enable all photodiodes, no SAI)
36 {0x9F, 0x00},
37 // GPenTh (0xA0, gesture enter threshold) -> 0x28 (also 0x32)
38 {0xA0, 0x28},
39 // GPexTh (0xA1, gesture exit threshold) -> 0x1E
40 {0xA1, 0x1E},
41 // GConf 1 (0xA2, gesture config 1) -> 0x40 (4 gesture events for interrupt (GFIFO 3), 1 for exit)
42 {0xA2, 0x40},
43};
44
45static constexpr i2c::I2CRegValue APDS9960_GESTURE_OFFSETS[] PROGMEM = {
46 // GOffsetU (0xA4) -> 0x00 (no offset)
47 {0xA4, 0x00},
48 // GOffsetD (0xA5) -> 0x00 (no offset)
49 {0xA5, 0x00},
50 // GOffsetL (0xA7) -> 0x00 (no offset)
51 {0xA7, 0x00},
52 // GOffsetR (0xA9) -> 0x00 (no offset)
53 {0xA9, 0x00},
54 // GPulse (0xA6) -> 0xC9 (32 µs, 10 pulses)
55 {0xA6, 0xC9},
56 // GConf 3 (0xAA, gesture config 3) -> 0x00 (all photodiodes active during gesture, all gesture dimensions enabled)
57 // 0x00 -> all dimensions, 0x01 -> up down, 0x02 -> left right
58 {0xAA, 0x00},
59};
60
61void APDS9960::setup() {
62 uint8_t id;
63 if (!this->read_byte(0x92, &id)) { // ID register
64 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
65 return;
66 }
67
68 if (id != 0xAB && id != 0x9C && id != 0xA8 && id != 0x9E) { // APDS9960 all should have one of these IDs
69 this->mark_failed(LOG_STR("APDS9960 has invalid id"));
70 return;
71 }
72
73 APDS9960_ERROR_CHECK(this->write_registers(APDS9960_TIMING));
74
75 // Control (0x8F): led drive (0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA),
76 // proximity gain (0 -> 1x, 1 -> 2X, 2 -> 4X, 3 -> 8X), ambient light gain (0 -> 1x, 1 -> 4x, 2 -> 16x, 3 -> 64x)
77 APDS9960_ERROR_CHECK(this->update_register(
78 0x8F, 0b11001111,
79 (this->led_drive_ & 0b11) << 6 | (this->proximity_gain_ & 0b11) << 2 | (this->ambient_gain_ & 0b11)));
80
81 APDS9960_ERROR_CHECK(this->write_registers(APDS9960_INTERRUPT_GESTURE));
82
83 // GConf 2 (0xA3): gesture gain (0 -> 1x, 1 -> 2x, 2 -> 4x, 3 -> 8x),
84 // gesture led drive (0 -> 100mA, 1 -> 50mA, 2 -> 25mA, 3 -> 12.5mA), gesture wait time
85 // (0 -> 0ms, 1 -> 2.8ms, 2 -> 5.6ms, 3 -> 8.4ms, 4 -> 14.0ms, 5 -> 22.4 ms, 6 -> 30.8ms, 7 -> 39.2 ms)
86 APDS9960_ERROR_CHECK(this->update_register(
87 0xA3, 0b01111111,
88 (this->gesture_gain_ & 0b11) << 5 | (this->gesture_led_drive_ & 0b11) << 3 | (this->gesture_wait_time_ & 0b111)));
89
90 APDS9960_ERROR_CHECK(this->write_registers(APDS9960_GESTURE_OFFSETS));
91
92 // Enable (0x80) ->
93 uint8_t val = 0;
94 val |= (0b1) << 0; // power on
95 val |= (this->is_color_enabled_() & 0b1) << 1;
96 val |= (this->is_proximity_enabled_() & 0b1) << 2;
97 val |= 0b0 << 3; // wait timer disabled
98 val |= 0b0 << 4; // color interrupt disabled
99 val |= 0b0 << 5; // proximity interrupt disabled
100 val |= (this->is_gesture_enabled_() & 0b1) << 6; // proximity is required for gestures
101 APDS9960_ERROR_CHECK(this->write_byte(0x80, val));
102}
104#ifdef USE_SENSOR
105 return this->red_sensor_ != nullptr || this->green_sensor_ != nullptr || this->blue_sensor_ != nullptr ||
106 this->clear_sensor_ != nullptr;
107#else
108 return false;
109#endif
110}
111
112void APDS9960::dump_config() {
113 ESP_LOGCONFIG(TAG, "APDS9960:");
114 LOG_I2C_DEVICE(this);
115
116 LOG_UPDATE_INTERVAL(this);
117
118#ifdef USE_SENSOR
119 LOG_SENSOR(" ", "Red channel", this->red_sensor_);
120 LOG_SENSOR(" ", "Green channel", this->green_sensor_);
121 LOG_SENSOR(" ", "Blue channel", this->blue_sensor_);
122 LOG_SENSOR(" ", "Clear channel", this->clear_sensor_);
123 LOG_SENSOR(" ", "Proximity", this->proximity_sensor_);
124#endif
125}
126
127#define APDS9960_WARNING_CHECK(func, warning) \
128 if (!(func)) { \
129 ESP_LOGW(TAG, warning); \
130 this->status_set_warning(); \
131 return; \
132 }
133
134void APDS9960::update() {
135 uint8_t status;
136 APDS9960_WARNING_CHECK(this->read_byte(0x93, &status), "Reading status bit failed.");
137 this->status_clear_warning();
138
139 this->read_color_data_(status);
140 this->read_proximity_data_(status);
141}
142
143void APDS9960::loop() { this->read_gesture_data_(); }
144
145void APDS9960::read_color_data_(uint8_t status) {
146 if (!this->is_color_enabled_())
147 return;
148
149 if ((status & 0x01) == 0x00) {
150 // color data not ready yet.
151 return;
152 }
153
154 uint16_t raw[4];
155 APDS9960_WARNING_CHECK(this->read_bytes_16_le(0x94, raw, 4), "Reading color values failed.");
156
157 uint16_t uint_clear = raw[0];
158 uint16_t uint_red = raw[1];
159 uint16_t uint_green = raw[2];
160 uint16_t uint_blue = raw[3];
161
162 float clear_perc = (uint_clear / float(UINT16_MAX)) * 100.0f;
163 float red_perc = (uint_red / float(UINT16_MAX)) * 100.0f;
164 float green_perc = (uint_green / float(UINT16_MAX)) * 100.0f;
165 float blue_perc = (uint_blue / float(UINT16_MAX)) * 100.0f;
166
167 ESP_LOGD(TAG, "Got clear=%.1f%% red=%.1f%% green=%.1f%% blue=%.1f%%", clear_perc, red_perc, green_perc, blue_perc);
168#ifdef USE_SENSOR
169 PUBLISH_STATE(this->clear_sensor_, clear_perc);
170 PUBLISH_STATE(this->red_sensor_, red_perc);
171 PUBLISH_STATE(this->green_sensor_, green_perc);
172 PUBLISH_STATE(this->blue_sensor_, blue_perc);
173#endif
174}
175void APDS9960::read_proximity_data_(uint8_t status) {
176#ifndef USE_SENSOR
177 return;
178#else
179 if (this->proximity_sensor_ == nullptr)
180 return;
181
182 if ((status & 0b10) == 0x00) {
183 // proximity data not ready yet.
184 return;
185 }
186
187 uint8_t prox;
188 APDS9960_WARNING_CHECK(this->read_byte(0x9C, &prox), "Reading proximity values failed.");
189
190 float prox_perc = (prox / float(UINT8_MAX)) * 100.0f;
191 ESP_LOGD(TAG, "Got proximity=%.1f%%", prox_perc);
192 this->proximity_sensor_->publish_state(prox_perc);
193#endif
194}
196 if (!this->is_gesture_enabled_())
197 return;
198
199 uint8_t status;
200 APDS9960_WARNING_CHECK(this->read_byte(0xAF, &status), "Reading gesture status failed.");
201
202 if ((status & 0b01) == 0) {
203 // GVALID is false
204 return;
205 }
206
207 if ((status & 0b10) == 0b10) {
208 ESP_LOGV(TAG, "FIFO buffer has filled to capacity!");
209 }
210
211 uint8_t fifo_level;
212 APDS9960_WARNING_CHECK(this->read_byte(0xAE, &fifo_level), "Reading FIFO level failed.");
213 if (fifo_level == 0) {
214 // no data to process
215 return;
216 }
217
218 APDS9960_WARNING_CHECK(fifo_level <= 32, "FIFO level has invalid value.")
219
220 uint8_t buf[128];
221 for (uint8_t pos = 0; pos < fifo_level * 4; pos += 32) {
222 // Read in 32-byte chunks due to ESP8266 I2C buffer limit.
223 // Always read from 0xFC — the FIFO auto-increments through 0xFC-0xFF
224 // and advances its internal pointer after every 4th byte.
225 uint8_t read = std::min(32, fifo_level * 4 - pos);
226 APDS9960_WARNING_CHECK(this->read_bytes(0xFC, buf + pos, read), "Reading FIFO buffer failed.");
227 }
228
229 if (millis() - this->gesture_start_ > 500) {
230 this->gesture_up_started_ = false;
231 this->gesture_down_started_ = false;
232 this->gesture_left_started_ = false;
233 this->gesture_right_started_ = false;
234 }
235
236 for (uint32_t i = 0; i < fifo_level * 4; i += 4) {
237 const int up = buf[i + 0]; // NOLINT
238 const int down = buf[i + 1];
239 const int left = buf[i + 2];
240 const int right = buf[i + 3];
241 this->process_dataset_(up, down, left, right);
242 }
243}
244void APDS9960::report_gesture_(int gesture) {
245#ifdef USE_BINARY_SENSOR
247 switch (gesture) {
248 case 1:
249 bin = this->up_direction_binary_sensor_;
250 this->gesture_up_started_ = false;
251 this->gesture_down_started_ = false;
252 ESP_LOGD(TAG, "Got gesture UP");
253 break;
254 case 2:
255 bin = this->down_direction_binary_sensor_;
256 this->gesture_up_started_ = false;
257 this->gesture_down_started_ = false;
258 ESP_LOGD(TAG, "Got gesture DOWN");
259 break;
260 case 3:
261 bin = this->left_direction_binary_sensor_;
262 this->gesture_left_started_ = false;
263 this->gesture_right_started_ = false;
264 ESP_LOGD(TAG, "Got gesture LEFT");
265 break;
266 case 4:
267 bin = this->right_direction_binary_sensor_;
268 this->gesture_left_started_ = false;
269 this->gesture_right_started_ = false;
270 ESP_LOGD(TAG, "Got gesture RIGHT");
271 break;
272 default:
273 return;
274 }
275
276 if (bin != nullptr) {
277 bin->publish_state(true);
278 bin->publish_state(false);
279 }
280#endif
281}
282void APDS9960::process_dataset_(int up, int down, int left, int right) {
283 /* Algorithm: (see Figure 11 in datasheet)
284 *
285 * Observation: When a gesture is started, we will see a short amount of time where
286 * the photodiode in the direction of the motion has a much higher count value
287 * than where the gesture originates.
288 *
289 * In this algorithm we continually check the difference between the count values of opposing
290 * directions. For example in the down/up direction we continually look at the difference of the
291 * up count and down count. When DOWN gesture begins, this difference will be positive with a
292 * high magnitude for a short amount of time (magic value here is the difference is at least 13).
293 *
294 * If we see such a pattern, we store that we saw the first part of a gesture (the leading edge).
295 * After that some time can pass during which the difference is zero again (though the count values
296 * are not zero). At the end of a gesture, we will see this difference go into the opposite direction
297 * for a short period of time.
298 *
299 * If a gesture is not ended within 500 milliseconds, we consider the initial trailing edge invalid
300 * and reset the state.
301 *
302 * This algorithm does work, but not too well. Some good signal processing algorithms could
303 * probably improve this a lot, especially since the incoming signal has such a characteristic
304 * and quite noise-free pattern.
305 */
306 const int up_down_delta = up - down;
307 const int left_right_delta = left - right;
308 const bool up_down_significant = abs(up_down_delta) > 13;
309 const bool left_right_significant = abs(left_right_delta) > 13;
310
311 if (up_down_significant) {
312 if (up_down_delta < 0) {
313 if (this->gesture_up_started_) {
314 // trailing edge of gesture up
315 this->report_gesture_(1); // UP
316 } else {
317 // leading edge of gesture down
318 this->gesture_down_started_ = true;
319 this->gesture_start_ = millis();
320 }
321 } else {
322 if (this->gesture_down_started_) {
323 // trailing edge of gesture down
324 this->report_gesture_(2); // DOWN
325 } else {
326 // leading edge of gesture up
327 this->gesture_up_started_ = true;
328 this->gesture_start_ = millis();
329 }
330 }
331 }
332
333 if (left_right_significant) {
334 if (left_right_delta < 0) {
335 if (this->gesture_left_started_) {
336 // trailing edge of gesture left
337 this->report_gesture_(3); // LEFT
338 } else {
339 // leading edge of gesture right
340 this->gesture_right_started_ = true;
341 this->gesture_start_ = millis();
342 }
343 } else {
344 if (this->gesture_right_started_) {
345 // trailing edge of gesture right
346 this->report_gesture_(4); // RIGHT
347 } else {
348 // leading edge of gesture left
349 this->gesture_left_started_ = true;
350 this->gesture_start_ = millis();
351 }
352 }
353 }
354}
356 return
357#ifdef USE_SENSOR
358 this->proximity_sensor_ != nullptr
359#else
360 false
361#endif
362 || this->is_gesture_enabled_();
363}
365#ifdef USE_BINARY_SENSOR
366 return this->up_direction_binary_sensor_ != nullptr || this->left_direction_binary_sensor_ != nullptr ||
367 this->down_direction_binary_sensor_ != nullptr || this->right_direction_binary_sensor_ != nullptr;
368#else
369 return false;
370#endif
371}
372
373} // namespace esphome::apds9960
uint8_t raw[35]
Definition bl0939.h:0
uint8_t status
Definition bl0942.h:8
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void status_clear_warning()
Definition component.h:309
void read_proximity_data_(uint8_t status)
Definition apds9960.cpp:175
bool is_gesture_enabled_() const
Definition apds9960.cpp:364
void report_gesture_(int gesture)
Definition apds9960.cpp:244
void read_color_data_(uint8_t status)
Definition apds9960.cpp:145
void process_dataset_(int up, int down, int left, int right)
Definition apds9960.cpp:282
bool is_proximity_enabled_() const
Definition apds9960.cpp:355
Base class for all binary_sensor-type classes.
void publish_state(bool new_state)
Publish a new state to the front-end.
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(uint8_t *data, size_t len) const
reads an array of bytes from the device using an I2CBus
Definition i2c.h:175
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
bool update_register(uint8_t a_register, uint8_t mask, uint8_t value)
Read a register, replace the bits in mask with those of value and write it back.
Definition i2c.cpp:95
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Compat APIs All methods below have been added for compatibility reasons.
Definition i2c.h:249
bool write_registers(const I2CRegValue *table, size_t count) const
Write each register and value of table in order, stopping at the first failure.
Definition i2c.cpp:73
uint16_t id
mopeka_std_values val[3]
ESPHOME_LOG_TAG(TAG, "apds9960")
size_t size_t pos
Definition helpers.h:1333
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
One register write for I2CDevice::write_registers(); tables of these may live in PROGMEM.
Definition i2c.h:18