ESPHome 2026.11.0b6
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"
5#include <cinttypes>
6
7// Very basic support for TOF10120 distance sensor
8
10
11ESPHOME_LOG_TAG(TAG, "tof10120");
12static const uint8_t TOF10120_READ_DISTANCE_CMD[] = {0x00};
13static const uint8_t TOF10120_DEFAULT_DELAY = 30;
14
15static const uint8_t TOF10120_DIR_SEND_REGISTER = 0x0e;
16static const uint8_t TOF10120_DISTANCE_REGISTER = 0x00;
17
18static 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 this->status_set_warning(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
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 this->status_set_warning(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
42 return;
43 }
44
45 uint32_t distance_mm = encode_uint16(data[0], data[1]);
46 ESP_LOGI(TAG, "Data read: %" PRIu32 "mm", distance_mm);
47
48 if (distance_mm == TOF10120_OUT_OF_RANGE_VALUE) {
49 ESP_LOGW(TAG, "Distance measurement out of range");
50 this->publish_state(NAN);
51 } else {
52 this->publish_state(distance_mm / 1000.0f);
53 }
55}
56
57} // namespace esphome::tof10120
void status_clear_warning()
Definition component.h:309
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")
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
void HOT delay(uint32_t ms)
Definition hal.cpp:85
static void uint32_t