ESPHome 2026.11.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
10ESPHOME_LOG_TAG(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 this->status_set_warning(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
30 return;
31 }
32
33 uint8_t data[2];
34 if (this->write(&TOF10120_DISTANCE_REGISTER, 1) != i2c::ERROR_OK) {
35 this->status_set_warning();
36 return;
37 }
38 delay(TOF10120_DEFAULT_DELAY);
39 if (this->read(data, 2) != i2c::ERROR_OK) {
40 this->status_set_warning(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
41 return;
42 }
43
44 uint32_t distance_mm = (data[0] << 8) | data[1];
45 ESP_LOGI(TAG, "Data read: %" PRIu32 "mm", distance_mm);
46
47 if (distance_mm == TOF10120_OUT_OF_RANGE_VALUE) {
48 ESP_LOGW(TAG, "Distance measurement out of range");
49 this->publish_state(NAN);
50 } else {
51 this->publish_state(distance_mm / 1000.0f);
52 }
54}
55
56} // namespace esphome::tof10120
void status_clear_warning()
Definition component.h:296
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:195
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_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:298
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
ESPHOME_LOG_TAG(TAG, "tof10120")
void HOT delay(uint32_t ms)
Definition hal.cpp:85
static void uint32_t