ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
a02yyuw.cpp
Go to the documentation of this file.
1// Datasheet https://wiki.dfrobot.com/_A02YYUW_Waterproof_Ultrasonic_Sensor_SKU_SEN0311
2
3#include "a02yyuw.h"
5#include "esphome/core/log.h"
6
7namespace esphome::a02yyuw {
8
9static const char *const TAG = "a02yyuw.sensor";
10
12 uint8_t data;
13 while (this->available() > 0) {
14 this->read_byte(&data);
15 if (this->buffer_.empty() && (data != 0xff))
16 continue;
17 buffer_.push_back(data);
18 if (this->buffer_.size() == 4)
19 this->check_buffer_();
20 }
21}
22
24 uint8_t checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
25 if (this->buffer_[3] == checksum) {
26 float distance = (this->buffer_[1] << 8) + this->buffer_[2];
27 if (distance > 30) {
28 ESP_LOGV(TAG, "Distance from sensor: %f mm", distance);
29 this->publish_state(distance);
30 } else {
31 char hex_buf[format_hex_pretty_size(4)];
32 ESP_LOGW(TAG, "Invalid data read from sensor: %s",
33 format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_.size()));
34 }
35 } else {
36 ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
37 }
38 this->buffer_.clear();
39}
40
41void A02yyuwComponent::dump_config() { LOG_SENSOR("", "A02yyuw Sensor", this); }
42
43} // namespace esphome::a02yyuw
uint8_t checksum
Definition bl0906.h:3
std::vector< uint8_t > buffer_
Definition a02yyuw.h:22
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
bool read_byte(uint8_t *data)
Definition uart.h:34
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:341
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1386