ESPHome  2024.4.0
tof10120_sensor.cpp
Go to the documentation of this file.
1 #include "tof10120_sensor.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/hal.h"
4 #include <cinttypes>
5 
6 // Very basic support for TOF10120 distance sensor
7 
8 namespace esphome {
9 namespace tof10120 {
10 
11 static const char *const TAG = "tof10120";
12 static const uint8_t TOF10120_READ_DISTANCE_CMD[] = {0x00};
13 static const uint8_t TOF10120_DEFAULT_DELAY = 30;
14 
15 static const uint8_t TOF10120_DIR_SEND_REGISTER = 0x0e;
16 static const uint8_t TOF10120_DISTANCE_REGISTER = 0x00;
17 
18 static const uint16_t TOF10120_OUT_OF_RANGE_VALUE = 2000;
19 
21  LOG_SENSOR("", "TOF10120", this);
22  LOG_UPDATE_INTERVAL(this);
23  LOG_I2C_DEVICE(this);
24 }
25 
27 
29  if (!this->write_bytes(TOF10120_DISTANCE_REGISTER, TOF10120_READ_DISTANCE_CMD, sizeof(TOF10120_READ_DISTANCE_CMD))) {
30  ESP_LOGE(TAG, "Communication with TOF10120 failed on write");
31  this->status_set_warning();
32  return;
33  }
34 
35  uint8_t data[2];
36  if (this->write(&TOF10120_DISTANCE_REGISTER, 1) != i2c::ERROR_OK) {
37  this->status_set_warning();
38  return;
39  }
40  delay(TOF10120_DEFAULT_DELAY);
41  if (this->read(data, 2) != i2c::ERROR_OK) {
42  ESP_LOGE(TAG, "Communication with TOF10120 failed on read");
43  this->status_set_warning();
44  return;
45  }
46 
47  uint32_t distance_mm = (data[0] << 8) | data[1];
48  ESP_LOGI(TAG, "Data read: %" PRIu32 "mm", distance_mm);
49 
50  if (distance_mm == TOF10120_OUT_OF_RANGE_VALUE) {
51  ESP_LOGW(TAG, "Distance measurement out of range");
52  this->publish_state(NAN);
53  } else {
54  this->publish_state(distance_mm / 1000.0f);
55  }
56  this->status_clear_warning();
57 }
58 
59 } // namespace tof10120
60 } // namespace esphome
void status_set_warning(const char *message="unspecified")
Definition: component.cpp:151
ErrorCode read(uint8_t *data, size_t len)
reads an array of bytes from the device using an I2CBus
Definition: i2c.h:160
ErrorCode write(const uint8_t *data, size_t len, bool stop=true)
writes an array of bytes to a device using an I2CBus
Definition: i2c.h:186
No error found during execution of method.
Definition: i2c_bus.h:13
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
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:248