ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
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
9
10static const char *const TAG = "tof10120";
11static const uint8_t TOF10120_READ_DISTANCE_CMD[] = {0x00};
12static const uint8_t TOF10120_DEFAULT_DELAY = 30;
13
14static const uint8_t TOF10120_DIR_SEND_REGISTER = 0x0e;
15static const uint8_t TOF10120_DISTANCE_REGISTER = 0x00;
16
17static 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, ESP_LOG_MSG_COMM_FAIL);
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, ESP_LOG_MSG_COMM_FAIL);
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: %" PRIu32 "mm", 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 }
56}
57
58} // namespace esphome::tof10120
void status_clear_warning()
Definition component.h:289
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:183
ErrorCode read(uint8_t *data, size_t len) const
reads an array of bytes from the device using an I2CBus
Definition i2c.h:163
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:251
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:14
void HOT delay(uint32_t ms)
Definition hal.cpp:85
static void uint32_t