ESPHome  2022.6.3
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 
5 // Very basic support for TOF10120 distance sensor
6 
7 namespace esphome {
8 namespace tof10120 {
9 
10 static const char *const TAG = "tof10120";
11 static const uint8_t TOF10120_READ_DISTANCE_CMD[] = {0x00};
12 static const uint8_t TOF10120_DEFAULT_DELAY = 30;
13 
14 static const uint8_t TOF10120_DIR_SEND_REGISTER = 0x0e;
15 static const uint8_t TOF10120_DISTANCE_REGISTER = 0x00;
16 
17 static const uint16_t TOF10120_OUT_OF_RANGE_VALUE = 2000;
18 
20  LOG_SENSOR("", "TOF10120", this);
21  LOG_UPDATE_INTERVAL(this);
22  LOG_I2C_DEVICE(this);
23 }
24 
26 
28  if (!this->write_bytes(TOF10120_DISTANCE_REGISTER, TOF10120_READ_DISTANCE_CMD, sizeof(TOF10120_READ_DISTANCE_CMD))) {
29  ESP_LOGE(TAG, "Communication with TOF10120 failed on write");
30  this->status_set_warning();
31  return;
32  }
33 
34  uint8_t data[2];
35  if (this->write(&TOF10120_DISTANCE_REGISTER, 1) != i2c::ERROR_OK) {
36  this->status_set_warning();
37  return;
38  }
39  delay(TOF10120_DEFAULT_DELAY);
40  if (this->read(data, 2) != i2c::ERROR_OK) {
41  ESP_LOGE(TAG, "Communication with TOF10120 failed on read");
42  this->status_set_warning();
43  return;
44  }
45 
46  uint32_t distance_mm = (data[0] << 8) | data[1];
47  ESP_LOGI(TAG, "Data read: %dmm", distance_mm);
48 
49  if (distance_mm == TOF10120_OUT_OF_RANGE_VALUE) {
50  ESP_LOGW(TAG, "Distance measurement out of range");
51  this->publish_state(NAN);
52  } else {
53  this->publish_state(distance_mm / 1000.0f);
54  }
55  this->status_clear_warning();
56 }
57 
58 } // namespace tof10120
59 } // namespace esphome
ErrorCode read(uint8_t *data, size_t len)
Definition: i2c.h:48
void status_clear_warning()
Definition: component.cpp:148
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:70
ErrorCode write(const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:56
void status_set_warning()
Definition: component.cpp:140
Definition: a4988.cpp:4
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:27
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition: i2c.h:109