ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
gl_r01_i2c.cpp
Go to the documentation of this file.
1#include "esphome/core/log.h"
2#include "esphome/core/hal.h"
3#include "gl_r01_i2c.h"
4
6
7static const char *const TAG = "gl_r01_i2c";
8
9// Register definitions from datasheet
10static const uint8_t REG_VERSION = 0x00;
11static const uint8_t REG_DISTANCE = 0x02;
12static const uint8_t REG_TRIGGER = 0x10;
13static const uint8_t CMD_TRIGGER = 0xB0;
14static const uint8_t RESTART_CMD1 = 0x5A;
15static const uint8_t RESTART_CMD2 = 0xA5;
16static const uint8_t READ_DELAY = 40; // minimum milliseconds from datasheet to safely read measurement result
17
19 // Verify sensor presence
20 if (!this->read_byte_16(REG_VERSION, &this->version_)) {
21 ESP_LOGE(TAG, "Failed to communicate with GL-R01 I2C sensor!");
22 this->mark_failed();
23 return;
24 }
25 ESP_LOGD(TAG, "Found GL-R01 I2C with version 0x%04X", this->version_);
26}
27
29 ESP_LOGCONFIG(TAG,
30 "GL-R01 I2C:\n"
31 " Firmware Version: 0x%04X",
32 this->version_);
33 LOG_I2C_DEVICE(this);
34 LOG_SENSOR(" ", "Distance", this);
35}
36
38 // Trigger a new measurement
39 if (!this->write_byte(REG_TRIGGER, CMD_TRIGGER)) {
40 ESP_LOGE(TAG, "Failed to trigger measurement!");
41 this->status_set_warning();
42 return;
43 }
44
45 // Schedule reading the result after the read delay
46 this->set_timeout(READ_DELAY, [this]() { this->read_distance_(); });
47}
48
50 uint16_t distance = 0;
51 if (!this->read_byte_16(REG_DISTANCE, &distance)) {
52 ESP_LOGE(TAG, "Failed to read distance value!");
53 this->status_set_warning();
54 return;
55 }
56
57 if (distance == 0xFFFF) {
58 ESP_LOGW(TAG, "Invalid measurement received!");
59 this->status_set_warning();
60 } else {
61 ESP_LOGV(TAG, "Distance: %umm", distance);
62 this->publish_state(distance);
64 }
65}
66
67} // namespace esphome::gl_r01_i2c
void mark_failed()
Mark this component as failed.
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:510
void status_clear_warning()
Definition component.h:306
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:265
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:249
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68