ESPHome
2025.9.0-dev
Loading...
Searching...
No Matches
esphome
components
a01nyub
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
"
4
#include "
esphome/core/helpers.h
"
5
#include "
esphome/core/log.h
"
6
7
namespace
esphome
{
8
namespace
a01nyub {
9
10
static
const
char
*
const
TAG =
"a01nyub.sensor"
;
11
12
void
A01nyubComponent::loop
() {
13
uint8_t data;
14
while
(this->
available
() > 0) {
15
this->
read_byte
(&data);
16
if
(this->
buffer_
.empty() && (data != 0xff))
17
continue
;
18
buffer_
.push_back(data);
19
if
(this->
buffer_
.size() == 4)
20
this->
check_buffer_
();
21
}
22
}
23
24
void
A01nyubComponent::check_buffer_
() {
25
uint8_t
checksum
= this->
buffer_
[0] + this->
buffer_
[1] + this->
buffer_
[2];
26
if
(this->buffer_[3] ==
checksum
) {
27
float
distance = (this->buffer_[1] << 8) + this->buffer_[2];
28
if
(distance > 280) {
29
float
meters = distance / 1000.0;
30
ESP_LOGV(TAG,
"Distance from sensor: %f mm, %f m"
, distance, meters);
31
this->
publish_state
(meters);
32
}
else
{
33
ESP_LOGW(TAG,
"Invalid data read from sensor: %s"
,
format_hex_pretty
(this->buffer_).c_str());
34
}
35
}
else
{
36
ESP_LOGW(TAG,
"checksum failed: %02x != %02x"
,
checksum
, this->buffer_[3]);
37
}
38
this->buffer_.clear();
39
}
40
41
void
A01nyubComponent::dump_config
() { LOG_SENSOR(
""
,
"A01nyub Sensor"
,
this
); }
42
43
}
// namespace a01nyub
44
}
// namespace esphome
a01nyub.h
checksum
uint8_t checksum
Definition
bl0906.h:3
esphome::a01nyub::A01nyubComponent::loop
void loop() override
Definition
a01nyub.cpp:12
esphome::a01nyub::A01nyubComponent::dump_config
void dump_config() override
Definition
a01nyub.cpp:41
esphome::a01nyub::A01nyubComponent::check_buffer_
void check_buffer_()
Definition
a01nyub.cpp:24
esphome::a01nyub::A01nyubComponent::buffer_
std::vector< uint8_t > buffer_
Definition
a01nyub.h:23
esphome::sensor::Sensor::publish_state
void publish_state(float state)
Publish a new state to the front-end.
Definition
sensor.cpp:45
esphome::uart::UARTDevice::read_byte
bool read_byte(uint8_t *data)
Definition
uart.h:29
esphome::uart::UARTDevice::available
int available()
Definition
uart.h:41
helpers.h
log.h
esphome
Providing packet encoding functions for exchanging data with a remote host.
Definition
a01nyub.cpp:7
esphome::format_hex_pretty
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition
helpers.cpp:280
Generated by
1.12.0