ESPHome 2025.9.0-dev
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
5namespace esphome {
6namespace gl_r01_i2c {
7
8static const char *const TAG = "gl_r01_i2c";
9
10// Register definitions from datasheet
11static const uint8_t REG_VERSION = 0x00;
12static const uint8_t REG_DISTANCE = 0x02;
13static const uint8_t REG_TRIGGER = 0x10;
14static const uint8_t CMD_TRIGGER = 0xB0;
15static const uint8_t RESTART_CMD1 = 0x5A;
16static const uint8_t RESTART_CMD2 = 0xA5;
17static const uint8_t READ_DELAY = 40; // minimum milliseconds from datasheet to safely read measurement result
18
20 // Verify sensor presence
21 if (!this->read_byte_16(REG_VERSION, &this->version_)) {
22 ESP_LOGE(TAG, "Failed to communicate with GL-R01 I2C sensor!");
23 this->mark_failed();
24 return;
25 }
26 ESP_LOGD(TAG, "Found GL-R01 I2C with version 0x%04X", this->version_);
27}
28
30 ESP_LOGCONFIG(TAG, "GL-R01 I2C:");
31 ESP_LOGCONFIG(TAG, " Firmware Version: 0x%04X", this->version_);
32 LOG_I2C_DEVICE(this);
33 LOG_SENSOR(" ", "Distance", this);
34}
35
37 // Trigger a new measurement
38 if (!this->write_byte(REG_TRIGGER, CMD_TRIGGER)) {
39 ESP_LOGE(TAG, "Failed to trigger measurement!");
40 this->status_set_warning();
41 return;
42 }
43
44 // Schedule reading the result after the read delay
45 this->set_timeout(READ_DELAY, [this]() { this->read_distance_(); });
46}
47
49 uint16_t distance = 0;
50 if (!this->read_byte_16(REG_DISTANCE, &distance)) {
51 ESP_LOGE(TAG, "Failed to read distance value!");
52 this->status_set_warning();
53 return;
54 }
55
56 if (distance == 0xFFFF) {
57 ESP_LOGW(TAG, "Invalid measurement received!");
58 this->status_set_warning();
59 } else {
60 ESP_LOGV(TAG, "Distance: %umm", distance);
61 this->publish_state(distance);
63 }
64}
65
66} // namespace gl_r01_i2c
67} // namespace esphome
virtual void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
bool write_byte(uint8_t a_register, uint8_t data, bool stop=true)
Definition i2c.h:266
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:250
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7