ESPHome  2024.10.2
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"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.h"
6 
7 namespace esphome {
8 namespace a02yyuw {
9 
10 static const char *const TAG = "a02yyuw.sensor";
11 
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 
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 > 30) {
29  ESP_LOGV(TAG, "Distance from sensor: %f mm", distance);
30  this->publish_state(distance);
31  } else {
32  ESP_LOGW(TAG, "Invalid data read from sensor: %s", format_hex_pretty(this->buffer_).c_str());
33  }
34  } else {
35  ESP_LOGW(TAG, "checksum failed: %02x != %02x", checksum, this->buffer_[3]);
36  }
37  this->buffer_.clear();
38 }
39 
40 void A02yyuwComponent::dump_config() { LOG_SENSOR("", "A02yyuw Sensor", this); }
41 
42 } // namespace a02yyuw
43 } // namespace esphome
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:359
uint8_t checksum
Definition: bl0906.h:210
std::vector< uint8_t > buffer_
Definition: a02yyuw.h:23
bool read_byte(uint8_t *data)
Definition: uart.h:29
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7