ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
a01nyub.cpp
Go to the documentation of this file.
1// Datasheet https://wiki.dfrobot.com/A01NYUB%20Waterproof%20Ultrasonic%20Sensor%20SKU:%20SEN0313
2
3#include "a01nyub.h"
5#include "esphome/core/log.h"
6
7namespace esphome::a01nyub {
8
9ESPHOME_LOG_TAG(TAG, "a01nyub.sensor");
10
12 this->read_available([this](uint8_t data) {
13 if (this->buffer_.empty() && (data != 0xff))
14 return;
15 buffer_.push_back(data);
16 if (this->buffer_.size() == 4)
17 this->check_buffer_();
18 });
19}
20
22 uint8_t checksum = this->buffer_[0] + this->buffer_[1] + this->buffer_[2];
23 if (this->buffer_[3] == checksum) {
24 float distance = (this->buffer_[1] << 8) + this->buffer_[2];
25 if (distance > 280) {
26 float meters = distance / 1000.0f;
27 ESP_LOGV(TAG, "Distance from sensor: %f mm, %f m", distance, meters);
28 this->publish_state(meters);
29 } else {
30 char hex_buf[format_hex_pretty_size(4)];
31 ESP_LOGW(TAG, "Invalid data read from sensor: %s",
32 format_hex_pretty_to(hex_buf, this->buffer_.data(), this->buffer_.size()));
33 }
34 } else {
35 ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
36 }
37 this->buffer_.clear();
38}
39
40void A01nyubComponent::dump_config() { LOG_SENSOR("", "A01nyub Sensor", this); }
41
42} // namespace esphome::a01nyub
uint8_t checksum
Definition bl0906.h:3
std::vector< uint8_t > buffer_
Definition a01nyub.h:22
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
ESPHOME_LOG_TAG(TAG, "a01nyub.sensor")
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:498
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:1609